diff --git a/.gitea/workflows/rust-build.yml b/.gitea/workflows/rust-build.yml index 4addfa7df..d055b38be 100644 --- a/.gitea/workflows/rust-build.yml +++ b/.gitea/workflows/rust-build.yml @@ -35,4 +35,8 @@ jobs: # --all-features above never builds a crate with a default feature off. scrypt without # `std` is its caller-supplied-memory configuration, and it once did not compile. - name: Test bouncycastle-digest without std - run: cargo test -p bouncycastle-digest --no-default-features + # The vector suites need bc-test-data, which this job does not check out. + # Every target is built first, so that one that stops compiling without std is seen. + run: | + cargo test -p bouncycastle-digest --no-default-features --no-run + cargo test -p bouncycastle-digest --no-default-features --lib --test scrypt_scrypt_caller_memory_tests diff --git a/.github/workflows/oaep-ct.yml b/.github/workflows/oaep-ct.yml new file mode 100644 index 000000000..efaf1de7f --- /dev/null +++ b/.github/workflows/oaep-ct.yml @@ -0,0 +1,29 @@ +name: OAEP Constant-Time Decode + +on: + pull_request: + +permissions: + contents: read + +concurrency: + group: oaep-ct-${{ github.event.pull_request.number || github.ref }} + cancel-in-progress: true + +jobs: + oaep-ct: + if: github.repository == 'bcgit/bc-rust' + name: oaep-ct + runs-on: ubuntu-latest + steps: + - name: Checkout code + uses: actions/checkout@v4 + + - name: Install valgrind + run: sudo apt-get update && sudo apt-get install -y valgrind + + - name: Install nightly with rust-src + run: rustup toolchain install nightly --profile minimal --component rust-src + + - name: Check the EME-OAEP decode under memcheck and in the Cortex-M0 and RISC-V 32I assembly + run: ./dev_scripts/check_oaep_ct.sh diff --git a/.github/workflows/rsa-ct-stack.yml b/.github/workflows/rsa-ct-stack.yml new file mode 100644 index 000000000..e2e33277b --- /dev/null +++ b/.github/workflows/rsa-ct-stack.yml @@ -0,0 +1,29 @@ +name: RSA Constant-Time Setup and Stack Wipes + +on: + pull_request: + +permissions: + contents: read + +concurrency: + group: rsa-ct-stack-${{ github.event.pull_request.number || github.ref }} + cancel-in-progress: true + +jobs: + rsa-ct-stack: + if: github.repository == 'bcgit/bc-rust' + name: rsa-ct-stack + runs-on: ubuntu-latest + steps: + - name: Checkout code + uses: actions/checkout@v4 + + - name: Install valgrind + run: sudo apt-get update && sudo apt-get install -y valgrind + + - name: Check the RSA private-key arithmetic under memcheck with the key undefined + run: ./dev_scripts/check_rsa_ct.sh + + - name: Search the stack each RSA private-key operation used for the key + run: ./dev_scripts/check_rsa_stack.sh diff --git a/.github/workflows/rust-build.yml b/.github/workflows/rust-build.yml index 4d2d0c247..807125e18 100644 --- a/.github/workflows/rust-build.yml +++ b/.github/workflows/rust-build.yml @@ -28,4 +28,8 @@ jobs: # --all-features above never builds a crate with a default feature off. scrypt without # `std` is its caller-supplied-memory configuration, and it once did not compile. - name: Test bouncycastle-digest without std - run: cargo test -p bouncycastle-digest --no-default-features + # The vector suites need bc-test-data, which this job does not check out. + # Every target is built first, so that one that stops compiling without std is seen. + run: | + cargo test -p bouncycastle-digest --no-default-features --no-run + cargo test -p bouncycastle-digest --no-default-features --lib --test scrypt_scrypt_caller_memory_tests diff --git a/.gitignore b/.gitignore index 41d845b5e..9feb9b52e 100644 --- a/.gitignore +++ b/.gitignore @@ -22,3 +22,6 @@ custom_mutants_output/ .claude/settings.local.json .claude 2/ dev_scripts/aes_ct_harness/Cargo.lock +dev_scripts/oaep_ct_harness/Cargo.lock +dev_scripts/rsa_ct_harness/Cargo.lock +dev_scripts/rsa_stack_harness/Cargo.lock diff --git a/CLAUDE.md b/CLAUDE.md index cab738e75..7b103e894 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -43,7 +43,7 @@ Revisit this section at the first non-alpha release. - Builds on Rust **stable**: there is no toolchain pin, and no crate enables a `#![feature(...)]` gate, so nightly-only tooling (`-Z` flags and the like) is not available. CI builds, tests and docs on stable; only the - `rustfmt` job and the AES assembly check (`-Zbuild-std=core` for targets without a shipped `core`) install + `rustfmt` job and the AES and OAEP assembly checks (`-Zbuild-std=core` for targets without a shipped `core`) install nightly. - 2024 edition (set workspace-wide in the root `Cargo.toml`). - Minimum Rust is 1.88: `rust-version` in the root `Cargo.toml`, inherited by `bouncycastle-utils` (the crate that @@ -127,7 +127,7 @@ crypto// A family crate holds its primitives as modules, each with the layout it had as a crate: `bouncycastle-hybrid` (`crypto/hybrid`: `hpke`), `bouncycastle-digest` (`crypto/digest`: `blake2`, -`concatkdf`, `pbkdf2`, `ripemd`, `scrypt`, `sm3`, `x963kdf`), `bouncycastle-symmetric` +`blake3`, `concatkdf`, `pbkdf2`, `ripemd`, `scrypt`, `sha1`, `sm3`, `x963kdf`), `bouncycastle-symmetric` (`crypto/symmetric`: `aria`, `ascon`, `camellia`, `chacha20`, `chacha20_poly1305_aead`, `kbkdf`, `poly1305`, `sm4`, `tdes`) and `bouncycastle-pqc` (`crypto/pqc`: `mldsa`, `mldsa_lowmemory`, `mlkem`, `mlkem_lowmemory`, and the `mldsa_common` / `mlkem_common` modules the @@ -468,11 +468,12 @@ external vector suites — is specified in QUALITY_AND_STYLE.md and CONTRIBUTING ## CI -Six workflows under `.github/workflows/`, all triggered by pull requests: +Eight workflows under `.github/workflows/`, all triggered by pull requests: - `rust-build.yml`: `cargo build --workspace --all-targets --all-features` on stable, then - `cargo test -p bouncycastle-digest --no-default-features`, since `--all-features` never - builds a crate with a default feature off. + `cargo test -p bouncycastle-digest --no-default-features` on the crate's unit tests and scrypt's + caller-memory tests (the vector suites need bc-test-data, which that job does not check out), + since `--all-features` never builds a crate with a default feature off. - `rust-test.yml`: `cargo test --all` on stable, with `bcgit/bc-test-data` and `C2SP/wycheproof` checked out beside the repository. Wycheproof is pinned to a commit (`ref:` in the workflow), so that a change upstream does not fail an unrelated PR: a vector suite that is strict about the @@ -483,6 +484,18 @@ Six workflows under `.github/workflows/`, all triggered by pull requests: - `aes-ct-asm.yml`: `dev_scripts/check_aes_ct_asm.sh` on **nightly** with `rust-src`: builds `dev_scripts/aes_ct_harness` for thumbv6m and riscv32i and greps the assembly of the AES round-key widening for a multiply, call or branch (see the comment on `PlaneWord::splat` in the aes crate). +- `oaep-ct.yml`: `dev_scripts/check_oaep_ct.sh` with valgrind and **nightly** `rust-src`: runs + `dev_scripts/oaep_ct_harness` (the EME-OAEP decode, included by path) under memcheck with the encoded + message undefined, with a variable-time control, and greps its thumbv6m and riscv32i assembly for a + multiply, divide or unexpected call. +- `rsa-ct-stack.yml`: two checks of `crypto/rsa`, on the runner's stable toolchain. `dev_scripts/check_rsa_ct.sh` + with valgrind runs `dev_scripts/rsa_ct_harness` (the Montgomery setup over a secret modulus, the checked + CRT and a key constructor's congruences; the last two through the crate's `ct_harness` module, which exists + only under `--cfg bouncycastle_rsa_ct_harness`) under memcheck with the key undefined, with controls that must + be reported. `dev_scripts/check_rsa_stack.sh` runs `dev_scripts/rsa_stack_harness`, which paints the stack, runs + each private-key operation and searches what it used for the key and what was derived from it. The second is + sized by measurement for an x86-64 release build, so a new compiler that lays frames out deeper fails it: that + is the check working, and the fix is to re-measure the wipe sizes, not to drop the step. - `publish_doc_benches_to_ghpages.yaml`: builds rustdoc and runs `quality_stats.sh`; on `main` it also publishes docs and code stats to GitHub Pages (`https://bcgit.github.io/bc-rust/`). Its bench step is commented out because the benches are too slow on the hosted runner, so benchmark figures come from a @@ -491,8 +504,8 @@ Six workflows under `.github/workflows/`, all triggered by pull requests: `cargo test --all` is the workspace run, so a failing test does block a PR; what CI does not run is `cargo mutants`, the CLI shell tests under `cli/tests/`, or rustdoc with warnings denied. -The gitea origin has its own copies of the five pull-request checks under `.gitea/workflows/` -(there is no Pages job). They differ from the GitHub ones in two ways: the toolchain is installed +The gitea origin has its own copies of five of the pull-request checks under `.gitea/workflows/` +(there is no Pages job, and `oaep-ct.yml` and `rsa-ct-stack.yml` have no gitea copy). They differ from the GitHub ones in two ways: the toolchain is installed with `rustup` in a shell step, and the test job takes its vectors from the runner's read-only `/bc-test-data` and `/wycheproof` mounts, failing if either is missing. Wycheproof's are read out of the mounted clone at the pinned commit (`git archive`), wherever the clone's `HEAD` is, so the diff --git a/Cargo.toml b/Cargo.toml index ecf0f3e85..09c27a565 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -28,6 +28,7 @@ bouncycastle-dhkem = { path = "./crypto/dhkem" } bouncycastle-hybrid = { path = "./crypto/hybrid" } bouncycastle-pqc = { path = "./crypto/pqc" } bouncycastle-rng = { path = "./crypto/rng" } +bouncycastle-rsa = { path = "./crypto/rsa" } bouncycastle-sha2 = { path = "./crypto/sha2" } bouncycastle-sha3 = { path = "./crypto/sha3" } bouncycastle-sm2 = { path = "./crypto/sm2" } @@ -73,6 +74,7 @@ bouncycastle-dhkem.workspace = true bouncycastle-hybrid.workspace = true bouncycastle-pqc.workspace = true bouncycastle-rng.workspace = true +bouncycastle-rsa.workspace = true bouncycastle-sha2.workspace = true bouncycastle-sha3.workspace = true bouncycastle-sm2.workspace = true diff --git a/alpha_0.1.4_release_notes.md b/alpha_0.1.4_release_notes.md index db9dbfc30..cb07d8169 100644 --- a/alpha_0.1.4_release_notes.md +++ b/alpha_0.1.4_release_notes.md @@ -102,6 +102,32 @@ `kbkdf-double-pipeline`, `kbkdf-kmac128` and `kbkdf-kmac256` CLI commands. * `bouncycastle-dhkem` -- the generic DHKEM is a crate of its own, apart from HPKE, and gains `AuthEncap` and `AuthDecap`. Its `_out` functions return the number of bytes written. +* SHA-1 -- `bouncycastle_digest::sha1`, FIPS 180-4's SHA-1 on the `Hash` traits, for interoperation with what already + uses it (an older peer's RSA-OAEP hash or MGF1, a fingerprint): not collision resistant, so it is credited with + no security strength (`SecurityStrength::None`). Checked against NIST's CAVP SHAVS vectors and RFC 3174's; the + `sha1` CLI command. It does not carry `CollisionResistantHash`, so the RSA signature schemes verify over it and + do not sign, short of `hazmat::WithoutCollisionResistance`. +* RSA -- `bouncycastle-rsa`: RSASSA-PKCS1-v1_5 and RSASSA-PSS (RFC 8017 Section 8) on the signature roles, RSASVE + (NIST SP 800-56B Rev. 2 Section 7.2.1) on the KEM roles, its secret value raw or through HKDF, and key generation + by FIPS 186-5 Appendix A.1.3 with 25 Miller-Rabin rounds (FIPS 140-3 IG C.F), at RSA-2048, 3072, 4096 and 8192; + RSA-1024 and RSA-1536 verify signatures and nothing else. A public key encodes as `n || e` and a private key as + `p || q || dP || dQ || qInv || e`, with `e` in 8 big-endian bytes, and a modulus must have exactly its size's bit + length. A private key's constructor and decoder refuse components that do not belong together with `e` (RFC 8017 + Section 3.2), in constant time; `RsaPrivateComponents::validate` is SP 800-56B Rev. 2 Section 6.4.1.4.3's + validation of a key pair, primality included, for a key from elsewhere. The result of every private-key + operation is checked against `e` before it is released (`SignatureError::ComputationFault`, or the operation's + one decryption error). A non-empty `ctx` is refused with `SignatureError::LengthError`, RSA having no context + input. Private-key operations wipe the stack they used, sized for an optimised x86-64 build; a key the caller + moves out of the `Result` it was returned in is the caller's to wipe. The `rsa-` and `rsasve-` CLI + commands. Two checks, run by CI and by hand: `dev_scripts/check_rsa_ct.sh` puts the CRT and the constructor's + congruences under memcheck with the key undefined, and `dev_scripts/check_rsa_stack.sh` searches the stack each + private-key operation used for the key. +* RSAES-OAEP -- RFC 8017 Section 7.1 key transport on the RSA key-establishment keys, under `OaepParams` + (label hash, MGF1 hash, label): as a KEM that draws the key (KTS-OAEP-basic, SP 800-56B Rev. 2) and, through + the new `core::key_transport_key` roles, for a key the caller holds; the `rsa-oaep-` CLI commands. The hashes + are RFC 8017's seven (SHA-1, SHA-224, SHA-256, SHA-384, SHA-512, SHA-512/224, SHA-512/256), a sealed trait + `OaepHash`. `dev_scripts/check_oaep_ct.sh`, run on pull requests, puts the decoding under memcheck with the encoded + message undefined and reads its Cortex-M0 and RISC-V 32I assembly. ## Minor features / bug fixes diff --git a/cli/src/main.rs b/cli/src/main.rs index 8b50b9dc3..af3445c2e 100644 --- a/cli/src/main.rs +++ b/cli/src/main.rs @@ -30,7 +30,11 @@ mod ofb_cmd; mod pbkdf2_cmd; mod ripemd_cmd; mod rng_cmd; +mod rsa_cmd; +mod rsa_oaep_cmd; +mod rsasve_cmd; mod scrypt_cmd; +mod sha1_cmd; mod sha2_cmd; mod sha3_cmd; mod sm2_cmd; @@ -64,6 +68,9 @@ use crate::mac_cmd::HMACVariant; use crate::mldsa_cmd::{MLDSAAction, PreHashAlg}; use crate::ripemd_cmd::RIPEMDVariant; use crate::rng_cmd::DrbgHash; +use crate::rsa_cmd::{RSAAction, RSAHash, RSAScheme}; +use crate::rsa_oaep_cmd::{OaepArgs, RSAOAEPAction, RSAOAEPHash}; +use crate::rsasve_cmd::RSASVEAction; use crate::sha2_cmd::SHA2Variant; use crate::sha3_cmd::{SHA3Variant, Strength}; use crate::sm2_cmd::SM2Action; @@ -4527,6 +4534,414 @@ enum Subcommands { x: bool, }, + /// RSASVE over RSA-2048: the RSA KEM of SP 800-56B Rev. 2 Section 7.2.1 (BC FIPS Java's KTS_SVE / + /// RSA-KAS-KEM, OpenSSL's "RSASVE" kem op). `keygen` (FIPS 186-5 A.1.3, e = 65537) writes the + /// private key to stdout and the public key to `--pkfile`; key files use the same raw encoding + /// as rsa-2048's. The shared secret is the raw 256-byte secret value Z, to be passed through a + /// KDF before use. + RSASVE_2048 { + action: RSASVEAction, + + #[arg(long)] + /// The private key file (in hex or binary) for decaps + skfile: Option, + + #[arg(long)] + /// The public key file (in hex or binary) for encaps, or to write the generated public + /// key to for keygen + pkfile: Option, + + #[arg(long)] + /// The ciphertext value file (in hex or binary) either for encaps to output to, or for + /// decaps to read from. + ctfile: Option, + + #[arg(short)] + /// Output in hex format. + x: bool, + }, + + /// RSASVE over RSA-3072. See rsasve-2048. + RSASVE_3072 { + action: RSASVEAction, + + #[arg(long)] + /// The private key file (in hex or binary) for decaps + skfile: Option, + + #[arg(long)] + /// The public key file (in hex or binary) for encaps, or to write the generated public + /// key to for keygen + pkfile: Option, + + #[arg(long)] + /// The ciphertext value file (in hex or binary) either for encaps to output to, or for + /// decaps to read from. + ctfile: Option, + + #[arg(short)] + /// Output in hex format. + x: bool, + }, + + /// RSASVE over RSA-4096. See rsasve-2048. + RSASVE_4096 { + action: RSASVEAction, + + #[arg(long)] + /// The private key file (in hex or binary) for decaps + skfile: Option, + + #[arg(long)] + /// The public key file (in hex or binary) for encaps, or to write the generated public + /// key to for keygen + pkfile: Option, + + #[arg(long)] + /// The ciphertext value file (in hex or binary) either for encaps to output to, or for + /// decaps to read from. + ctfile: Option, + + #[arg(short)] + /// Output in hex format. + x: bool, + }, + + /// RSASVE over RSA-8192. See rsasve-2048. + RSASVE_8192 { + action: RSASVEAction, + + #[arg(long)] + /// The private key file (in hex or binary) for decaps + skfile: Option, + + #[arg(long)] + /// The public key file (in hex or binary) for encaps, or to write the generated public + /// key to for keygen + pkfile: Option, + + #[arg(long)] + /// The ciphertext value file (in hex or binary) either for encaps to output to, or for + /// decaps to read from. + ctfile: Option, + + #[arg(short)] + /// Output in hex format. + x: bool, + }, + + /// RSAES-OAEP key transport over RSA-2048 (RFC 8017 Section 7.1, SP 800-56B Rev. 2 Section 7.2.2), on + /// rsasve-2048's keys and key files. `encaps` / `decaps` draw and recover a 32-byte key + /// (KTS-OAEP-basic); `transport` / `recover` carry a key supplied on stdin. The label hash + /// is `--hash`, MGF1's is `--mgf-hash` (the same unless given), and both sides give the same + /// `--label`. + RSA_OAEP_2048 { + action: RSAOAEPAction, + + #[arg(long, value_enum, default_value = "sha256")] + /// The hash of the label. + hash: RSAOAEPHash, + + #[arg(long, value_enum)] + /// The hash under MGF1; the label's hash if not given. + mgf_hash: Option, + + #[arg(long)] + /// The label, in hex; empty if not given. + label: Option, + + #[arg(long)] + /// The private key file (in hex or binary) for decaps and recover + skfile: Option, + + #[arg(long)] + /// The public key file (in hex or binary) for encaps and transport, or to write the + /// generated public key to for keygen + pkfile: Option, + + #[arg(long)] + /// The ciphertext file (in hex or binary), for encaps and transport to write and for + /// decaps and recover to read. + ctfile: Option, + + #[arg(short)] + /// Output in hex format. + x: bool, + }, + + /// RSAES-OAEP key transport over RSA-3072. See rsa-oaep-2048. + RSA_OAEP_3072 { + action: RSAOAEPAction, + + #[arg(long, value_enum, default_value = "sha256")] + /// The hash of the label. + hash: RSAOAEPHash, + + #[arg(long, value_enum)] + /// The hash under MGF1; the label's hash if not given. + mgf_hash: Option, + + #[arg(long)] + /// The label, in hex; empty if not given. + label: Option, + + #[arg(long)] + /// The private key file (in hex or binary) for decaps and recover + skfile: Option, + + #[arg(long)] + /// The public key file (in hex or binary) for encaps and transport, or to write the + /// generated public key to for keygen + pkfile: Option, + + #[arg(long)] + /// The ciphertext file (in hex or binary), for encaps and transport to write and for + /// decaps and recover to read. + ctfile: Option, + + #[arg(short)] + /// Output in hex format. + x: bool, + }, + + /// RSAES-OAEP key transport over RSA-4096. See rsa-oaep-2048. + RSA_OAEP_4096 { + action: RSAOAEPAction, + + #[arg(long, value_enum, default_value = "sha256")] + /// The hash of the label. + hash: RSAOAEPHash, + + #[arg(long, value_enum)] + /// The hash under MGF1; the label's hash if not given. + mgf_hash: Option, + + #[arg(long)] + /// The label, in hex; empty if not given. + label: Option, + + #[arg(long)] + /// The private key file (in hex or binary) for decaps and recover + skfile: Option, + + #[arg(long)] + /// The public key file (in hex or binary) for encaps and transport, or to write the + /// generated public key to for keygen + pkfile: Option, + + #[arg(long)] + /// The ciphertext file (in hex or binary), for encaps and transport to write and for + /// decaps and recover to read. + ctfile: Option, + + #[arg(short)] + /// Output in hex format. + x: bool, + }, + + /// RSAES-OAEP key transport over RSA-8192. See rsa-oaep-2048. + RSA_OAEP_8192 { + action: RSAOAEPAction, + + #[arg(long, value_enum, default_value = "sha256")] + /// The hash of the label. + hash: RSAOAEPHash, + + #[arg(long, value_enum)] + /// The hash under MGF1; the label's hash if not given. + mgf_hash: Option, + + #[arg(long)] + /// The label, in hex; empty if not given. + label: Option, + + #[arg(long)] + /// The private key file (in hex or binary) for decaps and recover + skfile: Option, + + #[arg(long)] + /// The public key file (in hex or binary) for encaps and transport, or to write the + /// generated public key to for keygen + pkfile: Option, + + #[arg(long)] + /// The ciphertext file (in hex or binary), for encaps and transport to write and for + /// decaps and recover to read. + ctfile: Option, + + #[arg(short)] + /// Output in hex format. + x: bool, + }, + + /// RSA-1024 signature verification (RFC 8017 Section 8.2), PKCS#1 v1.5 only. Verification-only: this + /// crate has no RSA-1024 private key type at all. See rsa-2048 for --scheme/--hash. + RSA_1024 { + #[arg(long, value_enum)] + /// The signature scheme: only `pkcs1v15` is available at this modulus size. + scheme: RSAScheme, + + #[arg(long, value_enum)] + /// The message digest: `sha256` or `sha384` only at this modulus size. + hash: RSAHash, + + #[arg(long)] + /// The public key file (in hex or binary) for verifying + pkfile: Option, + + #[arg(long)] + /// The signature value file (in hex or binary) for verifying + sigfile: Option, + }, + + /// RSA-1536 signature verification (RFC 8017 Section 8.2), PKCS#1 v1.5 only. Verification-only: this + /// crate has no RSA-1536 private key type at all. See rsa-2048 for --scheme/--hash. + RSA_1536 { + #[arg(long, value_enum)] + /// The signature scheme: only `pkcs1v15` is available at this modulus size. + scheme: RSAScheme, + + #[arg(long, value_enum)] + /// The message digest: `sha256`, `sha384`, or `sha512` at this modulus size. + hash: RSAHash, + + #[arg(long)] + /// The public key file (in hex or binary) for verifying + pkfile: Option, + + #[arg(long)] + /// The signature value file (in hex or binary) for verifying + sigfile: Option, + }, + + /// RSA-2048 key generation, signing and verification: RSASSA-PKCS1-v1_5 (RFC 8017 Section 8.2) or + /// RSASSA-PSS (RFC 8017 Section 8.1, or RFC 8702 Section 3.2.1 with `--hash shake128`), selected by + /// `--scheme`/`--hash`. PSS draws a fresh salt from the OS RNG each time it signs. `keygen` + /// (FIPS 186-5 A.1.3, e = 65537) writes the private key to stdout and the public key to + /// `--pkfile`. Private/public key files use this crate's own raw fixed-width encoding (see + /// `RsaPrivateComponents`/`RsaPublicComponents`'s `# Encoding` docs), not PEM or ASN.1 DER. + RSA_2048 { + action: RSAAction, + + #[arg(long, value_enum)] + /// The signature scheme. + scheme: RSAScheme, + + #[arg(long, value_enum)] + /// The message digest: `sha256`, `sha384`, `sha512`, or (PSS only) `shake128`. + hash: RSAHash, + + #[arg(long)] + /// The private key file (in hex or binary) for signing + skfile: Option, + + #[arg(long)] + /// The public key file (in hex or binary) for verifying, or to write the generated public + /// key to for keygen + pkfile: Option, + + #[arg(long)] + /// The signature value file (in hex or binary) for verifying + sigfile: Option, + + #[arg(short)] + /// Output in hex format. + x: bool, + }, + + /// RSA-3072 signing/verification. See rsa-2048. + RSA_3072 { + action: RSAAction, + + #[arg(long, value_enum)] + /// The signature scheme. + scheme: RSAScheme, + + #[arg(long, value_enum)] + /// The message digest: `sha256`, `sha384`, `sha512`, or (PSS only) `shake128`. + hash: RSAHash, + + #[arg(long)] + /// The private key file (in hex or binary) for signing + skfile: Option, + + #[arg(long)] + /// The public key file (in hex or binary) for verifying, or to write the generated public + /// key to for keygen + pkfile: Option, + + #[arg(long)] + /// The signature value file (in hex or binary) for verifying + sigfile: Option, + + #[arg(short)] + /// Output in hex format. + x: bool, + }, + + /// RSA-4096 signing/verification. See rsa-2048; note `--hash shake256` (not shake128) is the + /// SHAKE choice wired up at this modulus size (RFC 8702 Section 5). + RSA_4096 { + action: RSAAction, + + #[arg(long, value_enum)] + /// The signature scheme. + scheme: RSAScheme, + + #[arg(long, value_enum)] + /// The message digest: `sha256`, `sha384`, `sha512`, or (PSS only) `shake256`. + hash: RSAHash, + + #[arg(long)] + /// The private key file (in hex or binary) for signing + skfile: Option, + + #[arg(long)] + /// The public key file (in hex or binary) for verifying, or to write the generated public + /// key to for keygen + pkfile: Option, + + #[arg(long)] + /// The signature value file (in hex or binary) for verifying + sigfile: Option, + + #[arg(short)] + /// Output in hex format. + x: bool, + }, + + /// RSA-8192 signing/verification. See rsa-2048; no PSS-SHAKE variant is wired up at this + /// modulus size (no Wycheproof vectors exist for it, and RFC 8702 Section 5's "4096-bit or larger" + /// SHAKE256 recommendation is already covered by rsa-4096). + RSA_8192 { + action: RSAAction, + + #[arg(long, value_enum)] + /// The signature scheme. + scheme: RSAScheme, + + #[arg(long, value_enum)] + /// The message digest: `sha256`, `sha384`, or `sha512`. + hash: RSAHash, + + #[arg(long)] + /// The private key file (in hex or binary) for signing + skfile: Option, + + #[arg(long)] + /// The public key file (in hex or binary) for verifying, or to write the generated public + /// key to for keygen + pkfile: Option, + + #[arg(long)] + /// The signature value file (in hex or binary) for verifying + sigfile: Option, + + #[arg(short)] + /// Output in hex format. + x: bool, + }, + /// The SM2 Digital Signature Algorithm (GB/T 32918.2-2016; draft-shen-sm2-ecdsa-02 S5), /// randomised only (the standard specifies no deterministic scheme). `--idfile` is mandatory /// for signing and verifying: it carries the signer's identity IDA (S5.5), which every SM2 @@ -4588,6 +5003,15 @@ enum Subcommands { x: bool, }, + /// Perform SHA-1 (FIPS 180-4) of the content provided on stdin. SHA-1 is not collision + /// resistant; this is for checking against existing digests. + /// Supports streaming update for low memory footprint. + SHA1 { + #[arg(short)] + /// Output the hashes in hex format. + x: bool, + }, + /// Perform SM3 of the content provided on stdin. /// Supports streaming update for low memory footprint. SM3 { @@ -8466,6 +8890,120 @@ fn run() { Some(Subcommands::SHAKE256 { length, x }) => { sha3_cmd::shake_cmd(Strength::Bits256, *length, *x); } + Some(Subcommands::RSASVE_2048 { action, skfile, pkfile, ctfile, x }) => { + rsasve_cmd::rsasve_2048_cmd(action, skfile, pkfile, ctfile, *x); + } + Some(Subcommands::RSASVE_3072 { action, skfile, pkfile, ctfile, x }) => { + rsasve_cmd::rsasve_3072_cmd(action, skfile, pkfile, ctfile, *x); + } + Some(Subcommands::RSASVE_4096 { action, skfile, pkfile, ctfile, x }) => { + rsasve_cmd::rsasve_4096_cmd(action, skfile, pkfile, ctfile, *x); + } + Some(Subcommands::RSASVE_8192 { action, skfile, pkfile, ctfile, x }) => { + rsasve_cmd::rsasve_8192_cmd(action, skfile, pkfile, ctfile, *x); + } + Some(Subcommands::RSA_OAEP_2048 { + action, + hash, + mgf_hash, + label, + skfile, + pkfile, + ctfile, + x, + }) => { + rsa_oaep_cmd::rsa_oaep_2048_cmd(&OaepArgs { + action, + hash: *hash, + mgf_hash: *mgf_hash, + label, + skfile, + pkfile, + ctfile, + output_hex: *x, + }); + } + Some(Subcommands::RSA_OAEP_3072 { + action, + hash, + mgf_hash, + label, + skfile, + pkfile, + ctfile, + x, + }) => { + rsa_oaep_cmd::rsa_oaep_3072_cmd(&OaepArgs { + action, + hash: *hash, + mgf_hash: *mgf_hash, + label, + skfile, + pkfile, + ctfile, + output_hex: *x, + }); + } + Some(Subcommands::RSA_OAEP_4096 { + action, + hash, + mgf_hash, + label, + skfile, + pkfile, + ctfile, + x, + }) => { + rsa_oaep_cmd::rsa_oaep_4096_cmd(&OaepArgs { + action, + hash: *hash, + mgf_hash: *mgf_hash, + label, + skfile, + pkfile, + ctfile, + output_hex: *x, + }); + } + Some(Subcommands::RSA_OAEP_8192 { + action, + hash, + mgf_hash, + label, + skfile, + pkfile, + ctfile, + x, + }) => { + rsa_oaep_cmd::rsa_oaep_8192_cmd(&OaepArgs { + action, + hash: *hash, + mgf_hash: *mgf_hash, + label, + skfile, + pkfile, + ctfile, + output_hex: *x, + }); + } + Some(Subcommands::RSA_1024 { scheme, hash, pkfile, sigfile }) => { + rsa_cmd::rsa_1024_cmd(scheme, hash, pkfile, sigfile); + } + Some(Subcommands::RSA_1536 { scheme, hash, pkfile, sigfile }) => { + rsa_cmd::rsa_1536_cmd(scheme, hash, pkfile, sigfile); + } + Some(Subcommands::RSA_2048 { action, scheme, hash, skfile, pkfile, sigfile, x }) => { + rsa_cmd::rsa_2048_cmd(action, scheme, hash, skfile, pkfile, sigfile, *x); + } + Some(Subcommands::RSA_3072 { action, scheme, hash, skfile, pkfile, sigfile, x }) => { + rsa_cmd::rsa_3072_cmd(action, scheme, hash, skfile, pkfile, sigfile, *x); + } + Some(Subcommands::RSA_4096 { action, scheme, hash, skfile, pkfile, sigfile, x }) => { + rsa_cmd::rsa_4096_cmd(action, scheme, hash, skfile, pkfile, sigfile, *x); + } + Some(Subcommands::RSA_8192 { action, scheme, hash, skfile, pkfile, sigfile, x }) => { + rsa_cmd::rsa_8192_cmd(action, scheme, hash, skfile, pkfile, sigfile, *x); + } Some(Subcommands::SM2 { action, idfile, skfile, pkfile, sigfile, x }) => { sm2_cmd::sm2_cmd(action, idfile, skfile, pkfile, sigfile, *x); } @@ -8481,6 +9019,9 @@ fn run() { Some(Subcommands::RIPEMD320 { x }) => { ripemd_cmd::ripemd_cmd(RIPEMDVariant::RIPEMD320, *x); } + Some(Subcommands::SHA1 { x }) => { + sha1_cmd::sha1_cmd(*x); + } Some(Subcommands::SM3 { x }) => { sm3_cmd::sm3_cmd(*x); } diff --git a/cli/src/mlkem_cmd.rs b/cli/src/mlkem_cmd.rs index c469d00f7..bcadba489 100644 --- a/cli/src/mlkem_cmd.rs +++ b/cli/src/mlkem_cmd.rs @@ -316,7 +316,10 @@ fn write_encaps_output( } /// The ciphertext from `--ctfile` or stdin, which must be exactly the parameter set's length. -fn read_ciphertext(ctfile: &Option, name: &str) -> [u8; CT_LEN] { +pub(crate) fn read_ciphertext( + ctfile: &Option, + name: &str, +) -> [u8; CT_LEN] { let ct = read_input_file_or_stdin(ctfile); <[u8; CT_LEN]>::try_from(ct.as_slice()).unwrap_or_else(|_| { eprintln!("Error: the ciphertext is {} bytes; an {name} ciphertext is {CT_LEN}.", ct.len()); diff --git a/cli/src/rsa_cmd.rs b/cli/src/rsa_cmd.rs new file mode 100644 index 000000000..7c6fc52fa --- /dev/null +++ b/cli/src/rsa_cmd.rs @@ -0,0 +1,750 @@ +//! CLI wiring for RSA signatures (RFC 8017 §8, RFC 8702 §3.2.1), one command function per modulus +//! size (`rsa_1024_cmd` .. `rsa_8192_cmd`) since modulus size is what fixes the private/public key +//! and signature byte lengths -- the same reason `ecdsa_cmd.rs` picks one command per curve. +//! Scheme (PKCS#1 v1.5 / PSS) and hash (SHA-256/384/512, or SHAKE128/256 for PSS) are +//! `--scheme`/`--hash` flags within a size's command rather than further separate subcommands: +//! unlike curve alone (ECDSA) or hash alone (HMAC) elsewhere in this CLI, RSA varies along three +//! independent axes at once, and multiplying all three out into subcommand names +//! (`RSA_2048_PSS_SHA384`, ...) would mean over thirty near-identical subcommands for what is +//! fundamentally one primitive per modulus size. +//! +//! Every (size, scheme, hash) pairing is one of `bouncycastle_rsa`'s algorithm marker +//! types (`rsa_2048::RSASSA_PKCS1_v1_5_SHA256` and siblings), and a key is a key for one of +//! them, `RsaPrivateKey` / `RsaPublicKey`, so, as `ecdsa_cmd.rs` does for its curves, one +//! generic command per role ([`rsa_pss_cmd`] over `SigningKey`, [`rsa_pkcs1_cmd`] over +//! `DeterministicSigningKey`) is monomorphised once per pairing below, and the message streams +//! from stdin through the workers' `do_update` in this CLI's usual ~1 KB chunks rather than +//! being read whole. A key file is decoded under the pairing of the command that reads it: the +//! bytes carry no scheme, and the key type the command names is the one it is for. The traits' +//! `ctx` is not exposed as a flag: RSA has no context input, and `bouncycastle_rsa` refuses a +//! non-empty one, so every call below passes `None`. +//! +//! `keygen` (FIPS 186-5 Appendix A.1.3 through the size marker's per-scheme generators, +//! `RSA2048::generate_pss_signature_key_pair::` and siblings) writes the private key +//! to stdout like the other key-generating commands, and -- unlike them -- also needs `--pkfile` +//! to receive the public key: there is no `PkFromSk`/`CheckConsistency` here, so the public key +//! has to be kept from generation time. Private and public key files use the raw fixed-width layout +//! `RsaPrivateKey`/`RsaPublicKey`'s `PrivateKey`/`PublicKey` impls encode +//! (documented under `# Encoding` on `RsaPrivateComponents`/`RsaPublicComponents`): not PEM, +//! not ASN.1 DER -- this crate has no encoder for either -- so a key produced by another RSA +//! implementation cannot be fed to this CLI directly. +//! +//! 1024- and 1536-bit RSA are verification-only in `bouncycastle_rsa` (see its crate docs' `# +//! Scope`), so `rsa_1024_cmd`/`rsa_1536_cmd` take no `action`/`skfile` at all: they only verify, +//! through [`do_verify`], which needs only a `VerifyingKey` -- exactly the trait those sizes' +//! types implement. + +use crate::helpers::{ + println_stdout, read_input_file, read_secret_file, stream_stdin, write_bytes_or_hex, + write_bytes_or_hex_to_file, write_private_key, +}; +use bouncycastle::core::errors::SignatureError; +use bouncycastle::core::key_material::KeyMaterialTrait; +use bouncycastle::core::signature_key::{DeterministicSigningKey, SigningKey, VerifyingKey}; +use bouncycastle::core::traits::{PrivateKey, PublicKey, RNG, SignatureSigner, SignatureVerifier}; +use bouncycastle::rng::HashDRBG_SHA512; +use bouncycastle::rsa::keys::{RsaPrivateKey, RsaPublicKey}; +use bouncycastle::rsa::rsassa::{ + RsaDeterministicSignatureAlgorithm, RsaRandomizedSignatureAlgorithm, RsaSignatureAlgorithm, +}; +use bouncycastle::rsa::size::SignatureKeyPair; +use bouncycastle::rsa::{ + RSA2048, RSA3072, RSA4096, RSA8192, rsa_1024, rsa_1536, rsa_2048, rsa_3072, rsa_4096, rsa_8192, +}; +use bouncycastle::sha2::{SHA256, SHA384, SHA512}; +use bouncycastle::sha3::{SHAKE128, SHAKE256}; +use clap::ValueEnum; +use std::process::exit; + +#[derive(ValueEnum, Clone, Debug, PartialEq, Eq)] +pub(crate) enum RSAAction { + /// Generate a key pair: the private key to stdout, the public key to `--pkfile`. + Keygen, + /// Sign a message read from stdin with a private key file and output the signature. + Sign, + /// Verify a message read from stdin with a public key file and a signature file. + Verify, +} + +#[derive(ValueEnum, Clone, Debug)] +pub(crate) enum RSAScheme { + /// RSASSA-PKCS1-v1_5 (RFC 8017 §8.2). + Pkcs1v15, + /// RSASSA-PSS (RFC 8017 §8.1 for SHA-256/384/512 with MGF1; RFC 8702 §3.2.1 for SHAKE128/256 + /// used natively as both the hash and the mask generation function). Salt length is fixed to + /// the hash's own output length in both cases. + Pss, +} + +#[derive(ValueEnum, Clone, Debug)] +pub(crate) enum RSAHash { + Sha256, + Sha384, + Sha512, + /// Only valid with `--scheme pss`; RFC 8702 §5 recommends this pairing for a 2048- or + /// 3072-bit modulus. + Shake128, + /// Only valid with `--scheme pss`; RFC 8702 §5 recommends this pairing for a 4096-bit or + /// larger modulus. + Shake256, +} + +/// `--pkfile` and `--sigfile`, which cannot fall back to stdin (that carries the message): raw +/// bytes, or hex under `--hex-input`. +fn require_file(file: &Option, flag_name: &str) -> Vec { + match file { + Some(f) => read_input_file(f), + None => { + eprintln!("Error: no {flag_name} provided."); + exit(-1); + } + } +} + +/// `--skfile`, into a zeroized buffer. +fn require_secret(file: &Option, flag_name: &str) -> crate::helpers::SecretBytes { + match file { + Some(f) => read_secret_file(f), + None => { + eprintln!("Error: no {flag_name} provided."); + exit(-1); + } + } +} + +fn unsupported(scheme: &RSAScheme, hash: &RSAHash, alg_name: &str) -> ! { + eprintln!("Error: {scheme:?}/{hash:?} is not supported for {alg_name}."); + exit(-1); +} + +/// The private key in `--skfile`. See `RsaPrivateComponents`'s `# Encoding` docs for the +/// expected layout; a wrong-length file is one of the `DecodingError`s `PrivateKey::from_bytes` +/// reports. +fn load_sk, const SK_LEN: usize>( + skfile: &Option, + alg_name: &str, +) -> SK { + // `exit` runs no destructors: the key file's bytes go out of scope, and so are wiped, + // before a failure exits. + let parsed = { + let bytes = require_secret(skfile, "skfile"); + SK::from_bytes(bytes.ref_to_bytes()) + }; + match parsed { + Ok(sk) => sk, + Err(_) => { + eprintln!( + "Error: couldn't parse the input as a valid {alg_name} private key (must be \ + exactly {SK_LEN} bytes)." + ); + exit(-1); + } + } +} + +/// See `RsaPublicComponents`'s `# Encoding` docs for the expected layout; a wrong-length file +/// is one of the `DecodingError`s `PublicKey::from_bytes` reports. +fn parse_pk, const PK_LEN: usize>(bytes: &[u8], alg_name: &str) -> PK { + match PK::from_bytes(bytes) { + Ok(pk) => pk, + Err(_) => { + eprintln!( + "Error: couldn't parse the input as a valid {alg_name} public key (must be exactly \ + {PK_LEN} bytes)." + ); + exit(-1); + } + } +} + +/// Verifies stdin against `--pkfile`/`--sigfile` through `PK`'s streaming `VerifyingKey` +/// impl. Shared by the `Verify` arms of [`rsa_pss_cmd`] and [`rsa_pkcs1_cmd`], and called +/// directly by the verify-only sizes (`rsa_1024_cmd`, `rsa_1536_cmd`). A signature file of the +/// wrong length is simply invalid (RFC 8017 §8.1.2/§8.2.2 step 1), as `do_verify_final` reports +/// it. +fn do_verify( + pkfile: &Option, + sigfile: &Option, + alg_name: &str, +) where + RsaPublicKey: PublicKey + VerifyingKey, +{ + let pk = parse_pk::, PK_LEN>(&require_file(pkfile, "pkfile"), alg_name); + let sig = require_file(sigfile, "sigfile"); + + // `create_verifier` refuses a non-empty context and nothing else, so this unwrap cannot fire. + let mut verifier = VerifyingKey::::create_verifier(&pk, None).unwrap(); + stream_stdin(|chunk| verifier.do_update(chunk)); + + if verifier.do_verify_final(&sig).is_ok() { + println_stdout("Signature is valid."); + } else { + eprintln!("Signature is invalid."); + exit(-1); + } +} + +/// The generator a command runs for its pairing: the size marker's, for the command's algorithm. +type Keygen = fn(&mut dyn RNG) -> Result<(RsaPublicKey, RsaPrivateKey), SignatureError>; + +/// Generates a key pair for one (size, scheme, hash) pairing: the private key to stdout and +/// the public key to `--pkfile`. `keygen` is the size's FIPS 186-5 generator. +fn rsa_keygen_cmd( + keygen: Keygen, + pkfile: &Option, + output_hex: bool, + alg_name: &str, +) where + RsaPublicKey: PublicKey, + RsaPrivateKey: PrivateKey, +{ + let Some(pkfile) = pkfile else { + eprintln!( + "Error: {alg_name} keygen needs --pkfile to receive the public key (this command \ + cannot derive it from the private key file later)." + ); + exit(-1); + }; + let (pk, sk) = keygen(&mut HashDRBG_SHA512::new_from_os()).unwrap_or_else(|e| { + eprintln!("Error: {alg_name} key generation failed: {e:?}"); + exit(-1); + }); + write_bytes_or_hex_to_file(&pk.encode(), pkfile, output_hex); + write_private_key(&sk, output_hex); +} + +/// One RSASSA-PSS pairing: `keygen` and `verify` as for every scheme; `sign` draws the salt from +/// an OS-seeded DRBG through [`SigningKey::create_signer`]. +#[allow(clippy::too_many_arguments)] +fn rsa_pss_cmd< + A: RsaRandomizedSignatureAlgorithm, + const PK_LEN: usize, + const SK_LEN: usize, + const SIG_LEN: usize, +>( + action: &RSAAction, + keygen: Keygen, + skfile: &Option, + pkfile: &Option, + sigfile: &Option, + output_hex: bool, + alg_name: &str, +) where + RsaPublicKey: PublicKey + VerifyingKey, + RsaPrivateKey: PrivateKey + SigningKey, +{ + match action { + RSAAction::Keygen => { + rsa_keygen_cmd::(keygen, pkfile, output_hex, alg_name) + } + RSAAction::Sign => { + // `exit` runs no destructors, so the key is dropped before the result is looked at. + let sig = { + let sk = load_sk::, SK_LEN>(skfile, alg_name); + // No context, and an RNG that delivers: neither refusal of `create_signer` + // applies, so this unwrap cannot fire. + let mut signer = SigningKey::::create_signer( + &sk, + &mut HashDRBG_SHA512::new_from_os(), + None, + ) + .unwrap(); + stream_stdin(|chunk| signer.do_update(chunk)); + signer.do_final() + }; + let sig = sig.unwrap_or_else(|_| { + eprintln!("Error: signing failed."); + exit(-1); + }); + write_bytes_or_hex(&sig, output_hex); + } + RSAAction::Verify => do_verify::(pkfile, sigfile, alg_name), + } +} + +/// One RSASSA-PKCS1-v1_5 pairing: as [`rsa_pss_cmd`], but the scheme is deterministic and signs +/// through [`DeterministicSigningKey::create_signer_deterministic`]. +#[allow(clippy::too_many_arguments)] +fn rsa_pkcs1_cmd< + A: RsaDeterministicSignatureAlgorithm, + const PK_LEN: usize, + const SK_LEN: usize, + const SIG_LEN: usize, +>( + action: &RSAAction, + keygen: Keygen, + skfile: &Option, + pkfile: &Option, + sigfile: &Option, + output_hex: bool, + alg_name: &str, +) where + RsaPublicKey: PublicKey + VerifyingKey, + RsaPrivateKey: PrivateKey + DeterministicSigningKey, +{ + match action { + RSAAction::Keygen => { + rsa_keygen_cmd::(keygen, pkfile, output_hex, alg_name) + } + RSAAction::Sign => { + // `exit` runs no destructors, so the key is dropped before the result is looked at. + let sig = { + let sk = load_sk::, SK_LEN>(skfile, alg_name); + // No context, which is all `create_signer_deterministic` refuses. + let mut signer = + DeterministicSigningKey::::create_signer_deterministic(&sk, None) + .unwrap(); + stream_stdin(|chunk| signer.do_update(chunk)); + signer.do_final() + }; + let sig = sig.unwrap_or_else(|_| { + eprintln!("Error: signing failed."); + exit(-1); + }); + write_bytes_or_hex(&sig, output_hex); + } + RSAAction::Verify => do_verify::(pkfile, sigfile, alg_name), + } +} + +pub(crate) fn rsa_1024_cmd( + scheme: &RSAScheme, + hash: &RSAHash, + pkfile: &Option, + sigfile: &Option, +) { + use rsa_1024::{PK_LEN, RSASSA_PKCS1_v1_5_SHA256, RSASSA_PKCS1_v1_5_SHA384, SIG_LEN}; + match (scheme, hash) { + (RSAScheme::Pkcs1v15, RSAHash::Sha256) => { + do_verify::( + pkfile, + sigfile, + "RSA-1024/PKCS#1v1.5/SHA-256", + ) + } + (RSAScheme::Pkcs1v15, RSAHash::Sha384) => { + do_verify::( + pkfile, + sigfile, + "RSA-1024/PKCS#1v1.5/SHA-384", + ) + } + (scheme, hash) => unsupported(scheme, hash, "RSA-1024"), + } +} + +pub(crate) fn rsa_1536_cmd( + scheme: &RSAScheme, + hash: &RSAHash, + pkfile: &Option, + sigfile: &Option, +) { + use rsa_1536::{ + PK_LEN, RSASSA_PKCS1_v1_5_SHA256, RSASSA_PKCS1_v1_5_SHA384, RSASSA_PKCS1_v1_5_SHA512, + SIG_LEN, + }; + match (scheme, hash) { + (RSAScheme::Pkcs1v15, RSAHash::Sha256) => { + do_verify::( + pkfile, + sigfile, + "RSA-1536/PKCS#1v1.5/SHA-256", + ) + } + (RSAScheme::Pkcs1v15, RSAHash::Sha384) => { + do_verify::( + pkfile, + sigfile, + "RSA-1536/PKCS#1v1.5/SHA-384", + ) + } + (RSAScheme::Pkcs1v15, RSAHash::Sha512) => { + do_verify::( + pkfile, + sigfile, + "RSA-1536/PKCS#1v1.5/SHA-512", + ) + } + (scheme, hash) => unsupported(scheme, hash, "RSA-1536"), + } +} + +/// RSA-2048: `keygen`, `sign` and `verify` for every pairing offered at this size. +#[allow(clippy::too_many_arguments)] +pub(crate) fn rsa_2048_cmd( + action: &RSAAction, + scheme: &RSAScheme, + hash: &RSAHash, + skfile: &Option, + pkfile: &Option, + sigfile: &Option, + output_hex: bool, +) { + use rsa_2048::{ + PK_LEN, RSASSA_PKCS1_v1_5_SHA256, RSASSA_PKCS1_v1_5_SHA384, RSASSA_PKCS1_v1_5_SHA512, + RSASSA_PSS_SHA256, RSASSA_PSS_SHA384, RSASSA_PSS_SHA512, RSASSA_PSS_SHAKE128, SIG_LEN, + SK_LEN, + }; + match (scheme, hash) { + (RSAScheme::Pkcs1v15, RSAHash::Sha256) => { + rsa_pkcs1_cmd::( + action, + RSA2048::generate_pkcs1_v1_5_signature_key_pair::, + skfile, + pkfile, + sigfile, + output_hex, + "RSA-2048/PKCS#1v1.5/SHA-256", + ) + } + (RSAScheme::Pkcs1v15, RSAHash::Sha384) => { + rsa_pkcs1_cmd::( + action, + RSA2048::generate_pkcs1_v1_5_signature_key_pair::, + skfile, + pkfile, + sigfile, + output_hex, + "RSA-2048/PKCS#1v1.5/SHA-384", + ) + } + (RSAScheme::Pkcs1v15, RSAHash::Sha512) => { + rsa_pkcs1_cmd::( + action, + RSA2048::generate_pkcs1_v1_5_signature_key_pair::, + skfile, + pkfile, + sigfile, + output_hex, + "RSA-2048/PKCS#1v1.5/SHA-512", + ) + } + (RSAScheme::Pss, RSAHash::Sha256) => { + rsa_pss_cmd::( + action, + RSA2048::generate_pss_signature_key_pair::, + skfile, + pkfile, + sigfile, + output_hex, + "RSA-2048/PSS/SHA-256", + ) + } + (RSAScheme::Pss, RSAHash::Sha384) => { + rsa_pss_cmd::( + action, + RSA2048::generate_pss_signature_key_pair::, + skfile, + pkfile, + sigfile, + output_hex, + "RSA-2048/PSS/SHA-384", + ) + } + (RSAScheme::Pss, RSAHash::Sha512) => { + rsa_pss_cmd::( + action, + RSA2048::generate_pss_signature_key_pair::, + skfile, + pkfile, + sigfile, + output_hex, + "RSA-2048/PSS/SHA-512", + ) + } + (RSAScheme::Pss, RSAHash::Shake128) => { + rsa_pss_cmd::( + action, + RSA2048::generate_pss_signature_key_pair::, + skfile, + pkfile, + sigfile, + output_hex, + "RSA-2048/PSS-SHAKE128", + ) + } + (scheme, hash) => unsupported(scheme, hash, "RSA-2048"), + } +} + +/// RSA-3072: `keygen`, `sign` and `verify` for every pairing offered at this size. +#[allow(clippy::too_many_arguments)] +pub(crate) fn rsa_3072_cmd( + action: &RSAAction, + scheme: &RSAScheme, + hash: &RSAHash, + skfile: &Option, + pkfile: &Option, + sigfile: &Option, + output_hex: bool, +) { + use rsa_3072::{ + PK_LEN, RSASSA_PKCS1_v1_5_SHA256, RSASSA_PKCS1_v1_5_SHA384, RSASSA_PKCS1_v1_5_SHA512, + RSASSA_PSS_SHA256, RSASSA_PSS_SHA384, RSASSA_PSS_SHA512, RSASSA_PSS_SHAKE128, SIG_LEN, + SK_LEN, + }; + match (scheme, hash) { + (RSAScheme::Pkcs1v15, RSAHash::Sha256) => { + rsa_pkcs1_cmd::( + action, + RSA3072::generate_pkcs1_v1_5_signature_key_pair::, + skfile, + pkfile, + sigfile, + output_hex, + "RSA-3072/PKCS#1v1.5/SHA-256", + ) + } + (RSAScheme::Pkcs1v15, RSAHash::Sha384) => { + rsa_pkcs1_cmd::( + action, + RSA3072::generate_pkcs1_v1_5_signature_key_pair::, + skfile, + pkfile, + sigfile, + output_hex, + "RSA-3072/PKCS#1v1.5/SHA-384", + ) + } + (RSAScheme::Pkcs1v15, RSAHash::Sha512) => { + rsa_pkcs1_cmd::( + action, + RSA3072::generate_pkcs1_v1_5_signature_key_pair::, + skfile, + pkfile, + sigfile, + output_hex, + "RSA-3072/PKCS#1v1.5/SHA-512", + ) + } + (RSAScheme::Pss, RSAHash::Sha256) => { + rsa_pss_cmd::( + action, + RSA3072::generate_pss_signature_key_pair::, + skfile, + pkfile, + sigfile, + output_hex, + "RSA-3072/PSS/SHA-256", + ) + } + (RSAScheme::Pss, RSAHash::Sha384) => { + rsa_pss_cmd::( + action, + RSA3072::generate_pss_signature_key_pair::, + skfile, + pkfile, + sigfile, + output_hex, + "RSA-3072/PSS/SHA-384", + ) + } + (RSAScheme::Pss, RSAHash::Sha512) => { + rsa_pss_cmd::( + action, + RSA3072::generate_pss_signature_key_pair::, + skfile, + pkfile, + sigfile, + output_hex, + "RSA-3072/PSS/SHA-512", + ) + } + (RSAScheme::Pss, RSAHash::Shake128) => { + rsa_pss_cmd::( + action, + RSA3072::generate_pss_signature_key_pair::, + skfile, + pkfile, + sigfile, + output_hex, + "RSA-3072/PSS-SHAKE128", + ) + } + (scheme, hash) => unsupported(scheme, hash, "RSA-3072"), + } +} + +/// RSA-4096: `keygen`, `sign` and `verify` for every pairing offered at this size. +#[allow(clippy::too_many_arguments)] +pub(crate) fn rsa_4096_cmd( + action: &RSAAction, + scheme: &RSAScheme, + hash: &RSAHash, + skfile: &Option, + pkfile: &Option, + sigfile: &Option, + output_hex: bool, +) { + use rsa_4096::{ + PK_LEN, RSASSA_PKCS1_v1_5_SHA256, RSASSA_PKCS1_v1_5_SHA384, RSASSA_PKCS1_v1_5_SHA512, + RSASSA_PSS_SHA256, RSASSA_PSS_SHA384, RSASSA_PSS_SHA512, RSASSA_PSS_SHAKE256, SIG_LEN, + SK_LEN, + }; + match (scheme, hash) { + (RSAScheme::Pkcs1v15, RSAHash::Sha256) => { + rsa_pkcs1_cmd::( + action, + RSA4096::generate_pkcs1_v1_5_signature_key_pair::, + skfile, + pkfile, + sigfile, + output_hex, + "RSA-4096/PKCS#1v1.5/SHA-256", + ) + } + (RSAScheme::Pkcs1v15, RSAHash::Sha384) => { + rsa_pkcs1_cmd::( + action, + RSA4096::generate_pkcs1_v1_5_signature_key_pair::, + skfile, + pkfile, + sigfile, + output_hex, + "RSA-4096/PKCS#1v1.5/SHA-384", + ) + } + (RSAScheme::Pkcs1v15, RSAHash::Sha512) => { + rsa_pkcs1_cmd::( + action, + RSA4096::generate_pkcs1_v1_5_signature_key_pair::, + skfile, + pkfile, + sigfile, + output_hex, + "RSA-4096/PKCS#1v1.5/SHA-512", + ) + } + (RSAScheme::Pss, RSAHash::Sha256) => { + rsa_pss_cmd::( + action, + RSA4096::generate_pss_signature_key_pair::, + skfile, + pkfile, + sigfile, + output_hex, + "RSA-4096/PSS/SHA-256", + ) + } + (RSAScheme::Pss, RSAHash::Sha384) => { + rsa_pss_cmd::( + action, + RSA4096::generate_pss_signature_key_pair::, + skfile, + pkfile, + sigfile, + output_hex, + "RSA-4096/PSS/SHA-384", + ) + } + (RSAScheme::Pss, RSAHash::Sha512) => { + rsa_pss_cmd::( + action, + RSA4096::generate_pss_signature_key_pair::, + skfile, + pkfile, + sigfile, + output_hex, + "RSA-4096/PSS/SHA-512", + ) + } + (RSAScheme::Pss, RSAHash::Shake256) => { + rsa_pss_cmd::( + action, + RSA4096::generate_pss_signature_key_pair::, + skfile, + pkfile, + sigfile, + output_hex, + "RSA-4096/PSS-SHAKE256", + ) + } + (scheme, hash) => unsupported(scheme, hash, "RSA-4096"), + } +} + +/// RSA-8192: `keygen`, `sign` and `verify` for every pairing offered at this size. +#[allow(clippy::too_many_arguments)] +pub(crate) fn rsa_8192_cmd( + action: &RSAAction, + scheme: &RSAScheme, + hash: &RSAHash, + skfile: &Option, + pkfile: &Option, + sigfile: &Option, + output_hex: bool, +) { + use rsa_8192::{ + PK_LEN, RSASSA_PKCS1_v1_5_SHA256, RSASSA_PKCS1_v1_5_SHA384, RSASSA_PKCS1_v1_5_SHA512, + RSASSA_PSS_SHA256, RSASSA_PSS_SHA384, RSASSA_PSS_SHA512, SIG_LEN, SK_LEN, + }; + match (scheme, hash) { + (RSAScheme::Pkcs1v15, RSAHash::Sha256) => { + rsa_pkcs1_cmd::( + action, + RSA8192::generate_pkcs1_v1_5_signature_key_pair::, + skfile, + pkfile, + sigfile, + output_hex, + "RSA-8192/PKCS#1v1.5/SHA-256", + ) + } + (RSAScheme::Pkcs1v15, RSAHash::Sha384) => { + rsa_pkcs1_cmd::( + action, + RSA8192::generate_pkcs1_v1_5_signature_key_pair::, + skfile, + pkfile, + sigfile, + output_hex, + "RSA-8192/PKCS#1v1.5/SHA-384", + ) + } + (RSAScheme::Pkcs1v15, RSAHash::Sha512) => { + rsa_pkcs1_cmd::( + action, + RSA8192::generate_pkcs1_v1_5_signature_key_pair::, + skfile, + pkfile, + sigfile, + output_hex, + "RSA-8192/PKCS#1v1.5/SHA-512", + ) + } + (RSAScheme::Pss, RSAHash::Sha256) => { + rsa_pss_cmd::( + action, + RSA8192::generate_pss_signature_key_pair::, + skfile, + pkfile, + sigfile, + output_hex, + "RSA-8192/PSS/SHA-256", + ) + } + (RSAScheme::Pss, RSAHash::Sha384) => { + rsa_pss_cmd::( + action, + RSA8192::generate_pss_signature_key_pair::, + skfile, + pkfile, + sigfile, + output_hex, + "RSA-8192/PSS/SHA-384", + ) + } + (RSAScheme::Pss, RSAHash::Sha512) => { + rsa_pss_cmd::( + action, + RSA8192::generate_pss_signature_key_pair::, + skfile, + pkfile, + sigfile, + output_hex, + "RSA-8192/PSS/SHA-512", + ) + } + (scheme, hash) => unsupported(scheme, hash, "RSA-8192"), + } +} diff --git a/cli/src/rsa_oaep_cmd.rs b/cli/src/rsa_oaep_cmd.rs new file mode 100644 index 000000000..f3304a816 --- /dev/null +++ b/cli/src/rsa_oaep_cmd.rs @@ -0,0 +1,287 @@ +//! CLI wiring for RSAES-OAEP key transport (RFC 8017 §7.1; SP 800-56B Rev. 2 §7.2.2 and §9.2.3), +//! one command per modulus size, on the same key-establishment keys and key files as +//! `rsasve_cmd.rs`. The label hash and the MGF1 hash are `--hash` and `--mgf-hash` (the same +//! hash unless given), and the label is `--label`, in hex. +//! +//! Two pairs of actions over the one scheme. `encaps` / `decaps` are the KEM: the command +//! draws a 32-byte key and transports it. `transport` / `recover` carry a key the caller +//! supplies on stdin, of any length the modulus and hash allow. + +use crate::helpers::{ + decode_hex_arg, println_stdout, read_input_file, read_input_file_or_stdin, read_secret_file, + read_secret_stdin, write_bytes_or_hex, write_bytes_or_hex_to_file, write_private_key, + write_secret_bytes_or_hex, +}; +use bouncycastle::core::kem_key::{DecapsulatingKey, EncapsulatingKey}; +use bouncycastle::core::key_material::{KeyMaterial, KeyMaterialTrait}; +use bouncycastle::core::key_transport_key::{KeyTransportDecryptingKey, KeyTransportEncryptingKey}; +use bouncycastle::core::traits::{PrivateKey, PublicKey}; +use bouncycastle::digest::sha1::SHA1; +use bouncycastle::rng::HashDRBG_SHA512; +use bouncycastle::rsa::rsaes_oaep::{OaepHash, OaepParams}; +use bouncycastle::rsa::rsasve::{RSASVE, RsaKEMPrivateKey, RsaKEMPublicKey}; +use bouncycastle::rsa::size::{RsaSigningSize, RsaSize}; +use bouncycastle::rsa::{RSA2048, RSA3072, RSA4096, RSA8192}; +use bouncycastle::sha2::{SHA224, SHA256, SHA384, SHA512, SHA512_224, SHA512_256}; +use clap::ValueEnum; +use std::process::exit; + +/// The length of the key `encaps` draws and `decaps` expects. +const KEM_KEY_LEN: usize = 32; + +#[derive(ValueEnum, Clone, Debug, PartialEq, Eq)] +pub(crate) enum RSAOAEPAction { + /// Generate a key-establishment key pair: the private key to stdout, the public key to + /// `--pkfile`. The keys are rsasve's. + Keygen, + /// Draw a 32-byte key and transport it to the public key in `--pkfile` (or on stdin). With + /// `--ctfile`, the ciphertext goes to that file and the key to stdout. Without it, the + /// ciphertext and then the key go to stdout in hex, separated by a newline. + Encaps, + /// Recover the 32-byte key in the ciphertext in `--ctfile` (or on stdin) with the private + /// key in `--skfile`, and write it to stdout. + Decaps, + /// Transport the key on stdin to the public key in `--pkfile`: the ciphertext to stdout, + /// or to `--ctfile`. + Transport, + /// Recover the key in the ciphertext in `--ctfile` (or on stdin) with the private key in + /// `--skfile`, whatever its length, and write it to stdout. + Recover, +} + +/// A hash for the label and for MGF1. +#[derive(ValueEnum, Clone, Copy, Debug)] +pub(crate) enum RSAOAEPHash { + /// For peers that use it; prefer SHA-256 or longer. + Sha1, + Sha224, + Sha256, + Sha384, + Sha512, + #[value(name = "sha512-224")] + Sha512_224, + #[value(name = "sha512-256")] + Sha512_256, +} + +/// What the command line gives a size's command. +pub(crate) struct OaepArgs<'a> { + pub(crate) action: &'a RSAOAEPAction, + pub(crate) hash: RSAOAEPHash, + pub(crate) mgf_hash: Option, + pub(crate) label: &'a Option, + pub(crate) skfile: &'a Option, + pub(crate) pkfile: &'a Option, + pub(crate) ctfile: &'a Option, + pub(crate) output_hex: bool, +} + +/// A file a flag must name. +fn required<'a>(file: &'a Option, flag_name: &str) -> &'a str { + match file { + Some(f) => f, + None => { + eprintln!("Error: no {flag_name} provided."); + exit(-1); + } + } +} + +/// One size, label hash and MGF1 hash, per the action. +fn run( + args: &OaepArgs, + alg_name: &str, +) where + K: RsaSigningSize + + RsaSize< + Modulus = [u8; N], + PublicKeyEncoded = [u8; PK_LEN], + PrivateKeyEncoded = [u8; SK_LEN], + >, + H: OaepHash, + M: OaepHash, +{ + let label = args.label.as_ref().map(|l| decode_hex_arg(l, "label")).unwrap_or_default(); + let params = OaepParams::::new(&label); + let load_pk = |bytes: Vec| { + RsaKEMPublicKey::::from_bytes(&bytes).unwrap_or_else(|e| { + eprintln!( + "Error: couldn't parse the input as a valid {alg_name} public key (must be \ + exactly {PK_LEN} bytes): {e:?}" + ); + exit(-1); + }) + }; + // The key file's bytes go out of scope, and so are wiped, before a failure exits. + let load_sk = || { + let parsed = { + let bytes = read_secret_file(required(args.skfile, "skfile")); + RsaKEMPrivateKey::::from_bytes(bytes.ref_to_bytes()) + }; + parsed.unwrap_or_else(|e| { + eprintln!( + "Error: couldn't parse the input as a valid {alg_name} private key (must be \ + exactly {SK_LEN} bytes): {e:?}" + ); + exit(-1); + }) + }; + let load_ct = || { + let ct = read_input_file_or_stdin(args.ctfile); + <[u8; N]>::try_from(ct.as_slice()).unwrap_or_else(|_| { + eprintln!( + "Error: the ciphertext is {} bytes; an {alg_name} ciphertext is {N}.", + ct.len() + ); + exit(-1); + }) + }; + + match args.action { + RSAOAEPAction::Keygen => { + let pkfile = required(args.pkfile, "pkfile"); + let (pk, sk) = + RSASVE::::keygen(&mut HashDRBG_SHA512::new_from_os()).unwrap_or_else(|e| { + eprintln!("Error: {alg_name} key generation failed: {e:?}"); + exit(-1); + }); + write_bytes_or_hex_to_file(&pk.encode(), pkfile, args.output_hex); + write_private_key(&sk, args.output_hex); + } + RSAOAEPAction::Encaps => { + let pk = load_pk(read_input_file_or_stdin(args.pkfile)); + let (key, ct) = + pk.encaps(&mut HashDRBG_SHA512::new_from_os(), params).unwrap_or_else(|e| { + eprintln!("Error: {alg_name} encapsulation failed: {e:?}"); + exit(-1); + }); + match args.ctfile { + Some(ctfile) => { + write_bytes_or_hex_to_file(&ct, ctfile, args.output_hex); + write_secret_bytes_or_hex(key.ref_to_bytes(), args.output_hex); + } + None => { + write_bytes_or_hex(&ct, true); + println_stdout(""); + write_secret_bytes_or_hex(key.ref_to_bytes(), true); + } + } + } + RSAOAEPAction::Decaps => { + let ct = load_ct(); + // `exit` runs no destructors, so the key is dropped before the result is looked at. + let key = { + let sk = load_sk(); + sk.decaps(&ct, params) + }; + let key = key.unwrap_or_else(|_| { + eprintln!("Error: {alg_name} decryption failed."); + exit(-1); + }); + write_secret_bytes_or_hex(key.ref_to_bytes(), args.output_hex); + } + RSAOAEPAction::Transport => { + // stdin carries the key, so the public key must come from its file. + let pk = load_pk(read_input_file(required(args.pkfile, "pkfile"))); + let ct = { + let key = read_secret_stdin(); + pk.transport(&mut HashDRBG_SHA512::new_from_os(), params, &key) + }; + let ct = ct.unwrap_or_else(|e| { + eprintln!( + "Error: {alg_name} key transport failed (the key may be at most {} bytes): {e:?}", + pk.max_key_len(params) + ); + exit(-1); + }); + match args.ctfile { + Some(ctfile) => write_bytes_or_hex_to_file(&ct, ctfile, args.output_hex), + None => write_bytes_or_hex(&ct, args.output_hex), + } + } + RSAOAEPAction::Recover => { + let ct = load_ct(); + let mut key = KeyMaterial::<1024>::new(); + let result = { + let sk = load_sk(); + sk.recover_out(&ct, params, &mut key) + }; + if result.is_err() { + eprintln!("Error: {alg_name} decryption failed."); + exit(-1); + } + write_secret_bytes_or_hex(key.ref_to_bytes(), args.output_hex); + } + } +} + +/// The MGF1 hash. +fn with_mgf( + args: &OaepArgs, + alg_name: &str, +) where + K: RsaSigningSize + + RsaSize< + Modulus = [u8; N], + PublicKeyEncoded = [u8; PK_LEN], + PrivateKeyEncoded = [u8; SK_LEN], + >, + H: OaepHash, +{ + match args.mgf_hash.unwrap_or(args.hash) { + RSAOAEPHash::Sha1 => run::(args, alg_name), + RSAOAEPHash::Sha224 => run::(args, alg_name), + RSAOAEPHash::Sha256 => run::(args, alg_name), + RSAOAEPHash::Sha384 => run::(args, alg_name), + RSAOAEPHash::Sha512 => run::(args, alg_name), + RSAOAEPHash::Sha512_224 => run::(args, alg_name), + RSAOAEPHash::Sha512_256 => run::(args, alg_name), + } +} + +/// The label hash. +fn with_hash( + args: &OaepArgs, + alg_name: &str, +) where + K: RsaSigningSize + + RsaSize< + Modulus = [u8; N], + PublicKeyEncoded = [u8; PK_LEN], + PrivateKeyEncoded = [u8; SK_LEN], + >, +{ + match args.hash { + RSAOAEPHash::Sha1 => with_mgf::(args, alg_name), + RSAOAEPHash::Sha224 => with_mgf::(args, alg_name), + RSAOAEPHash::Sha256 => with_mgf::(args, alg_name), + RSAOAEPHash::Sha384 => with_mgf::(args, alg_name), + RSAOAEPHash::Sha512 => with_mgf::(args, alg_name), + RSAOAEPHash::Sha512_224 => with_mgf::(args, alg_name), + RSAOAEPHash::Sha512_256 => with_mgf::(args, alg_name), + } +} + +pub(crate) fn rsa_oaep_2048_cmd(args: &OaepArgs) { + with_hash::( + args, "RSAES-OAEP-2048", + ); +} + +pub(crate) fn rsa_oaep_3072_cmd(args: &OaepArgs) { + with_hash::( + args, "RSAES-OAEP-3072", + ); +} + +pub(crate) fn rsa_oaep_4096_cmd(args: &OaepArgs) { + with_hash::( + args, "RSAES-OAEP-4096", + ); +} + +pub(crate) fn rsa_oaep_8192_cmd(args: &OaepArgs) { + with_hash::( + args, "RSAES-OAEP-8192", + ); +} diff --git a/cli/src/rsasve_cmd.rs b/cli/src/rsasve_cmd.rs new file mode 100644 index 000000000..8d8120554 --- /dev/null +++ b/cli/src/rsasve_cmd.rs @@ -0,0 +1,225 @@ +//! CLI wiring for RSASVE (SP 800-56B Rev. 2 §7.2.1), `bouncycastle_rsa`'s RSA KEM. There is one +//! command per modulus size, since the size fixes the key, ciphertext and shared-secret lengths +//! (the same split `rsa_cmd.rs` makes for signatures). A single generic [`rsasve_cmd`], bound over +//! the `EncapsulatingKey` / `DecapsulatingKey` roles, is monomorphised once per size. +//! +//! The shape follows `mlkem_cmd.rs`'s `Encaps`/`Decaps`. The shared secret always goes to stdout +//! and is never written to a file. `encaps` writes the ciphertext to `--ctfile` if one is given; +//! otherwise it prints the ciphertext and then the shared secret, both in hex, one per line. +//! `keygen` is `rsa_cmd.rs`'s: the private key to stdout, the public key to `--pkfile`, since +//! no command derives the public key from the private key file. +//! +//! These are separate subcommands from `rsa-` because `bouncycastle_rsa` keeps +//! key-establishment and signing keys as separate types (see its `rsasve` module's +//! `# Key separation`). The file encodings are the same raw layouts, however, and nothing here +//! stops a caller from pointing one command at the other's key files. The encodings cannot tell +//! the two kinds of key apart. +//! +//! The shared secret is RSASVE's raw secret value `Z`, the modulus's full length. It still needs +//! a KDF (e.g. `hkdf`) before it can be used as a key. + +use crate::helpers::{ + println_stdout, read_input_file_or_stdin, read_secret_file, write_bytes_or_hex, + write_bytes_or_hex_to_file, write_private_key, write_secret_bytes_or_hex, +}; +use bouncycastle::core::errors::KEMError; +use bouncycastle::core::kem_key::{DecapsulatingKey, EncapsulatingKey}; +use bouncycastle::core::key_material::KeyMaterialTrait; +use bouncycastle::core::traits::{PrivateKey, PublicKey, RNG}; +use bouncycastle::rng::HashDRBG_SHA512; +use bouncycastle::rsa::{rsa_2048, rsa_3072, rsa_4096, rsa_8192}; +use clap::ValueEnum; +use std::process::exit; + +#[derive(ValueEnum, Clone, Debug, PartialEq, Eq)] +pub(crate) enum RSASVEAction { + /// Generate a key-establishment key pair: the private key to stdout, the public key to + /// `--pkfile`. + Keygen, + /// Encapsulate to the public key in `--pkfile` (or read from stdin). With `--ctfile`, the + /// ciphertext goes to that file and the shared secret to stdout. Without it, the ciphertext + /// and then the shared secret go to stdout in hex, separated by a newline. + Encaps, + /// Decapsulate the ciphertext in `--ctfile` (or read from stdin) with the private key in + /// `--skfile`, and write the shared secret to stdout. + Decaps, +} + +/// `--skfile`, into a zeroized buffer: raw bytes, or hex under `--hex-input`. +fn require_secret(file: &Option, flag_name: &str) -> crate::helpers::SecretBytes { + match file { + Some(f) => read_secret_file(f), + None => { + eprintln!("Error: no {flag_name} provided."); + exit(-1); + } + } +} + +/// One modulus size's RSASVE, per `action`. +fn rsasve_cmd< + PK: PublicKey + EncapsulatingKey<(), CT_LEN, SS_LEN>, + SK: PrivateKey + DecapsulatingKey<(), CT_LEN, SS_LEN>, + const PK_LEN: usize, + const SK_LEN: usize, + const CT_LEN: usize, + const SS_LEN: usize, +>( + action: &RSASVEAction, + keygen: fn(&mut dyn RNG) -> Result<(PK, SK), KEMError>, + skfile: &Option, + pkfile: &Option, + ctfile: &Option, + output_hex: bool, + alg_name: &str, +) { + match action { + RSASVEAction::Keygen => { + let Some(pkfile) = pkfile else { + eprintln!( + "Error: {alg_name} keygen needs --pkfile to receive the public key (this \ + command cannot derive it from the private key file later)." + ); + exit(-1); + }; + let (pk, sk) = keygen(&mut HashDRBG_SHA512::new_from_os()).unwrap_or_else(|e| { + eprintln!("Error: {alg_name} key generation failed: {e:?}"); + exit(-1); + }); + write_bytes_or_hex_to_file(&pk.encode(), pkfile, output_hex); + write_private_key(&sk, output_hex); + } + RSASVEAction::Encaps => { + let pk = PK::from_bytes(&read_input_file_or_stdin(pkfile)).unwrap_or_else(|e| { + eprintln!( + "Error: couldn't parse the input as a valid {alg_name} public key (must be \ + exactly {PK_LEN} bytes): {e:?}" + ); + exit(-1); + }); + let (ss, ct) = pk.encaps(&mut HashDRBG_SHA512::new_from_os(), ()).unwrap_or_else(|e| { + eprintln!("Error: {alg_name} encapsulation failed: {e:?}"); + exit(-1); + }); + match ctfile { + Some(ctfile) => { + write_bytes_or_hex_to_file(&ct, ctfile, output_hex); + write_secret_bytes_or_hex(ss.ref_to_bytes(), output_hex); + } + None => { + write_bytes_or_hex(&ct, true); + println_stdout(""); + write_secret_bytes_or_hex(ss.ref_to_bytes(), true); + } + } + } + RSASVEAction::Decaps => { + let ct = crate::mlkem_cmd::read_ciphertext::(ctfile, alg_name); + // `exit` runs no destructors, so the key file's bytes and the key are dropped + // before either result is looked at. + let ss = { + let parsed = { + let bytes = require_secret(skfile, "skfile"); + SK::from_bytes(bytes.ref_to_bytes()) + }; + parsed.map(|sk| sk.decaps(&ct, ())) + }; + let ss = ss.unwrap_or_else(|e| { + eprintln!( + "Error: couldn't parse the input as a valid {alg_name} private key (must be \ + exactly {SK_LEN} bytes): {e:?}" + ); + exit(-1); + }); + let ss = ss.unwrap_or_else(|e| { + eprintln!("Error: {alg_name} decapsulation failed: {e:?}"); + exit(-1); + }); + write_secret_bytes_or_hex(ss.ref_to_bytes(), output_hex); + } + } +} + +pub(crate) fn rsasve_2048_cmd( + action: &RSASVEAction, + skfile: &Option, + pkfile: &Option, + ctfile: &Option, + output_hex: bool, +) { + use rsa_2048::{ + CT_LEN, PK_LEN, RSA2048KEMPrivateKey, RSA2048KEMPublicKey, RSASVE, SK_LEN, SS_LEN, + }; + rsasve_cmd::( + action, + RSASVE::keygen, + skfile, + pkfile, + ctfile, + output_hex, + "RSASVE-2048", + ); +} + +pub(crate) fn rsasve_3072_cmd( + action: &RSASVEAction, + skfile: &Option, + pkfile: &Option, + ctfile: &Option, + output_hex: bool, +) { + use rsa_3072::{ + CT_LEN, PK_LEN, RSA3072KEMPrivateKey, RSA3072KEMPublicKey, RSASVE, SK_LEN, SS_LEN, + }; + rsasve_cmd::( + action, + RSASVE::keygen, + skfile, + pkfile, + ctfile, + output_hex, + "RSASVE-3072", + ); +} + +pub(crate) fn rsasve_4096_cmd( + action: &RSASVEAction, + skfile: &Option, + pkfile: &Option, + ctfile: &Option, + output_hex: bool, +) { + use rsa_4096::{ + CT_LEN, PK_LEN, RSA4096KEMPrivateKey, RSA4096KEMPublicKey, RSASVE, SK_LEN, SS_LEN, + }; + rsasve_cmd::( + action, + RSASVE::keygen, + skfile, + pkfile, + ctfile, + output_hex, + "RSASVE-4096", + ); +} + +pub(crate) fn rsasve_8192_cmd( + action: &RSASVEAction, + skfile: &Option, + pkfile: &Option, + ctfile: &Option, + output_hex: bool, +) { + use rsa_8192::{ + CT_LEN, PK_LEN, RSA8192KEMPrivateKey, RSA8192KEMPublicKey, RSASVE, SK_LEN, SS_LEN, + }; + rsasve_cmd::( + action, + RSASVE::keygen, + skfile, + pkfile, + ctfile, + output_hex, + "RSASVE-8192", + ); +} diff --git a/cli/src/sha1_cmd.rs b/cli/src/sha1_cmd.rs new file mode 100644 index 000000000..c21c1da78 --- /dev/null +++ b/cli/src/sha1_cmd.rs @@ -0,0 +1,6 @@ +use crate::helpers::stream_hash; +use bouncycastle::digest::sha1::SHA1; + +pub(crate) fn sha1_cmd(output_hex: bool) { + stream_hash(SHA1::new(), output_hex); +} diff --git a/cli/tests/rsa_cli_tests.rs b/cli/tests/rsa_cli_tests.rs new file mode 100644 index 000000000..9dc605a6a --- /dev/null +++ b/cli/tests/rsa_cli_tests.rs @@ -0,0 +1,366 @@ +//! Tests for the `rsa-1024` .. `rsa-8192` subcommands, driving the built `bc-rust` binary as a +//! subprocess (the harness is the one `aes_cbc_cli_tests.rs` documents): the behaviour worth +//! testing is the command-line contract -- key/signature file loading, the streamed stdin message, +//! exit codes -- none of which is reachable from the library API. What the library computes is +//! cross-checked by verifying the CLI's signatures with `bouncycastle_rsa`'s own +//! `VerifyingKey` impls (and, for the deterministic PKCS#1 v1.5 case, comparing bytes). +//! +//! `CARGO_BIN_EXE_bc-rust` is set by cargo for integration tests and points at the binary for the +//! current profile, so there is nothing to build or locate by hand. + +use bouncycastle::core::signature_key::{DeterministicOneShotSigningKey, OneShotVerifyingKey}; +use bouncycastle::core::traits::{PrivateKey, PublicKey}; +use bouncycastle::rsa::RSA2048; +use bouncycastle::rsa::keys::{ + RsaPrivateComponents, RsaPrivateKey, RsaPublicComponents, RsaPublicKey, +}; +use bouncycastle::rsa::rsa_2048::{ + RSASSA_PKCS1_v1_5_SHA256, RSASSA_PSS_SHA256, RSASSA_PSS_SHAKE128, +}; +use bouncycastle::rsa::rsassa::RsaSignatureAlgorithm; +use std::io::{ErrorKind, Write}; +use std::path::PathBuf; +use std::process::{Command, Output, Stdio}; +use std::sync::atomic::{AtomicUsize, Ordering}; +use std::thread; + +/// The path to the binary under test, resolved by cargo. +const BC_RUST: &str = env!("CARGO_BIN_EXE_bc-rust"); + +/// The genuine RSA-2048 CRT key `bouncycastle_rsa`'s own crate docs use (Wycheproof +/// `rsa_pkcs1_2048_sig_gen_test.json`'s SHA-256 group, factored as `rsa_2048_pkcs1_v1_5_tests.rs` +/// describes), in the CLI's `p || q || dP || dQ || qInv || e` key-file layout, hex. +const SK_2048_HEX: &str = concat!( + "dc431050f782e894fb5248247d98cb7d58b8d1e24f3b55d041c56e4de086b0d5", + "bb028bda42eeb5d234d5681e5809d415e6a289ad4cfbf78f978f6c35814f50ee", + "bff1c5b80a69f788e81e6bab5ddaa78369d659d143ec6f17e79813a575cfad9c", + "569156b90113e2e9110ad9e7b48a1c9348a6e653321191290ea36cfb3a5b18f1", + "bd1a81e7977f9898122273ae3222b598ea5fb19eb4eabc38308a5e32196603b2", + "e500ffb79f5b886816611debc472fac45544070beb057c941378a6868af3b7a0", + "3d3f9880ec47d5e089b94fbde542aba9ae8d72c57088d7abf5b131f39098f7bc", + "160f90536abc9492fd4e06f3ed7299d4b97bb03677207d95669f140cfbc20f25", + "a94b528b28f291599121d91952ffd1c7f21d7c1479d99d478885fb161870ee12", + "18bf08472612dbe5497e8d9c650688e09c786961ae3e2c354dc48ae34514759c", + "4c23c4588488961dc06b414e61c0e1e7fbbd2923d31532fe289f96da220711e5", + "8c14019808e00414276933bb07e4efb9b4a9b37656917205209f33f09515d7c1", + "3af0e72a933aef09ff2503df78bafed531c02ff1a2bc437c540cdcbd4ad35435", + "cf511763596543480629b114ca7f780ff7efa32ea0cb6e000d6d9ea1f2ef71fd", + "9cf9948422a165557e37e755edfe70d90b920502eb478bc98a63f788ce3a0f85", + "6d6ede7251a383bfa8fa480a81a925af7b3cc538c4bab8c9f7597ffb68011d8d", + "2640fbfbcfefb163ee7a87b6483a66ee41f956d90fa8a7939bfc042ee0924b1b", + "7993d0445f758d51933e85179c0320b0c968b48a91c38b5be923e1097c0c562f", + "88d42294b6a2759bafa5428a74f1270874e45f6fcc60f21602de5eccd143cf31", + "241f5921b5ad3983fb54ef17be3b285367e50c999c67247b552fe4bfce945f7b", + "0000000000010001", +); +/// Its public key, `n || e` with `e = 0x10001`. +const PK_2048_HEX: &str = concat!( + "a2b451a07d0aa5f96e455671513550514a8a5b462ebef717094fa1fee82224e6", + "37f9746d3f7cafd31878d80325b6ef5a1700f65903b469429e89d6eac8845097", + "b5ab393189db92512ed8a7711a1253facd20f79c15e8247f3d3e42e46e48c98e", + "254a2fe9765313a03eff8f17e1a029397a1fa26a8dce26f490ed81299615d981", + "4c22da610428e09c7d9658594266f5c021d0fceca08d945a12be82de4d1ece6b", + "4c03145b5d3495d4ed5411eb878daf05fd7afc3e09ada0f1126422f590975a19", + "69816f48698bcbba1b4d9cae79d460d8f9f85e7975005d9bc22c4e5ac0f7c1a4", + "5d12569a62807d3b9a02e5a530e773066f453d1f5b4c2e9cf7820283f742b9d5", + "0000000000010001", +); +/// The RSA-1024 public key from `bouncycastle_rsa`'s crate docs (Wycheproof +/// `rsa_pkcs1_1024_sig_gen_test.json`'s first group), `n || e`. +const PK_1024_HEX: &str = concat!( + "ac9048a7a4f560af91b4fcaf62a14595cb9ca9ec12000fc845e48572113cab28", + "90adb011a919575a40760d1f23fe92509c8a5810b6d05990b909dd0f4c6014f2", + "b31b6abd805bace99816e2eda41fd7b95405db7c5c8f4cf6babb14f550d5d0dd", + "5179b54951fff6aa9686f30f478db649b7c7044cc202dccad00343468eaacfbf", + "0000000000010001", +); +/// One of that group's genuine PKCS#1 v1.5/SHA-256 signatures, over twenty zero bytes. +const SIG_1024_HEX: &str = concat!( + "41339884a9b3940e8488d666bb158063c6a2a2717cae7f564834a876fcbf7098", + "ecf3acbfabf37d38a8e6127b1e313744f1f896e165efdaea0b2e7673867842b9", + "e94db0868ed9a92bcdcb370a4e20ff275c82595e4400a8b9e9f12482f014846b", + "48216f321266ae6ae6338dbcdc41b711e483e6e3e728772e7f9f5ef95c30196b", +); + +/// Runs `bc-rust ` with `stdin_bytes` on stdin and returns the completed output. See +/// `aes_cbc_cli_tests.rs`'s `run` for why stdin is written from a thread and `BrokenPipe` ignored. +fn run(args: &[&str], stdin_bytes: &[u8]) -> Output { + let mut child = Command::new(BC_RUST) + .args(args) + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .spawn() + .expect("failed to spawn bc-rust"); + + let mut stdin = child.stdin.take().expect("stdin piped"); + let payload = stdin_bytes.to_vec(); + let writer = thread::spawn(move || match stdin.write_all(&payload) { + Ok(()) => {} + Err(e) if e.kind() == ErrorKind::BrokenPipe => {} + Err(e) => panic!("failed to write to stdin: {e}"), + }); + + let output = child.wait_with_output().expect("failed to wait for bc-rust"); + writer.join().expect("the stdin writer thread panicked"); + output +} + +/// Runs a command that is expected to succeed, returning stdout. +fn run_ok(args: &[&str], stdin_bytes: &[u8]) -> Vec { + let out = run(args, stdin_bytes); + assert!( + out.status.success(), + "expected success from {args:?}, got {:?}\nstderr: {}", + out.status, + String::from_utf8_lossy(&out.stderr) + ); + out.stdout +} + +/// Runs a command that is expected to fail, returning stderr as a string. +fn run_err(args: &[&str], stdin_bytes: &[u8]) -> String { + let out = run(args, stdin_bytes); + assert!( + !out.status.success(), + "expected failure from {args:?}, but it succeeded\nstdout: {:?}", + String::from_utf8_lossy(&out.stdout) + ); + String::from_utf8_lossy(&out.stderr).into_owned() +} + +fn unhex(s: &str) -> Vec { + assert!(s.len().is_multiple_of(2), "hex string must have even length"); + (0..s.len()) + .step_by(2) + .map(|i| u8::from_str_radix(&s[i..i + 2], 16).expect("valid hex")) + .collect() +} + +/// Deterministic pseudo-random bytes, so the tests do not depend on an RNG or on `/dev/urandom`. +fn pseudo_random(len: usize, seed: u32) -> Vec { + let mut state = seed.wrapping_mul(2_654_435_761).wrapping_add(1); + (0..len) + .map(|_| { + state ^= state << 13; + state ^= state >> 17; + state ^= state << 5; + (state >> 24) as u8 + }) + .collect() +} + +static NEXT_FILE: AtomicUsize = AtomicUsize::new(0); + +/// Writes `contents` to a fresh file under the system temp dir (unique per process and call, so +/// parallel tests never share one) and returns its path as a `String` for `--skfile` and friends. +fn temp_file(tag: &str, contents: &[u8]) -> String { + let n = NEXT_FILE.fetch_add(1, Ordering::Relaxed); + let mut path: PathBuf = std::env::temp_dir(); + path.push(format!("bc-rust-rsa-cli-{}-{n}-{tag}", std::process::id())); + std::fs::write(&path, contents).expect("write temp file"); + path.to_string_lossy().into_owned() +} + +/// The key material, decoded through one key type (the bytes carry no scheme) and handed out +/// as the components, which each case types with the scheme it checks. +fn sk_2048() -> RsaPrivateComponents { + RsaPrivateKey::::from_bytes(&unhex(SK_2048_HEX)) + .expect("the documented key decodes") + .components() + .clone() +} + +fn pk_2048() -> RsaPublicComponents { + RsaPublicKey::::from_bytes(&unhex(PK_2048_HEX)) + .expect("the documented key decodes") + .components() + .clone() +} + +/// Key and signature files are raw bytes (hex would need the global `--hex-input`). +fn rsa_2048_sign(scheme: &str, hash: &str, msg: &[u8]) -> Vec { + let skfile = temp_file("sk", &unhex(SK_2048_HEX)); + run_ok(&["rsa-2048", "sign", "--scheme", scheme, "--hash", hash, "--skfile", &skfile], msg) +} + +fn rsa_2048_verify(scheme: &str, hash: &str, msg: &[u8], sig: &[u8]) -> Output { + let pkfile = temp_file("pk", &unhex(PK_2048_HEX)); + let sigfile = temp_file("sig", sig); + run( + &[ + "rsa-2048", "verify", "--scheme", scheme, "--hash", hash, "--pkfile", &pkfile, + "--sigfile", &sigfile, + ], + msg, + ) +} + +/// Verification-only size, against a genuine Wycheproof signature: the one real known-answer +/// check the CLI can make without a key generator. +#[test] +fn rsa_1024_verifies_a_wycheproof_signature_and_rejects_another_message() { + let pkfile = temp_file("pk1024", &unhex(PK_1024_HEX)); + let sigfile = temp_file("sig1024", &unhex(SIG_1024_HEX)); + let args = [ + "rsa-1024", "--scheme", "pkcs1v15", "--hash", "sha256", "--pkfile", &pkfile, "--sigfile", + &sigfile, + ]; + let out = run_ok(&args, &[0u8; 20]); + assert!(String::from_utf8_lossy(&out).contains("Signature is valid.")); + + let err = run_err(&args, b"a message this signature was not made for"); + assert!(err.contains("Signature is invalid."), "stderr: {err}"); +} + +/// PKCS#1 v1.5 is deterministic, so the CLI's signature must equal the library's byte for byte, +/// and a payload several times the CLI's 1 KB stream buffer proves the message is hashed across +/// chunk boundaries correctly. +#[test] +fn rsa_2048_pkcs1v15_signature_matches_the_library_and_verifies() { + let msg = pseudo_random(5000, 7); + let sig = rsa_2048_sign("pkcs1v15", "sha256", &msg); + let expected = + sk_2048().into_key::().sign_deterministic(&msg, None).unwrap(); + assert_eq!(sig, expected.to_vec()); + + let out = rsa_2048_verify("pkcs1v15", "sha256", &msg, &sig); + assert!(out.status.success(), "stderr: {}", String::from_utf8_lossy(&out.stderr)); + assert!(String::from_utf8_lossy(&out.stdout).contains("Signature is valid.")); + + // `-x` writes the same signature as hex. + let skfile = temp_file("sk", &unhex(SK_2048_HEX)); + let hex = run_ok( + &[ + "rsa-2048", "sign", "--scheme", "pkcs1v15", "--hash", "sha256", "--skfile", &skfile, + "-x", + ], + &msg, + ); + assert_eq!(unhex(String::from_utf8_lossy(&hex).trim()), sig); +} + +/// One PSS pairing: two CLI signatures of one message differ (a fresh salt each), and both +/// verify -- through the library's `VerifyingKey` impl for `PK` and through the CLI. +fn pss_case>(hash: &str, msg: &[u8]) { + let pk = pk_2048().into_key::(); + let sig_a = rsa_2048_sign("pss", hash, msg); + let sig_b = rsa_2048_sign("pss", hash, msg); + assert_ne!(sig_a, sig_b, "PSS/{hash}: a fresh salt each time"); + for sig in [&sig_a, &sig_b] { + pk.verify(msg, None, sig).unwrap_or_else(|e| panic!("PSS/{hash}: library rejected {e:?}")); + let out = rsa_2048_verify("pss", hash, msg, sig); + assert!(out.status.success(), "PSS/{hash}: {}", String::from_utf8_lossy(&out.stderr)); + } +} + +/// PSS draws a fresh salt per signature: see [`pss_case`], for the MGF1/SHA-256 and the +/// SHAKE128-native pairings. +#[test] +fn rsa_2048_pss_signatures_are_fresh_and_verify_both_ways() { + let msg = pseudo_random(3000, 11); + pss_case::("sha256", &msg); + pss_case::("shake128", &msg); +} + +#[test] +fn rsa_2048_verify_rejects_a_tampered_signature_and_a_truncated_one() { + let msg = b"tamper me"; + let mut sig = rsa_2048_sign("pkcs1v15", "sha256", msg); + sig[17] ^= 0x01; + let out = rsa_2048_verify("pkcs1v15", "sha256", msg, &sig); + assert!(!out.status.success()); + assert!(String::from_utf8_lossy(&out.stderr).contains("Signature is invalid.")); + + // RFC 8017 §8.2.2 step 1: a signature that is not k octets is invalid. + sig[17] ^= 0x01; + let out = rsa_2048_verify("pkcs1v15", "sha256", msg, &sig[..255]); + assert!(!out.status.success()); + assert!(String::from_utf8_lossy(&out.stderr).contains("Signature is invalid.")); +} + +#[test] +fn rsa_2048_rejects_a_wrong_length_key_file() { + let short_sk = temp_file("shortsk", &unhex(SK_2048_HEX)[..647]); + let err = run_err( + &["rsa-2048", "sign", "--scheme", "pkcs1v15", "--hash", "sha256", "--skfile", &short_sk], + b"msg", + ); + assert!(err.contains("648 bytes"), "stderr: {err}"); + + let short_pk = temp_file("shortpk", &unhex(PK_2048_HEX)[..263]); + let sigfile = temp_file("sig", &[0u8; 256]); + let err = run_err( + &[ + "rsa-2048", "verify", "--scheme", "pkcs1v15", "--hash", "sha256", "--pkfile", + &short_pk, "--sigfile", &sigfile, + ], + b"msg", + ); + assert!(err.contains("264 bytes"), "stderr: {err}"); +} + +/// Pairings a size does not offer (PSS at 1024 bits, SHAKE256 at 2048) are refused up front. +#[test] +fn unsupported_pairings_are_refused() { + let pkfile = temp_file("pk1024", &unhex(PK_1024_HEX)); + let sigfile = temp_file("sig1024", &unhex(SIG_1024_HEX)); + let err = run_err( + &[ + "rsa-1024", "--scheme", "pss", "--hash", "sha256", "--pkfile", &pkfile, "--sigfile", + &sigfile, + ], + &[0u8; 20], + ); + assert!(err.contains("not supported"), "stderr: {err}"); + + let skfile = temp_file("sk", &unhex(SK_2048_HEX)); + let err = run_err( + &["rsa-2048", "sign", "--scheme", "pss", "--hash", "shake256", "--skfile", &skfile], + b"msg", + ); + assert!(err.contains("not supported"), "stderr: {err}"); +} + +/// `keygen` writes a 648-byte private key to stdout and a 264-byte public key to `--pkfile`, and +/// the pair then signs and verifies through the CLI; without `--pkfile` it refuses, since the +/// public key cannot be recovered from the private key file later. +#[test] +fn rsa_2048_keygen_then_sign_and_verify() { + let pkfile = temp_file("genpk", b""); + let sk_hex = run_ok( + &[ + "rsa-2048", "keygen", "--scheme", "pkcs1v15", "--hash", "sha256", "--pkfile", &pkfile, + "-x", + ], + &[], + ); + let sk_hex = String::from_utf8(sk_hex).unwrap(); + assert_eq!(sk_hex.trim().len(), 2 * 648, "private key on stdout, hex"); + let pk_hex = std::fs::read_to_string(&pkfile).unwrap(); + assert_eq!(pk_hex.trim().len(), 2 * 264, "public key in --pkfile, hex"); + let pk = RsaPublicKey::::from_bytes(&unhex(pk_hex.trim())).unwrap(); + assert_eq!(pk.e(), 65537); + + // The keys came out in hex (`-x`); the files a command reads are raw bytes. + let skfile = temp_file("gensk", &unhex(sk_hex.trim())); + let pkfile = temp_file("genpkraw", &unhex(pk_hex.trim())); + let msg = pseudo_random(2000, 5); + let sig = run_ok( + &["rsa-2048", "sign", "--scheme", "pss", "--hash", "sha256", "--skfile", &skfile], + &msg, + ); + let sigfile = temp_file("gensig", &sig); + let out = run_ok( + &[ + "rsa-2048", "verify", "--scheme", "pss", "--hash", "sha256", "--pkfile", &pkfile, + "--sigfile", &sigfile, + ], + &msg, + ); + assert!(String::from_utf8_lossy(&out).contains("Signature is valid.")); + pk.verify(&msg, None, &sig).unwrap(); + + let err = run_err(&["rsa-2048", "keygen", "--scheme", "pkcs1v15", "--hash", "sha256"], &[]); + assert!(err.contains("--pkfile"), "stderr: {err}"); +} diff --git a/cli/tests/rsa_oaep_cli_tests.rs b/cli/tests/rsa_oaep_cli_tests.rs new file mode 100644 index 000000000..3a011cf79 --- /dev/null +++ b/cli/tests/rsa_oaep_cli_tests.rs @@ -0,0 +1,220 @@ +//! Tests for the `rsa-oaep-2048` .. `rsa-oaep-8192` subcommands, driving the built `bc-rust` +//! binary as a subprocess with the harness in `common`. The known answers are three cases of +//! Wycheproof's `rsa_oaep_2048_sha256_mgf1sha256_test.json` under that file's key, which pin +//! `recover`; `transport`, `encaps` and `decaps` are checked against it and each other. + +mod common; +use common::{BC_RUST, run_err, run_ok, tohex, unhex}; +use std::path::PathBuf; +use std::sync::atomic::{AtomicUsize, Ordering}; + +/// The RSA-2048 key of Wycheproof's `rsa_oaep_2048_sha256_mgf1sha256_test.json`, in the CLI's +/// `p || q || dP || dQ || qInv || e` key-file layout, hex. +const SK_HEX: &str = concat!( + "dc431050f782e894fb5248247d98cb7d58b8d1e24f3b55d041c56e4de086b0d5", + "bb028bda42eeb5d234d5681e5809d415e6a289ad4cfbf78f978f6c35814f50ee", + "bff1c5b80a69f788e81e6bab5ddaa78369d659d143ec6f17e79813a575cfad9c", + "569156b90113e2e9110ad9e7b48a1c9348a6e653321191290ea36cfb3a5b18f1", + "bd1a81e7977f9898122273ae3222b598ea5fb19eb4eabc38308a5e32196603b2", + "e500ffb79f5b886816611debc472fac45544070beb057c941378a6868af3b7a0", + "3d3f9880ec47d5e089b94fbde542aba9ae8d72c57088d7abf5b131f39098f7bc", + "160f90536abc9492fd4e06f3ed7299d4b97bb03677207d95669f140cfbc20f25", + "a94b528b28f291599121d91952ffd1c7f21d7c1479d99d478885fb161870ee12", + "18bf08472612dbe5497e8d9c650688e09c786961ae3e2c354dc48ae34514759c", + "4c23c4588488961dc06b414e61c0e1e7fbbd2923d31532fe289f96da220711e5", + "8c14019808e00414276933bb07e4efb9b4a9b37656917205209f33f09515d7c1", + "3af0e72a933aef09ff2503df78bafed531c02ff1a2bc437c540cdcbd4ad35435", + "cf511763596543480629b114ca7f780ff7efa32ea0cb6e000d6d9ea1f2ef71fd", + "9cf9948422a165557e37e755edfe70d90b920502eb478bc98a63f788ce3a0f85", + "6d6ede7251a383bfa8fa480a81a925af7b3cc538c4bab8c9f7597ffb68011d8d", + "2640fbfbcfefb163ee7a87b6483a66ee41f956d90fa8a7939bfc042ee0924b1b", + "7993d0445f758d51933e85179c0320b0c968b48a91c38b5be923e1097c0c562f", + "88d42294b6a2759bafa5428a74f1270874e45f6fcc60f21602de5eccd143cf31", + "241f5921b5ad3983fb54ef17be3b285367e50c999c67247b552fe4bfce945f7b", + "0000000000010001", +); +/// Its public key, `n || e`. +const PK_HEX: &str = concat!( + "a2b451a07d0aa5f96e455671513550514a8a5b462ebef717094fa1fee82224e6", + "37f9746d3f7cafd31878d80325b6ef5a1700f65903b469429e89d6eac8845097", + "b5ab393189db92512ed8a7711a1253facd20f79c15e8247f3d3e42e46e48c98e", + "254a2fe9765313a03eff8f17e1a029397a1fa26a8dce26f490ed81299615d981", + "4c22da610428e09c7d9658594266f5c021d0fceca08d945a12be82de4d1ece6b", + "4c03145b5d3495d4ed5411eb878daf05fd7afc3e09ada0f1126422f590975a19", + "69816f48698bcbba1b4d9cae79d460d8f9f85e7975005d9bc22c4e5ac0f7c1a4", + "5d12569a62807d3b9a02e5a530e773066f453d1f5b4c2e9cf7820283f742b9d5", + "0000000000010001", +); +/// tcId 2 of that file: a ciphertext of `MSG_HEX` under the empty label. +const CT_HEX: &str = concat!( + "207180c340658b5154ae45d2e4e7326a0997c683a26b595e536a29333c4b6614", + "9af85e029d5419a39e3a147b221516ffd86b6b4b66c3e0c4c49fe8c57a2f5c37", + "b8704b9b592b80db9cd788a4ed51ab4f0a1cbed63bd18d1f06a22f225866b0c2", + "c417cb23473b7ba4250b1353bd2e5b4f0f937cd2efe5fa38db3c295f7748b970", + "088657db4aa9a76e1ee6fbff166ec1861d00d085326c7384bdd1bc2f400d4f74", + "dbdfadaf3fdc46073e668573e02030b9eb5af58eb540c66677a771194479ec00", + "98d858a2ea45d0ba1e6b32440dfbac745000554d51a17684ca964b02a74d479f", + "1d432ef763ef4059715a4348cfe36a215359712f25b6977903be4adb92febbf6", +); +const MSG_HEX: &str = "0000000000000000000000000000000000000000"; +/// tcId 8: a ciphertext of `LABELLED_MSG_HEX` under `LABEL_HEX`. +const LABELLED_CT_HEX: &str = concat!( + "6583e2f176aa7e7f655d2c53497349c156c8851fb23325589e85fb83bfa85734", + "6caba222cdaa3234e71564154298c24dbb85e18822a1d5e7faa47863a64d7687", + "4a3cbc70f4d9f137426a344c473fac1dd7008a9973765e9f66c5b492535a647c", + "273c4f78ceb5aa7ba963a2142f2ce4a81f804c002b9b2eabb3c75e80a3c6ceaf", + "e5384a544c672a5d28d32bb87115f43eb79775fd9b3f4a2f6e6a89368bdd95ef", + "1d014877b60afdb1234acd57653a65459f01b2fbe381f22a739504b4897a7e6c", + "33b6349b276db6083abad9c169405859b800c812237634b503de6ada43013c1d", + "86697a135be78a9784576d796d62aa7819e2ea0e2d902ffdd9cfdd1ae66212ee", +); +const LABELLED_MSG_HEX: &str = "313233343030"; +const LABEL_HEX: &str = "0000000000000000"; +/// tcId 12: "first byte of l_hash modified". +const INVALID_CT_HEX: &str = concat!( + "287d7108a1c6e7a18acb0045b20c57cdf2ac03456b44942764a7a9e9fdf3db48", + "1d7e202e4c8d733b56b9c1e93d71e791af8325c9363df789b252a5ed0eddc79e", + "76fa41c2cb0a35618398217a390a5e6d99eed905d5554d19c1cf4e30bdf1c2fc", + "c5148b641d71b3f1977b63d232648ddd935ec9499a53ac2fbcac55f462e91065", + "adaa018a39c453ba759bd68b454074153421e2ce75cf149f748b5b84758df8a4", + "23d1c50c880af863f2a6df3cd465ca36aa2152b5771f3d507f4a4dd9f8006d80", + "eca23537092287976f218a90df1e16d889fe31e79f7309f3224f613e9b52479f", + "e73b7aad915319a3b62a5936649f7d015d7b09f7fa9f454f78a7c3dd4bf791e0", +); + +/// A fresh scratch file path holding `bytes`. +fn temp_file(name: &str, bytes: &[u8]) -> String { + static COUNTER: AtomicUsize = AtomicUsize::new(0); + let n = COUNTER.fetch_add(1, Ordering::Relaxed); + let path: PathBuf = + std::env::temp_dir().join(format!("bc-rust-oaep-{}-{n}-{name}", std::process::id())); + std::fs::write(&path, bytes).unwrap(); + path.to_string_lossy().into_owned() +} + +fn sk_file() -> String { + temp_file("sk", &unhex(SK_HEX)) +} + +fn pk_file() -> String { + temp_file("pk", &unhex(PK_HEX)) +} + +#[test] +fn recover_matches_the_wycheproof_vectors() { + let sk = sk_file(); + let ct = temp_file("ct", &unhex(CT_HEX)); + let out = run_ok(&["rsa-oaep-2048", "recover", "--skfile", &sk, "--ctfile", &ct, "-x"], b""); + assert_eq!(String::from_utf8(out).unwrap(), MSG_HEX); + // The ciphertext on stdin, and raw output. + let out = run_ok(&["rsa-oaep-2048", "recover", "--skfile", &sk], &unhex(CT_HEX)); + assert_eq!(tohex(&out), MSG_HEX); + + // A labelled ciphertext recovers under its label and under no other. + let ct = temp_file("ct-label", &unhex(LABELLED_CT_HEX)); + let args = ["rsa-oaep-2048", "recover", "--skfile", &sk, "--ctfile", &ct, "-x"]; + let out = run_ok(&[&args[..], &["--label", LABEL_HEX]].concat(), b""); + assert_eq!(String::from_utf8(out).unwrap(), LABELLED_MSG_HEX); + assert!(run_err(&args, b"").contains("decryption failed")); + assert!(run_err(&[&args[..], &["--label", "00"]].concat(), b"").contains("decryption failed")); +} + +/// Every failure reads the same, whatever was wrong with the ciphertext. +#[test] +fn a_bad_ciphertext_is_one_error() { + let sk = sk_file(); + for ct in [unhex(INVALID_CT_HEX), vec![0xFFu8; 256]] { + let ct = temp_file("bad", &ct); + for action in ["recover", "decaps"] { + let err = run_err(&["rsa-oaep-2048", action, "--skfile", &sk, "--ctfile", &ct], b""); + assert_eq!(err.trim(), "Error: RSAES-OAEP-2048 decryption failed.", "{action}"); + } + } + // Under another hash the valid ciphertext is a bad one too. + let ct = temp_file("ct", &unhex(CT_HEX)); + for extra in [["--hash", "sha384"], ["--mgf-hash", "sha1"]] { + let args = ["rsa-oaep-2048", "recover", "--skfile", &sk, "--ctfile", &ct]; + let err = run_err(&[&args[..], &extra[..]].concat(), b""); + assert_eq!(err.trim(), "Error: RSAES-OAEP-2048 decryption failed."); + } + // A ciphertext of the wrong length is refused before the key is used. + let short = temp_file("short", &[0u8; 255]); + let err = run_err(&["rsa-oaep-2048", "recover", "--skfile", &sk, "--ctfile", &short], b""); + assert!(err.contains("255 bytes"), "{err}"); +} + +#[test] +fn transport_and_recover_round_trip() { + let (sk, pk) = (sk_file(), pk_file()); + let key = unhex("000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f"); + for extra in [ + vec![], + vec!["--label", "6c6162656c"], + vec!["--hash", "sha1"], + vec!["--hash", "sha512", "--mgf-hash", "sha1"], + vec!["--hash", "sha512-256", "--mgf-hash", "sha224"], + ] { + let transport = ["rsa-oaep-2048", "transport", "--pkfile", &pk]; + let ct = run_ok(&[&transport[..], &extra[..]].concat(), &key); + assert_eq!(ct.len(), 256, "{extra:?}"); + // Two transports of one key are two ciphertexts. + assert_ne!(ct, run_ok(&[&transport[..], &extra[..]].concat(), &key), "{extra:?}"); + let recover = ["rsa-oaep-2048", "recover", "--skfile", &sk]; + assert_eq!(run_ok(&[&recover[..], &extra[..]].concat(), &ct), key, "{extra:?}"); + } + // To a file, in hex, and back with --hex-input. + let ct = temp_file("ct-out", b""); + run_ok(&["rsa-oaep-2048", "transport", "--pkfile", &pk, "--ctfile", &ct, "-x"], &key); + assert_eq!(std::fs::read(&ct).unwrap().len(), 512); + let args = ["--hex-input", "rsa-oaep-2048", "recover", "--ctfile", &ct, "--skfile"]; + let sk_hex = temp_file("sk-hex", SK_HEX.as_bytes()); + assert_eq!(run_ok(&[&args[..], &[sk_hex.as_str()]].concat(), b""), key); +} + +/// SHA-256 at RSA-2048 carries k - 2hLen - 2 = 190 bytes and no more. +#[test] +fn the_longest_key_is_190_bytes() { + let (sk, pk) = (sk_file(), pk_file()); + let key = vec![0x5Au8; 190]; + let ct = run_ok(&["rsa-oaep-2048", "transport", "--pkfile", &pk], &key); + assert_eq!(run_ok(&["rsa-oaep-2048", "recover", "--skfile", &sk], &ct), key); + let err = run_err(&["rsa-oaep-2048", "transport", "--pkfile", &pk], &[0x5Au8; 191]); + assert!(err.contains("at most 190 bytes"), "{err}"); +} + +#[test] +fn encaps_and_decaps_agree_and_interoperate_with_recover() { + let (sk, pk) = (sk_file(), pk_file()); + // Without --ctfile: the ciphertext and then the key, in hex, one per line. + let out = + String::from_utf8(run_ok(&["rsa-oaep-2048", "encaps", "--pkfile", &pk], b"")).unwrap(); + let (ct_hex, key_hex) = out.split_once('\n').expect("two lines"); + assert_eq!((ct_hex.len(), key_hex.len()), (512, 64)); + let ct = temp_file("kem-ct", &unhex(ct_hex)); + let key = run_ok(&["rsa-oaep-2048", "decaps", "--skfile", &sk, "--ctfile", &ct, "-x"], b""); + assert_eq!(String::from_utf8(key).unwrap(), key_hex); + // The KEM's ciphertext is a transported 32-byte key. + let key = run_ok(&["rsa-oaep-2048", "recover", "--skfile", &sk, "--ctfile", &ct, "-x"], b""); + assert_eq!(String::from_utf8(key).unwrap(), key_hex); + // And a transported key of another length is not one the KEM accepts. + let ct = run_ok(&["rsa-oaep-2048", "transport", "--pkfile", &pk], &[7u8; 16]); + let err = run_err(&["rsa-oaep-2048", "decaps", "--skfile", &sk], &ct); + assert_eq!(err.trim(), "Error: RSAES-OAEP-2048 decryption failed."); +} + +#[test] +fn the_files_each_action_needs_are_asked_for() { + let pk = pk_file(); + assert!(run_err(&["rsa-oaep-2048", "keygen"], b"").contains("no pkfile")); + assert!(run_err(&["rsa-oaep-2048", "transport"], b"key").contains("no pkfile")); + assert!(run_err(&["rsa-oaep-2048", "recover"], &[0u8; 256]).contains("no skfile")); + assert!(run_err(&["rsa-oaep-2048", "decaps"], &[0u8; 256]).contains("no skfile")); + let err = run_err(&["rsa-oaep-2048", "transport", "--pkfile", &pk, "--label", "xyz"], b"key"); + assert!(err.contains("`--label` must be hex"), "{err}"); + // The four sizes are listed. + let help = String::from_utf8(run_ok(&["--help"], b"")).unwrap(); + for size in ["2048", "3072", "4096", "8192"] { + assert!(help.contains(&format!("rsa-oaep-{size}")), "{size}"); + } + let _ = BC_RUST; +} diff --git a/cli/tests/test_sha1.sh b/cli/tests/test_sha1.sh new file mode 100755 index 000000000..0980cd69d --- /dev/null +++ b/cli/tests/test_sha1.sh @@ -0,0 +1,37 @@ +#!/usr/bin/env bash +# The sha1 subcommand against RFC 3174 Section 7.3's test results. +# +# Every expected value is copied from the RFC, none is typed by hand. Follows lib.sh's +# conventions: each test_* runs in its own subshell under `set -e`. + +source "$(dirname "${BASH_SOURCE[0]}")/lib.sh" + +# RFC 3174 Section 7.3, TEST1: "abc". +test_sha1_matches_rfc_3174_test1() { + local got + got=$(printf 'abc' | hex_out "$BC_RUST" sha1 -x) + assert_eq "$got" "a9993e364706816aba3e25717850c26c9cd0d89d" "SHA-1 of abc" +} + +# TEST2: 56 bytes, so the padding takes a second block. +test_sha1_matches_rfc_3174_test2() { + local got + got=$(printf 'abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq' | hex_out "$BC_RUST" sha1 -x) + assert_eq "$got" "84983e441c3bd26ebaae4aa1f95129e5e54670f1" "SHA-1 of TEST2" +} + +# TEST4: "01234567" repeated 80 times, ten blocks. +test_sha1_matches_rfc_3174_test4() { + local got + got=$(printf '01234567%.0s' $(seq 80) | hex_out "$BC_RUST" sha1 -x) + assert_eq "$got" "dea356a2cddd90c7a7ecedc5ebb563934f460452" "SHA-1 of TEST4" +} + +test_sha1_binary_output_matches_hex_output() { + rng 3000 >"$TMP/msg" + "$BC_RUST" sha1 <"$TMP/msg" >"$TMP/bin" + assert_size "$TMP/bin" 21 "20 digest bytes plus a newline" + assert_eq "$(head -c 20 "$TMP/bin" | "$BC_RUST" hex-encode)" "$(hex_out "$BC_RUST" sha1 -x <"$TMP/msg")" "binary and hex agree across chunk boundaries" +} + +run_all diff --git a/crypto/core-test-framework/src/kem.rs b/crypto/core-test-framework/src/kem.rs index 1d573bec9..6fe6e1bea 100644 --- a/crypto/core-test-framework/src/kem.rs +++ b/crypto/core-test-framework/src/kem.rs @@ -55,10 +55,13 @@ impl TestFrameworkKEM { assert_eq!(PK::Algorithm::ALG_NAME, SK::Algorithm::ALG_NAME); assert_eq!(PK::Algorithm::MAX_SECURITY_STRENGTH, SK::Algorithm::MAX_SECURITY_STRENGTH); - // The seed cycles, so it is longer than one draw: a 32-byte encapsulation message drawn - // twice from a 32-byte constant seed would repeat, and the "two encapsulations differ" - // check below would fail. - let mut rng = FixedSeedRNG::new(core::array::from_fn::(|i| i as u8)); + // The seed cycles, so it is longer than two draws of the largest KEM's randomness (RSASVE + // over RSA-8192 draws 1024 bytes per encapsulation), and it does not repeat within + // itself (a counting byte pattern repeats every 256 bytes, so two 256-byte draws from it + // are identical): otherwise the "two encapsulations differ" check below would fail. + let mut rng = FixedSeedRNG::new(core::array::from_fn::(|i| { + ((i as u64).wrapping_mul(0x9E37_79B9_7F4A_7C15) >> 56) as u8 + })); let (pk, sk) = keygen().unwrap(); // one-shots diff --git a/crypto/core-test-framework/src/key_transport.rs b/crypto/core-test-framework/src/key_transport.rs new file mode 100644 index 000000000..373106d2a --- /dev/null +++ b/crypto/core-test-framework/src/key_transport.rs @@ -0,0 +1,139 @@ +//! Generic behaviour tests for the key-transport role traits of +//! `bouncycastle_core::key_transport_key`. + +use bouncycastle_core::errors::{KeyMaterialError, KeyTransportError}; +use bouncycastle_core::hazmat::FixedSeedRNG; +use bouncycastle_core::key_material::{KeyMaterial, KeyMaterialTrait, KeyType}; +use bouncycastle_core::key_transport_key::{KeyTransportDecryptingKey, KeyTransportEncryptingKey}; +use bouncycastle_core::security_strength::SecurityStrength; +use bouncycastle_core::traits::Algorithm; +use bouncycastle_utils::min; + +/// Instance of the test framework. +pub struct TestFrameworkKeyTransport { + /// Whether two transports of one key give two ciphertexts. + alg_is_randomized: bool, +} + +impl TestFrameworkKeyTransport { + /// + pub fn new(alg_is_randomized: bool) -> Self { + Self { alg_is_randomized } + } + + /// Every member of [`KeyTransportEncryptingKey`] and [`KeyTransportDecryptingKey`] for the + /// key pairs given, over the parameter type of `params`, which every call takes a copy of. + /// `other_sk` is the private key of another pair. A damaged ciphertext is checked at byte + /// 17, so a ciphertext must be longer than that, and the algorithm must carry a 32-byte + /// key. + pub fn test( + &self, + pk: &PK, + sk: &SK, + other_sk: &SK, + params: Params, + ) where + Params: Copy, + PK: KeyTransportEncryptingKey, + SK: KeyTransportDecryptingKey, + { + // Both roles must name the same algorithm. + assert_eq!(PK::Algorithm::ALG_NAME, SK::Algorithm::ALG_NAME); + assert_eq!(PK::Algorithm::MAX_SECURITY_STRENGTH, SK::Algorithm::MAX_SECURITY_STRENGTH); + + // A seed that does not repeat within itself, so consecutive draws differ. + let mut rng = FixedSeedRNG::new(core::array::from_fn::(|i| { + ((i as u64).wrapping_mul(0x9E37_79B9_7F4A_7C15) >> 56) as u8 + })); + let key_bytes: [u8; 32] = core::array::from_fn(|i| 0xA0 ^ i as u8); + let key = + KeyMaterial::<32>::from_bytes_as_type(&key_bytes, KeyType::SymmetricCipherKey).unwrap(); + let max = pk.max_key_len(params); + assert!(max >= 32, "the algorithm must carry a 32-byte key"); + + // A round trip, by value and into a stale buffer; the count is the ciphertext's length. + let ct = pk.transport(&mut rng, params, &key).unwrap(); + let mut ct_out = [0xFFu8; CT_LEN]; + assert_eq!(pk.transport_out(&mut rng, params, &key, &mut ct_out), Ok(CT_LEN)); + if self.alg_is_randomized { + assert_ne!(ct, ct_out, "two transports of one key must differ"); + } else { + assert_eq!(ct, ct_out); + } + for ct in [&ct, &ct_out] { + let mut recovered = KeyMaterial::<64>::from_bytes(&[0xEE; 64]).unwrap(); + assert_eq!(sk.recover_out(ct, params, &mut recovered), Ok(32)); + assert_eq!(recovered.ref_to_bytes(), key_bytes); + // The key comes back as full-entropy material at the lesser of the algorithm's + // strength and what 32 bytes carry. + assert_eq!(recovered.key_type(), KeyType::CryptographicRandom); + let expected = + *min(&PK::Algorithm::MAX_SECURITY_STRENGTH, &SecurityStrength::from_bytes(32)); + assert_eq!(recovered.security_strength(), expected); + } + // Into a buffer of exactly the key's length. + let mut exact = KeyMaterial::<32>::new(); + assert_eq!(sk.recover_out(&ct, params, &mut exact), Ok(32)); + assert_eq!(exact.ref_to_bytes(), key_bytes); + + // A key longer than the recipient's buffer, a damaged ciphertext and another private + // key are the one error, with the buffer left zeroized. + let failures: [(&SK, [u8; CT_LEN]); 2] = [(sk, damaged(&ct)), (other_sk, ct)]; + for (sk, ct) in failures { + let mut recovered = KeyMaterial::<64>::from_bytes(&[0xEE; 64]).unwrap(); + assert_eq!( + sk.recover_out(&ct, params, &mut recovered), + Err(KeyTransportError::DecryptionFailed) + ); + assert_eq!(recovered.key_type(), KeyType::Zeroized); + } + let mut short = KeyMaterial::<31>::from_bytes(&[0xEE; 31]).unwrap(); + assert_eq!( + sk.recover_out(&ct, params, &mut short), + Err(KeyTransportError::DecryptionFailed) + ); + assert_eq!(short.key_type(), KeyType::Zeroized); + + // The longest key goes through; one byte more does not, and neither does a zeroized + // key, each leaving the ciphertext buffer zeroized. + let longest = + KeyMaterial::<4096>::from_bytes_as_type(&vec![0x5A; max], KeyType::Seed).unwrap(); + let ct = pk.transport(&mut rng, params, &longest).unwrap(); + let mut recovered = KeyMaterial::<4096>::new(); + assert_eq!(sk.recover_out(&ct, params, &mut recovered), Ok(max)); + assert_eq!(recovered.ref_to_bytes(), longest.ref_to_bytes()); + let too_long = + KeyMaterial::<4096>::from_bytes_as_type(&vec![0x5A; max + 1], KeyType::Seed).unwrap(); + let mut ct_out = [0xFFu8; CT_LEN]; + assert_eq!( + pk.transport_out(&mut rng, params, &too_long, &mut ct_out), + Err(KeyTransportError::KeyTooLong) + ); + assert_eq!(ct_out, [0u8; CT_LEN]); + let mut ct_out = [0xFFu8; CT_LEN]; + assert_eq!( + pk.transport_out(&mut rng, params, &KeyMaterial::<32>::new(), &mut ct_out), + Err(KeyTransportError::KeyMaterialError(KeyMaterialError::ActingOnZeroizedKey)) + ); + assert_eq!(ct_out, [0u8; CT_LEN]); + + // An RNG below the algorithm's strength is refused. + if PK::Algorithm::MAX_SECURITY_STRENGTH > SecurityStrength::None { + let mut weak = FixedSeedRNG::new([0x5A; 64]); + weak.set_security_strength(SecurityStrength::None); + let mut ct_out = [0xFFu8; CT_LEN]; + assert!(matches!( + pk.transport_out(&mut weak, params, &key, &mut ct_out), + Err(KeyTransportError::RNGError(_)) + )); + assert_eq!(ct_out, [0u8; CT_LEN]); + } + } +} + +/// `ct` with one bit of byte 17 flipped. +fn damaged(ct: &[u8; CT_LEN]) -> [u8; CT_LEN] { + let mut ct = *ct; + ct[17] ^= 0x04; + ct +} diff --git a/crypto/core-test-framework/src/lib.rs b/crypto/core-test-framework/src/lib.rs index b68ebaf4d..a240bd4bb 100644 --- a/crypto/core-test-framework/src/lib.rs +++ b/crypto/core-test-framework/src/lib.rs @@ -23,6 +23,7 @@ pub mod kdf; pub mod kem; pub mod key_agreement; pub mod key_stream; +pub mod key_transport; pub mod key_wrap; pub mod mac; pub mod signature; diff --git a/crypto/core-test-framework/src/test_data_loaders.rs b/crypto/core-test-framework/src/test_data_loaders.rs index 7c09ceaff..7e0f399a0 100644 --- a/crypto/core-test-framework/src/test_data_loaders.rs +++ b/crypto/core-test-framework/src/test_data_loaders.rs @@ -7,6 +7,10 @@ //! returns early, so `cargo test` passes for someone who has cloned only this repository. When a //! repository is present, a file missing from it is a failure rather than a skip. //! +//! bc-test-data also carries copies of some Wycheproof files, in `crypto/wycheproof`. Without the +//! Wycheproof checkout, [`wycheproof`] reads those; a file that has not been copied there is then +//! skipped, since the copies are a selection. +//! //! The paths are resolved from this crate's manifest directory, which is at the same depth as every //! crate under `crypto/`, so they do not depend on the directory `cargo test` runs in. Under //! `cargo mutants`, which copies the tree into `/tmp`, they resolve to `/tmp/bc-test-data` and @@ -28,6 +32,9 @@ const WYCHEPROOF_ROOT: &str = static BC_TEST_DATA_CHECK: Once = Once::new(); static WYCHEPROOF_CHECK: Once = Once::new(); +/// Where bc-test-data keeps its copies of Wycheproof files. +const WYCHEPROOF_COPIES_DIR: &str = "crypto/wycheproof"; + /// Returns the contents of `bc-test-data//`, or `None` (after a one-time warning) /// if bc-test-data is not cloned beside this repository. /// @@ -36,12 +43,27 @@ pub fn bc_test_data(dir: &str, filename: &str) -> Option { read(BC_TEST_DATA_ROOT, &BC_TEST_DATA_CHECK, "bc-test-data", &format!("{dir}/{filename}")) } -/// Returns the contents of `wycheproof/testvectors_v1/`, or `None` (after a one-time -/// warning) if Wycheproof is not cloned beside this repository. +/// Returns the contents of `wycheproof/testvectors_v1/`, or, if Wycheproof is not cloned +/// beside this repository, of bc-test-data's copy of that file. `None` (after a one-time warning) +/// if neither is there. /// /// Panics if Wycheproof is present but the file cannot be read. pub fn wycheproof(filename: &str) -> Option { - read(WYCHEPROOF_ROOT, &WYCHEPROOF_CHECK, "wycheproof", filename) + if Path::new(WYCHEPROOF_ROOT).is_dir() { + return read(WYCHEPROOF_ROOT, &WYCHEPROOF_CHECK, "wycheproof", filename); + } + let copies = format!("{BC_TEST_DATA_ROOT}/{WYCHEPROOF_COPIES_DIR}"); + WYCHEPROOF_CHECK.call_once(|| { + println!( + "WARNING: wycheproof not found at {WYCHEPROOF_ROOT}; reading the copies in {copies}, \ + and tests that need a file not copied there will be skipped" + ); + }); + let path = format!("{copies}/{filename}"); + if !Path::new(&path).is_file() { + return None; + } + Some(fs::read_to_string(&path).unwrap_or_else(|e| panic!("{path} is unreadable: {e}"))) } /// [`bc_test_data`], parsed as JSON. diff --git a/crypto/core/src/errors.rs b/crypto/core/src/errors.rs index 3e75aac64..e73fc22fd 100644 --- a/crypto/core/src/errors.rs +++ b/crypto/core/src/errors.rs @@ -88,6 +88,21 @@ pub enum KEMError { KDFError(KDFError), } +/// Errors of the key-transport roles ([`crate::key_transport_key`]). +#[derive(Debug, PartialEq, Eq)] +#[non_exhaustive] +pub enum KeyTransportError { + /// The key is longer than the algorithm can carry under these parameters. + KeyTooLong, + /// The ciphertext did not decrypt to a key, for whatever reason: the one error a recipient + /// reports, so that the causes cannot be told apart. + DecryptionFailed, + /// The key to transport is not usable, or the recovered key could not be typed. + KeyMaterialError(KeyMaterialError), + /// The RNG refused or failed to deliver, or is weaker than the algorithm requires. + RNGError(RNGError), +} + /// Errors of the key-agreement traits ([`crate::agreement_key`], [`crate::traits::KeyAgreement`]). #[derive(Debug, PartialEq, Eq)] #[non_exhaustive] @@ -176,8 +191,10 @@ pub enum SignatureError { /// The pre-hash is weaker than the parameter set (FIPS 204 Section 5.4 for HashML-DSA). PreHashTooWeak, /// A value the algorithm computed failed the check the algorithm makes on its own results - /// before releasing them, such as a point that is not on the curve. No input causes it: it - /// means a fault in the computation, and nothing was written. + /// before releasing them, such as a point that is not on the curve, or an RSA result that + /// the public exponent does not take back to its input. No message causes it: it means a + /// fault in the computation, or a private key whose parts do not belong together, and + /// nothing was written. ComputationFault, /// EncodingError(&'static str), @@ -389,3 +406,15 @@ impl From for SignatureError { Self::RNGError(e) } } + +impl From for KeyTransportError { + fn from(e: KeyMaterialError) -> Self { + Self::KeyMaterialError(e) + } +} + +impl From for KeyTransportError { + fn from(e: RNGError) -> Self { + Self::RNGError(e) + } +} diff --git a/crypto/core/src/key_transport_key.rs b/crypto/core/src/key_transport_key.rs new file mode 100644 index 000000000..038161819 --- /dev/null +++ b/crypto/core/src/key_transport_key.rs @@ -0,0 +1,76 @@ +//! The roles of key transport: a public key that encrypts a key the sender already holds to +//! its owner, and the private key that recovers it. This is the other way to establish a key +//! with a public-key encryption scheme; a KEM ([`crate::kem_key`]) generates the key itself. +//! +//! As with the KEM roles, the algorithm's parameters are the role's type parameter, so the +//! argument selects the algorithm a key runs: `pk.transport(&mut rng, params, &key)`. + +use crate::errors::KeyTransportError; +use crate::key_material::{KeyMaterial, KeyMaterialTrait}; +use crate::traits::{Algorithm, RNG}; + +/// Marks an [`Algorithm`] as a key-transport scheme: what the roles name. +pub trait KeyTransportAlgorithm: Algorithm {} + +/// A public key that transports keys to its owner under `Params`, as `CT_LEN`-byte +/// ciphertexts. +pub trait KeyTransportEncryptingKey { + /// The algorithm the key runs under these parameters. + type Algorithm: KeyTransportAlgorithm; + + /// The longest key, in bytes, that `params` let this key carry. + fn max_key_len(&self, params: Params) -> usize; + + /// Encrypts `key` to the owner of this public key into `ct`, which is zeroized first and + /// left so on an error, and returns the number of bytes written, always `CT_LEN`. + /// + /// # Errors + /// * [`KeyTransportError::KeyTooLong`] if `key` is longer than + /// [`max_key_len`](Self::max_key_len). + /// * [`KeyTransportError::KeyMaterialError`] if `key` is zeroized. + /// * [`KeyTransportError::RNGError`] if the RNG is weaker than the algorithm or fails. + fn transport_out( + &self, + rng: &mut dyn RNG, + params: Params, + key: &dyn KeyMaterialTrait, + ct: &mut [u8; CT_LEN], + ) -> Result; + + /// [`transport_out`](Self::transport_out) returning the ciphertext. + /// + /// # Errors + /// As [`transport_out`](Self::transport_out). + fn transport( + &self, + rng: &mut dyn RNG, + params: Params, + key: &dyn KeyMaterialTrait, + ) -> Result<[u8; CT_LEN], KeyTransportError> { + let mut ct = [0u8; CT_LEN]; + self.transport_out(rng, params, key, &mut ct)?; + Ok(ct) + } +} + +/// A private key that recovers the keys transported to it under `Params`. +pub trait KeyTransportDecryptingKey { + /// The algorithm the key runs under these parameters. + type Algorithm: KeyTransportAlgorithm; + + /// Recovers the key in `ct` into `key`, which is zeroized first and left so on an error, + /// and returns its length in bytes. The key comes back as + /// [`KeyType::CryptographicRandom`](crate::key_material::KeyType) at the lesser of the + /// algorithm's strength and what its length carries: the scheme transports bytes, not their + /// type, and does not say who sent them. + /// + /// # Errors + /// [`KeyTransportError::DecryptionFailed`] if `ct` is not a ciphertext for this key under + /// `params`, or holds a key longer than `N` bytes; the causes are not distinguished. + fn recover_out( + &self, + ct: &[u8; CT_LEN], + params: Params, + key: &mut KeyMaterial, + ) -> Result; +} diff --git a/crypto/core/src/lib.rs b/crypto/core/src/lib.rs index 1a7694095..4d6a42e97 100644 --- a/crypto/core/src/lib.rs +++ b/crypto/core/src/lib.rs @@ -19,6 +19,7 @@ pub mod hex; pub mod kdf_params; pub mod kem_key; pub mod key_material; +pub mod key_transport_key; mod provided; pub mod security_strength; pub mod signature_key; diff --git a/crypto/digest/Cargo.toml b/crypto/digest/Cargo.toml index a669e0551..38bdd08f0 100644 --- a/crypto/digest/Cargo.toml +++ b/crypto/digest/Cargo.toml @@ -80,3 +80,7 @@ harness = false [[bench]] name = "blake3_blake3_benches" harness = false + +[[bench]] +name = "sha1_sha1_benches" +harness = false diff --git a/crypto/digest/benches/sha1_sha1_benches.rs b/crypto/digest/benches/sha1_sha1_benches.rs new file mode 100644 index 000000000..98e59d2fa --- /dev/null +++ b/crypto/digest/benches/sha1_sha1_benches.rs @@ -0,0 +1,30 @@ +use criterion::{Criterion, Throughput, criterion_group, criterion_main}; +use std::hint::black_box; + +use bouncycastle_core::traits::{Hash, RNG}; +use bouncycastle_digest::sha1::SHA1; +use bouncycastle_rng as rng; + +fn bench_sha1(c: &mut Criterion) { + let mut data = [0_u8; 1024]; + rng::DefaultRNG::default().next_bytes_out(&mut data).unwrap(); + + let mut digest = vec![0; SHA1::new().output_len()]; + + let mut group = c.benchmark_group("sha1"); + group.throughput(Throughput::Bytes(16 * 1024)); + group.bench_function("16KiB", |b| { + b.iter(|| { + let mut md = SHA1::new(); + for _ in 0..16 { + md.do_update(black_box(&data)); + } + _ = md.do_final_out(&mut digest); + black_box(&digest); + }) + }); + group.finish(); +} + +criterion_group!(benches, bench_sha1); +criterion_main!(benches); diff --git a/crypto/digest/src/lib.rs b/crypto/digest/src/lib.rs index c0636295a..5980692dc 100644 --- a/crypto/digest/src/lib.rs +++ b/crypto/digest/src/lib.rs @@ -5,6 +5,7 @@ //! | [`blake2`] | BLAKE2b-512 and BLAKE2s-256 (RFC 7693), unkeyed and keyed | //! | [`blake3`] | BLAKE3: hash, keyed hash, key derivation and XOF | //! | [`ripemd`] | RIPEMD-128, -160, -256 and -320, and HMAC over RIPEMD-160 | +//! | [`sha1`] | SHA-1 (FIPS 180-4), for existing protocols only | //! | [`sm3`] | SM3 (GB/T 32905-2016), with HMAC and HKDF over it | //! | [`pbkdf2`] | PBKDF2 (RFC 8018 Section 5.2) over HMAC | //! | [`scrypt`] | scrypt (RFC 7914) | @@ -47,5 +48,6 @@ pub mod concatkdf; pub mod pbkdf2; pub mod ripemd; pub mod scrypt; +pub mod sha1; pub mod sm3; pub mod x963kdf; diff --git a/crypto/digest/src/sha1/mod.rs b/crypto/digest/src/sha1/mod.rs new file mode 100644 index 000000000..47942c54e --- /dev/null +++ b/crypto/digest/src/sha1/mod.rs @@ -0,0 +1,120 @@ +//! Implements SHA-1 as per FIPS 180-4, for the protocols that still name it. +//! +//! SHA-1 is here so that existing data and peers can be interoperated with: a mask generation +//! function or a label hash an older RSA-OAEP peer chose, a fingerprint, a legacy key +//! identifier. It is not for new designs; see [Security Considerations](#-security-considerations-). +//! +//! # Usage Examples +//! +//! Hash functionality is accessed via the [`Hash`] trait, which is implemented by [`SHA1`]. +//! +//! The simplest usage is via the one-shot functions. +//! ``` +//! use bouncycastle_core::traits::HashOneShot; +//! use bouncycastle_digest::sha1::SHA1; +//! +//! let output: Vec = SHA1::hash(b"abc"); +//! ``` +//! +//! It also has a streaming API that can accept input in chunks of any size. +//! +//! ``` +//! use bouncycastle_core::traits::Hash; +//! use bouncycastle_digest::sha1::SHA1; +//! +//! let data: &[u8] = b"\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0A\x0B\x0C\x0D\x0E\x0F +//! \x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1A\x1B\x1C\x1D\x1E\x1F"; +//! let mut sha1 = SHA1::new(); +//! +//! for chunk in data.chunks(16) { +//! sha1.do_update(chunk); +//! } +//! +//! let output: Vec = sha1.do_final(); +//! ``` +//! +//! A bit-oriented message (FIPS 180-4 s. 5.1) is finished with +//! [`do_final_partial_bits`](Hash::do_final_partial_bits), the trailing bits being the most +//! significant bits of the last byte, as in the SHA-2 crate. A computation in progress can be +//! suspended and resumed through [`Suspendable`], also as there. +//! +//! # Memory Usage +//! +//! No heap memory is used by the algorithm itself; the `Vec`-returning convenience methods +//! allocate only the output buffer, and the `*_out` variants allocate nothing. +//! +//! | Object | Size (bytes) | +//! |-----------------|--------------| +//! | `SHA1` | 104 | +//! | Suspended state | 96 | +//! +//! The object holds the 5-word hash value plus one 64-byte block of buffered input. +//! +//! Per-call stack usage does not depend on the data length. The figures are the frames the +//! compiler reports for the release build (x86-64 Linux, rustc 1.97.0-nightly), summed down +//! each entry point's deepest call path with a return address per call; the compression +//! function, with its 80-word message schedule, is 264 bytes of every one (see +//! `mem_usage_benches/src/bench_sha1_mem_usage.rs`): +//! +//! | Entry point | Stack | +//! |------------------------------------------|---------| +//! | `SHA1::do_update` | 328 B | +//! | `SHA1::do_final_out` | 352 B | +//! | `SHA1::do_final_partial_bits_out` | 376 B | +//! | `SHA1::hash_out` (one-shot) | 584 B | +//! | `SHA1::suspend` / `SHA1::from_suspended` | 8 / 8 B | +//! +//! # 🚨 Security Considerations 🚨 +//! +//! * **SHA-1 is not collision resistant.** Collisions have been published, and chosen-prefix +//! collisions are practical, so it must not be used where an attacker gains from two messages +//! with one digest: signatures, certificates, commitments, content addressing of untrusted +//! data. Its [`MAX_SECURITY_STRENGTH`](Algorithm::MAX_SECURITY_STRENGTH) is +//! [`SecurityStrength::None`] for that reason, and it does not carry +//! [`CollisionResistantHash`](bouncycastle_core::traits::CollisionResistantHash), which the +//! library's signing roles require: a signature over SHA-1 verifies and is not generated, +//! unless the caller names the hash as +//! [`WithoutCollisionResistance`](bouncycastle_core::hazmat::WithoutCollisionResistance). +//! * Uses that do not rest on collision resistance, such as MGF1 and the label hash of RSA-OAEP, +//! are not broken by the collision attacks, but offer no reason to choose SHA-1 over SHA-2 +//! where the choice is open. +//! * SHA-1 is a Merkle-Damgard construction and is subject to length extension: `H(k || m)` is +//! not a MAC. +//! * The hash value and input buffer are held in [`bouncycastle_utils::secret::Secret`] and +//! zeroized on drop. The message schedule and working variables on the stack during +//! compression are not zeroized. +//! * The implementation contains no data-dependent branches or table lookups. +//! * Message length: FIPS 180-4 permits messages shorter than 2^64 bits, so this implementation +//! supports 2^61 - 1 bytes. + +mod sha1; + +pub use self::sha1::{SHA1, SUSPENDED_SHA1_STATE_LEN}; +use bouncycastle_core::security_strength::SecurityStrength; +use bouncycastle_core::traits::{Algorithm, AlgorithmOID, HashAlgParams}; + +/*** Imports needed for docs ***/ +#[allow(unused_imports)] +use bouncycastle_core::traits::{Hash, Suspendable}; + +/// Algorithm name string for SHA-1, as used by the CLI. +pub const SHA1_NAME: &str = "SHA1"; + +/// SHA-1 is credited with no security strength: see the module's Security Considerations. +impl Algorithm for SHA1 { + const ALG_NAME: &'static str = SHA1_NAME; + const MAX_SECURITY_STRENGTH: SecurityStrength = SecurityStrength::None; +} + +/// FIPS 180-4 Figure 1: 160-bit digest, 512-bit block. +impl HashAlgParams for SHA1 { + const OUTPUT_LEN: usize = 20; + const BLOCK_LEN: usize = 64; +} + +/// RFC 8017 Appendix B.1: id-sha1 { iso(1) identified-organization(3) oiw(14) secsig(3) +/// algorithms(2) 26 } +impl AlgorithmOID for SHA1 { + const OID: &'static [u32] = &[1, 3, 14, 3, 2, 26]; + const OID_DER: &'static [u8] = &[0x06, 0x05, 0x2B, 0x0E, 0x03, 0x02, 0x1A]; +} diff --git a/crypto/digest/src/sha1/sha1.rs b/crypto/digest/src/sha1/sha1.rs new file mode 100644 index 000000000..c1e5b991a --- /dev/null +++ b/crypto/digest/src/sha1/sha1.rs @@ -0,0 +1,331 @@ +use bouncycastle_core::errors::{HashError, SuspendableError}; +use bouncycastle_core::traits::{FinishToken, Hash, HashOneShot, Suspendable}; +use bouncycastle_utils::suspendable_state::{add_lib_ver, check_lib_ver}; +use bouncycastle_utils::{min, secret::Secret}; + +/// The digest length in bytes: FIPS 180-4 Figure 1, a 160-bit message digest. +const OUTPUT_LEN: usize = 20; + +/// FIPS 180-4 s. 4.2.1 (4.14): the constants K_t, one for each twenty rounds. +const K_0_19: u32 = 0x5A827999; +const K_20_39: u32 = 0x6ED9EBA1; +const K_40_59: u32 = 0x8F1BBCDC; +const K_60_79: u32 = 0xCA62C1D6; + +/// FIPS 180-4 Figure 1 and s. 6.1: SHA-1 is defined for a message of l bits where 0 <= l < 2^64, +/// so the longest whole-byte message it covers is 2^61 - 1 bytes. +const MAX_MESSAGE_BYTES: u64 = (1 << 61) - 1; + +/// FIPS 180-4 s. 5.3.1: the initial hash value H(0). +const SHA1_H0: [u32; 5] = [0x67452301, 0xEFCDAB89, 0x98BADCFE, 0x10325476, 0xC3D2E1F0]; + +/// FIPS 180-4 s. 4.1.1 (4.1), 0 <= t <= 19: Ch(x, y, z) = (x AND y) XOR (NOT x AND z). +/// Mutants note: the two masks are disjoint, so `^` and `|` give identical results here; a +/// surviving `^`/`|` swap in this function is an equivalent mutant, not a missing test. +#[inline] +const fn ch(x: u32, y: u32, z: u32) -> u32 { + (x & y) ^ (!x & z) +} + +/// FIPS 180-4 s. 4.1.1 (4.1), 20 <= t <= 39 and 60 <= t <= 79: Parity(x, y, z) = x XOR y XOR z. +#[inline] +const fn parity(x: u32, y: u32, z: u32) -> u32 { + x ^ y ^ z +} + +/// FIPS 180-4 s. 4.1.1 (4.1), 40 <= t <= 59: Maj(x, y, z) = (x AND y) XOR (x AND z) XOR (y AND z). +/// Written in the equivalent form (x AND y) OR (z AND (x XOR y)), which saves an operation. +/// Mutants note: the two masks are disjoint, so `^` and `|` give identical results here, and +/// (x AND y) OR (z AND (x OR y)) is the majority too; a surviving `^`/`|` swap in this function +/// is an equivalent mutant, not a missing test. +#[inline] +const fn maj(x: u32, y: u32, z: u32) -> u32 { + (x & y) | (z & (x ^ y)) +} + +/// FIPS 180-4 s. 6.1.2, one iteration of the outer loop: absorbs a single 512-bit message block +/// into the hash value `s` (H(i-1) in, H(i) out). +fn compress_block(s: &mut [u32; 5], block: &[u8; 64]) { + // FIPS 180-4 s. 6.1.2 step 1: prepare the message schedule {W_t}. + let mut w = [0u32; 80]; + // W_t = M_t(i) for 0 <= t <= 15 (s. 5.2.1: sixteen big-endian 32-bit words). + let (words, _remainder) = block.as_chunks::<4>(); + for (w_t, word) in w.iter_mut().zip(words) { + *w_t = u32::from_be_bytes(*word); + } + // W_t = ROTL1(W_t-3 XOR W_t-8 XOR W_t-14 XOR W_t-16) for 16 <= t <= 79. + for t in 16..80 { + w[t] = (w[t - 3] ^ w[t - 8] ^ w[t - 14] ^ w[t - 16]).rotate_left(1); + } + + // FIPS 180-4 s. 6.1.2 step 2: initialize the working variables a..e with H(i-1). + let [mut a, mut b, mut c, mut d, mut e] = *s; + + // FIPS 180-4 s. 6.1.2 step 3: for t = 0 to 79. The branch is on the round number, which is + // public. + for (t, w_t) in w.iter().enumerate() { + // f_t and K_t (s. 4.1.1 and s. 4.2.1). + let (f_t, k_t) = match t { + 0..=19 => (ch(b, c, d), K_0_19), + 20..=39 => (parity(b, c, d), K_20_39), + 40..=59 => (maj(b, c, d), K_40_59), + _ => (parity(b, c, d), K_60_79), + }; + // T = ROTL5(a) + f_t(b, c, d) + e + K_t + W_t + let t_word = + a.rotate_left(5).wrapping_add(f_t).wrapping_add(e).wrapping_add(k_t).wrapping_add(*w_t); + // e = d; d = c; c = ROTL30(b); b = a; a = T + e = d; + d = c; + c = b.rotate_left(30); + b = a; + a = t_word; + } + + // FIPS 180-4 s. 6.1.2 step 4: H_j(i) = (working variable j) + H_j(i-1). + s[0] = s[0].wrapping_add(a); + s[1] = s[1].wrapping_add(b); + s[2] = s[2].wrapping_add(c); + s[3] = s[3].wrapping_add(d); + s[4] = s[4].wrapping_add(e); +} + +/// SHA-1 (FIPS 180-4 s. 6.1). See the module docs before using it for anything new. +#[derive(Clone)] +pub struct SHA1 { + h: Secret<[u32; 5]>, + byte_count: u64, + x_buf: Secret<[u8; 64]>, + x_buf_off: usize, +} + +impl SHA1 { + /// Creates a new SHA1 instance, ready for use. + pub fn new() -> Self { + let mut h = Secret::<[u32; 5]>::new(); + // FIPS 180-4 s. 6.1.1 step 1: set the initial hash value H(0) (s. 5.3.1). + h.copy_from_slice(&SHA1_H0); + Self { h, byte_count: 0, x_buf: Secret::new(), x_buf_off: 0 } + } + + fn compress(&mut self, blocks: &[[u8; 64]]) { + // FIPS 180-4 s. 6.1.2: each message block M(1), ..., M(N) is processed in order. + for block in blocks { + compress_block(&mut self.h, block); + } + } + + /// Pads and compresses the final block(s) as per FIPS 180-4 s. 5.1.1, then writes the digest. + /// + /// The `num_partial_bits` (0..=7, validated by the caller) trailing message bits are the most + /// significant bits of `partial_byte`, leading bit first: the ASN.1 BIT STRING order of + /// X.690 s. 8.6.2.1, which is also how FIPS 180-4 s. 3.1 numbers the bits of a message byte. So + /// they are used in place, the low `8 - num_partial_bits` bits are ignored, and the mandatory + /// "1" padding bit follows the message bits immediately in the same byte. + /// + /// Returns the number of bytes written (`min(output.len(), OUTPUT_LEN)`); a shorter output buffer + /// truncates the digest, a longer one is zero-filled past the digest. + fn do_final_internal( + &mut self, + partial_byte: u8, + num_partial_bits: usize, + output: &mut [u8], + ) -> usize { + debug_assert!(num_partial_bits <= 7); + output.fill(0); + + let n = *min(&output.len(), &OUTPUT_LEN); + + // FIPS 180-4 s. 5.1.1: append the bit "1" to the end of the message. The message bits are the + // top num_partial_bits bits of partial_byte, so the final message byte is [those bits] [1] [0...]; + // with no partial bits this is the familiar 0x80. The mask is built in u16 so that the 8-bit + // shift for num_partial_bits == 0 cannot overflow (0xFF00 >> 0 truncates to 0x00). + let mask = (0xFF00u16 >> num_partial_bits) as u8; + // Mutants note: the masked message bits and the padding bit occupy disjoint bit positions, so + // `|` and `^` give identical results here; a surviving `|`/`^` swap is an equivalent mutant. + let pad_byte = (partial_byte & mask) | (0x80u8 >> num_partial_bits); + + self.x_buf[self.x_buf_off] = pad_byte; + self.x_buf_off += 1; + + // FIPS 180-4 s. 5.1.1: if fewer than 64 bits remain for l, the k zero bits run into a second block. + if self.x_buf_off > 56 { + self.x_buf[self.x_buf_off..].fill(0x00); + compress_block(&mut self.h, &self.x_buf); + self.x_buf_off = 0; + } + + // FIPS 180-4 s. 5.1.1: k zero bits so that l + 1 + k = 448 mod 512, then the 64-bit big-endian + // message length l in bits. + self.x_buf[self.x_buf_off..56].fill(0x00); + // byte_count is a byte counter, so l = (byte_count << 3) | num_partial_bits (the low three bits + // of byte_count << 3 are zero). + // Mutants note: the low three bits of byte_count << 3 are zero, so `|` and `^` give identical + // results here; a surviving `|`/`^` swap is an equivalent mutant. + let bit_len: u64 = (self.byte_count << 3) | (num_partial_bits as u64); + self.x_buf[56..64].copy_from_slice(&bit_len.to_be_bytes()); + compress_block(&mut self.h, &self.x_buf); + + // FIPS 180-4 s. 6.1.2: the digest is H_0(N) || ... || H_4(N) (big-endian words), truncated + // to the caller's buffer if that is shorter. + let h = &self.h; + for i in 0..(n / 4) { + output[i * 4..i * 4 + 4].copy_from_slice(&h[i].to_be_bytes()); + } + if !n.is_multiple_of(4) { + output[((n / 4) * 4)..((n / 4) * 4) + (n % 4)] + .copy_from_slice(&h[n / 4].to_be_bytes()[0..(n % 4)]); + } + + n + } +} + +impl Default for SHA1 { + fn default() -> Self { + Self::new() + } +} + +impl Hash for SHA1 { + /// As per FIPS 180-4 Figure 1 + fn block_bitlen(&self) -> usize { + 512 + } + + fn output_len(&self) -> usize { + OUTPUT_LEN + } + + fn do_update(&mut self, block: &[u8]) { + let len = block.len(); + + // FIPS 180-4 s. 5.1.1: do_final_internal encodes l in a 64-bit field as `byte_count << 3`, + // and a left shift discards rather than panics, so past MAX_MESSAGE_BYTES the digest would + // silently be that of a message 2^64 bits shorter. do_update returns (), hence debug-only. + debug_assert!( + self.byte_count.checked_add(len as u64).is_some_and(|total| total <= MAX_MESSAGE_BYTES), + "message exceeds the FIPS 180-4 limit of {MAX_MESSAGE_BYTES} bytes for SHA-1" + ); + self.byte_count += len as u64; + + let available = 64 - self.x_buf_off; + + if len < available { + self.x_buf[self.x_buf_off..self.x_buf_off + len].copy_from_slice(block); + self.x_buf_off += len; + return; + } + + let mut block = block; + if self.x_buf_off != 0 { + self.x_buf[self.x_buf_off..].copy_from_slice(&block[..available]); + block = &block[available..]; + + compress_block(&mut self.h, &self.x_buf); + } + + // FIPS 180-4 s. 5.2.1: the message is parsed into 512-bit blocks; a partial trailing block waits in x_buf. + let (chunks, remainder) = block.as_chunks::<64>(); + + self.compress(chunks); + + let remaining = remainder.len(); + self.x_buf[..remaining].copy_from_slice(remainder); + self.x_buf_off = remaining; + } + + fn finish_into(&mut self, _token: &FinishToken, output: &mut [u8]) -> usize { + // A whole-byte message is the zero-partial-bits case of the general padding. + self.do_final_internal(0, 0, output) + } + + /// FIPS 180-4 s. 5.1: bit-oriented messages. The `num_partial_bits` most significant bits of + /// `partial_byte` (ASN.1 BIT STRING order, leading bit first) are appended to the message before + /// padding; the low bits are ignored. `num_partial_bits == 0` behaves exactly like + /// [`Hash::do_final_out`]. + fn finish_partial_bits_into( + &mut self, + _token: &FinishToken, + partial_byte: u8, + num_partial_bits: usize, + output: &mut [u8], + ) -> Result { + if num_partial_bits > 7 { + return Err(HashError::InvalidLength("num_partial_bits must be in the range [0,7]")); + } + Ok(self.do_final_internal(partial_byte, num_partial_bits, output)) + } +} + +/// Length in bytes of the serialized state of SHA1. +pub const SUSPENDED_SHA1_STATE_LEN: usize = 96; + +impl Suspendable for SHA1 { + fn suspend(self) -> [u8; SUSPENDED_SHA1_STATE_LEN] { + let mut out_to_return = [0u8; SUSPENDED_SHA1_STATE_LEN]; + + // insert the version tag + // infallible: add_lib_ver returns a slice of exactly SUSPENDED_SHA1_STATE_LEN - 3 = 93 bytes. + let out: &mut [u8; 93] = add_lib_ver(&mut out_to_return).try_into().unwrap(); + + // h: [u32; 5], 4 * 5 = 20 + for i in 0..5 { + out[i * 4..(i * 4) + 4].copy_from_slice(&self.h[i].to_le_bytes()); + } + + // byte_count: u64 + out[20..28].copy_from_slice(&self.byte_count.to_le_bytes()); + + // x_buf: [u8; 64] + out[28..92].copy_from_slice(&*self.x_buf); + + // x_buf_off: usize; it is never larger than 63 + debug_assert!(self.x_buf_off < 64); + out[92] = self.x_buf_off as u8; + + out_to_return + } + + fn from_suspended( + serialized_state: [u8; SUSPENDED_SHA1_STATE_LEN], + ) -> Result { + // check the version tag + // infallible: check_lib_ver returns a slice of exactly SUSPENDED_SHA1_STATE_LEN - 3 = 93 bytes. + let input: &[u8; 93] = check_lib_ver(&serialized_state, None)?.try_into().unwrap(); + + // h: [u32; 5] + let mut h = Secret::<[u32; 5]>::new(); + for i in 0..5 { + h[i] = u32::from_le_bytes(input[i * 4..(i * 4) + 4].try_into().unwrap()); + } + + // byte_count: u64 + let byte_count: u64 = u64::from_le_bytes(input[20..28].try_into().unwrap()); + + // x_buf: [u8; 64] + let mut x_buf = Secret::<[u8; 64]>::new(); + x_buf.copy_from_slice(&input[28..92]); + + // x_buf_off: usize + let x_buf_off: usize = input[92] as usize; + if x_buf_off >= 64 { + return Err(SuspendableError::InvalidData); + } + // do_update keeps byte_count congruent to x_buf_off modulo the block length, so a state in + // which they disagree describes no message and must not resume. + if byte_count % 64 != x_buf_off as u64 { + return Err(SuspendableError::InvalidData); + } + // FIPS 180-4 s. 5.1.1 encodes the length in a 64-bit block, so a longer message cannot be + // finished correctly. + if byte_count > MAX_MESSAGE_BYTES { + return Err(SuspendableError::InvalidData); + } + + Ok(SHA1 { h, byte_count, x_buf, x_buf_off }) + } +} + +// The one-shot form: `Default` is the function itself. +impl HashOneShot for SHA1 {} diff --git a/crypto/digest/tests/sha1_collision_resistant_hash_tests.rs b/crypto/digest/tests/sha1_collision_resistant_hash_tests.rs new file mode 100644 index 000000000..e93c882e0 --- /dev/null +++ b/crypto/digest/tests/sha1_collision_resistant_hash_tests.rs @@ -0,0 +1,9 @@ +//! SHA-1 does not carry `CollisionResistantHash`, the marker a signature's hash needs. + +use bouncycastle_core_test_framework::assert_not_collision_resistant_hash; +use bouncycastle_digest::sha1::SHA1; + +#[test] +fn sha1_does_not_carry_the_marker() { + assert_not_collision_resistant_hash!(SHA1); +} diff --git a/crypto/digest/tests/sha1_sha1_bc-test-data.rs b/crypto/digest/tests/sha1_sha1_bc-test-data.rs new file mode 100644 index 000000000..4d7f67aa5 --- /dev/null +++ b/crypto/digest/tests/sha1_sha1_bc-test-data.rs @@ -0,0 +1,180 @@ +//! NIST CAVP SHAVS test vectors for SHA-1. +//! +//! Vectors are read from the bc-test-data repo (https://github.com/bcgit/bc-test-data), which must be +//! cloned alongside this repo at "../bc-test-data", under `crypto/sha1/{bit-oriented,byte-oriented}/`: +//! the `SHA1*.rsp` files of NIST's `shabittestvectors.zip` and `shabytetestvectors.zip`. If it is not +//! present, the tests print a warning and pass vacuously. +//! +//! The three SHAVS test types (ShortMsg, LongMsg and Monte) are run as the SHA-2 crate runs them; +//! see `crypto/sha2/tests/sha2_bc-test-data.rs` for what each is. + +use bouncycastle_core::hex; +use bouncycastle_core::traits::HashOneShot; +use bouncycastle_core_test_framework::test_data_loaders::bc_test_data; +use bouncycastle_digest::sha1::SHA1; + +/// Splits a `Key = value` line from a `.rsp` file. +fn kv(line: &str) -> Option<(&str, &str)> { + let (k, v) = line.split_once('=')?; + Some((k.trim(), v.trim())) +} + +struct MsgCase { + len_bits: usize, + msg: Vec, + md: Vec, +} + +/// Parses a ShortMsg/LongMsg `.rsp` file into `(Len, Msg, MD)` triples. +fn parse_msg_file(content: &str) -> Vec { + let mut cases = vec![]; + let (mut len_bits, mut msg) = (None, None); + for line in content.lines() { + let Some((k, v)) = kv(line) else { continue }; + match k { + "Len" => len_bits = Some(v.parse::().expect("bad Len")), + "Msg" => msg = Some(hex::decode(v).expect("bad Msg hex")), + "MD" => cases.push(MsgCase { + len_bits: len_bits.take().expect("MD without Len"), + msg: msg.take().expect("MD without Msg"), + md: hex::decode(v).expect("bad MD hex"), + }), + _ => {} + } + } + cases +} + +/// Hashes the first `len_bits` bits of `msg` (CAVP MSB-first packing, as the API takes it) with `H`. +fn hash_bits(msg: &[u8], len_bits: usize) -> Vec { + let whole_bytes = len_bits / 8; + let partial_bits = len_bits % 8; + if partial_bits == 0 { + // Note: CAVP writes `Msg = 00` for Len = 0, so always slice rather than using msg directly. + H::hash(&msg[..whole_bytes]) + } else { + let mut h = H::default(); + h.do_update(&msg[..whole_bytes]); + // CAVP left-justifies the trailing bits in the last byte, which is the order the API takes. + h.do_final_partial_bits(msg[whole_bytes], partial_bits).expect("partial_bits is in 1..=7") + } +} + +fn run_msg_file(orientation: &str, filename: &str) { + let Some(content) = bc_test_data(&format!("crypto/sha1/{orientation}"), filename) else { + return; + }; + let cases = parse_msg_file(&content); + assert!(!cases.is_empty(), "{orientation}/{filename}: no test cases parsed"); + let mut partial_cases = 0; + for c in &cases { + if c.len_bits % 8 != 0 { + partial_cases += 1; + } + assert_eq!( + hash_bits::(&c.msg, c.len_bits), + c.md, + "{orientation}/{filename}: Len = {}", + c.len_bits + ); + // Whole-byte messages are also fed through the streaming API in uneven chunks. + if c.len_bits % 8 == 0 { + let mut h = H::default(); + for chunk in c.msg[..c.len_bits / 8].chunks(37) { + h.do_update(chunk); + } + assert_eq!( + h.do_final(), + c.md, + "{orientation}/{filename}: Len = {} (streamed)", + c.len_bits + ); + } + } + if orientation == "bit-oriented" { + assert!(partial_cases > 0, "{orientation}/{filename}: expected bit-length cases"); + } + println!("{orientation}/{filename}: {} cases ({partial_cases} bit-length)", cases.len()); +} + +struct MonteFile { + seed: Vec, + mds: Vec>, +} + +/// Parses a Monte `.rsp` file into the seed and the per-COUNT expected digests. +fn parse_monte_file(content: &str) -> MonteFile { + let mut seed = None; + let mut mds = vec![]; + for line in content.lines() { + let Some((k, v)) = kv(line) else { continue }; + match k { + "Seed" => seed = Some(hex::decode(v).expect("bad Seed hex")), + "MD" => mds.push(hex::decode(v).expect("bad MD hex")), + _ => {} + } + } + MonteFile { seed: seed.expect("Monte file without Seed"), mds } +} + +/// SHAVS s. 6.4 Monte Carlo test. +fn run_monte_file(orientation: &str, filename: &str) { + let Some(content) = bc_test_data(&format!("crypto/sha1/{orientation}"), filename) else { + return; + }; + let MonteFile { mut seed, mds } = parse_monte_file(&content); + assert_eq!(mds.len(), 100, "{orientation}/{filename}: expected 100 COUNTs"); + for (count, expected) in mds.iter().enumerate() { + // MD0 = MD1 = MD2 = Seed + let mut md = [seed.clone(), seed.clone(), seed.clone()]; + // for i = 3 to 1002: Mi = MDi-3 || MDi-2 || MDi-1; MDi = SHA(Mi) + for _ in 3..=1002 { + let mut m = Vec::with_capacity(3 * seed.len()); + m.extend_from_slice(&md[0]); + m.extend_from_slice(&md[1]); + m.extend_from_slice(&md[2]); + let next = H::hash(&m); + md.rotate_left(1); + md[2] = next; + } + // MDj = MD1002; Seed = MDj + assert_eq!(&md[2], expected, "{orientation}/{filename}: COUNT = {count}"); + seed = md[2].clone(); + } + println!("{orientation}/{filename}: {} counts", mds.len()); +} + +macro_rules! cavp_tests { + ($mod:ident, $hash:ty, $prefix:literal) => { + mod $mod { + use super::*; + + #[test] + fn bit_oriented_short_msg() { + run_msg_file::<$hash>("bit-oriented", concat!($prefix, "ShortMsg.rsp")); + } + #[test] + fn bit_oriented_long_msg() { + run_msg_file::<$hash>("bit-oriented", concat!($prefix, "LongMsg.rsp")); + } + #[test] + fn bit_oriented_monte() { + run_monte_file::<$hash>("bit-oriented", concat!($prefix, "Monte.rsp")); + } + #[test] + fn byte_oriented_short_msg() { + run_msg_file::<$hash>("byte-oriented", concat!($prefix, "ShortMsg.rsp")); + } + #[test] + fn byte_oriented_long_msg() { + run_msg_file::<$hash>("byte-oriented", concat!($prefix, "LongMsg.rsp")); + } + #[test] + fn byte_oriented_monte() { + run_monte_file::<$hash>("byte-oriented", concat!($prefix, "Monte.rsp")); + } + } + }; +} + +cavp_tests!(sha1, SHA1, "SHA1"); diff --git a/crypto/digest/tests/sha1_sha1_tests.rs b/crypto/digest/tests/sha1_sha1_tests.rs new file mode 100644 index 000000000..59b222781 --- /dev/null +++ b/crypto/digest/tests/sha1_sha1_tests.rs @@ -0,0 +1,262 @@ +//! SHA-1 through the `Hash` trait: the shared conformance suite, known answers that run without +//! bc-test-data, bit-oriented messages and the suspended state. +//! +//! The printed known answers are RFC 3174 Section 7.3's four test results and entries of NIST's +//! CAVP `SHA1ShortMsg.rsp` (byte- and bit-oriented), copied from those files, at the lengths +//! where the padding changes shape. + +use bouncycastle_core::errors::{HashError, SuspendableError}; +use bouncycastle_core::hex; +use bouncycastle_core::security_strength::SecurityStrength; +use bouncycastle_core::traits::{ + Algorithm, AlgorithmInfo, AlgorithmOID, Hash, HashAlgParams, HashOneShot, +}; +use bouncycastle_core_test_framework::hash::TestFrameworkHash; +use bouncycastle_digest::sha1::*; + +fn h(s: &str) -> Vec { + hex::decode(s).unwrap() +} + +/// RFC 3174 Section 7.3: TEST1, TEST2, and TEST4 repeated ten times. +const RFC_3174: [(&str, usize, &str); 3] = [ + ("abc", 1, "a9993e364706816aba3e25717850c26c9cd0d89d"), + ( + "abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq", + 1, + "84983e441c3bd26ebaae4aa1f95129e5e54670f1", + ), + ( + "0123456701234567012345670123456701234567012345670123456701234567", + 10, + "dea356a2cddd90c7a7ecedc5ebb563934f460452", + ), +]; + +/// CAVP byte-oriented `SHA1ShortMsg.rsp`: the empty message and messages of 55, 56, 63 and 64 +/// bytes, around the points where the length field does and does not fit the last block. +const CAVP_BYTES: [(&str, &str); 5] = [ + ("", "da39a3ee5e6b4b0d3255bfef95601890afd80709"), + ( + "ec6b4a88713df27c0f2d02e738b69db43abda3921317259c864c1c386e9a5a3f533dc05f3beeb2bec2aac8e06db4c6cb3cddcf697e03d5", + "a7272e2308622ff7a339460adc61efd0ea8dabdc", + ), + ( + "0321736beba578e90abc1a90aa56157d871618f6de0d764cc8c91e06c68ecd3b9de3824064503384db67beb7fe012232dacaef93a000fba7", + "aef843b86916c16f66c84d83a6005d23fd005c9e", + ), + ( + "f2c76ef617fa2bfc8a4d6bcbb15fe88436fdc2165d3074629579079d4d5b86f5081ab177b4c3f530376c9c924cbd421a8daf8830d0940c4fb7589865830699", + "9f3ea255f6af95c5454e55d7354cabb45352ea0b", + ), + ( + "45927e32ddf801caf35e18e7b5078b7f5435278212ec6bb99df884f49b327c6486feae46ba187dc1cc9145121e1492e6b06e9007394dc33b7748f86ac3207cfe", + "a70cfbfe7563dd0e665c7c6715a96a8d756950c0", + ), +]; + +/// CAVP bit-oriented `SHA1ShortMsg.rsp`: `(Len in bits, Msg, MD)`, the trailing bits +/// left-justified in the last byte of `Msg`. +const CAVP_BITS: [(usize, &str, &str); 6] = [ + (1, "00", "bb6b3e18f0115b57925241676f5b1ae88747b08a"), + (5, "48", "3320540d1c28b96ddd03eee1b186a8f2ae883fbe"), + (13, "de08", "5eb340c7214e400f8cd5782e9afb62c6f9afab57"), + ( + 447, + "de11fa659cc16ad64de598bf7403be07b14d1b7de62f3b0f98247a3c98cdc4cce2449ebec5ae6a82440fe668bd63f759c8eaa5c562c366dc", + "14c764e1369c26aa6a92e75384ea6394986d706b", + ), + ( + 449, + "e41de51ef465e8c8209f3a16aed159db3303bc07f145c2cb62f4e9fe153a40c0b9d41f5d7818157486362258f9be26b6db629a787dfe7eea00", + "5b9800a8c20f91575446c707f78ea09d35d708ac", + ), + ( + 511, + "99afae9df7a6cf61760a455cb11433b58445e21d29fc0804a1484b0d56fb01c0fe003a80c2ee00bca0dcdd690e789eafe05357e26b7fa7b5eb5c3daa22af9bcc", + "cc58d7a6dd5b77d61d069bf3ecd0c9a7ae01098d", + ), +]; + +/// Runs the shared Hash-trait conformance suite against the known answers. +#[test] +fn core_test_framework_hash() { + let test_framework = TestFrameworkHash::new(); + for (msg, repeat, md) in RFC_3174 { + test_framework.test_hash::(msg.repeat(repeat).as_bytes(), &h(md)); + } + for (msg, md) in CAVP_BYTES { + test_framework.test_hash::(&h(msg), &h(md)); + } +} + +/// RFC 3174 Section 7.3's TEST3: one million repetitions of "a", streamed. +#[test] +fn rfc_3174_one_million_a() { + let mut sha1 = SHA1::new(); + for _ in 0..1000 { + sha1.do_update(&[b'a'; 1000]); + } + assert_eq!(sha1.do_final(), h("34aa973cd4c4daa4f61eeb2bdbad27316534016f")); +} + +/// The known answers again a byte at a time, which exercises every buffer offset. +#[test] +fn streaming_a_byte_at_a_time() { + for (msg, md) in CAVP_BYTES { + let mut sha1 = SHA1::new(); + for b in h(msg) { + sha1.do_update(core::slice::from_ref(&b)); + } + assert_eq!(sha1.do_final(), h(md), "len={}", msg.len() / 2); + } +} + +/// A short output buffer truncates the digest and a long one is zero-filled past it. +#[test] +fn output_buffer_lengths() { + let md = h(RFC_3174[0].2); + for len in [0usize, 1, 3, 4, 5, 19, 20, 21, 32] { + let mut out = vec![0xFFu8; len]; + let mut sha1 = SHA1::new(); + sha1.do_update(b"abc"); + let n = sha1.do_final_out(&mut out); + assert_eq!(n, len.min(20), "len={len}"); + assert_eq!(&out[..n], &md[..n], "len={len}"); + assert!(out[n..].iter().all(|b| *b == 0), "len={len}"); + } +} + +#[test] +fn test_constants() { + assert_eq!(SHA1::OUTPUT_LEN, 20); + assert_eq!(SHA1::BLOCK_LEN, 64); + assert_eq!(SHA1::new().block_bitlen(), 512); + assert_eq!(SHA1::new().output_len(), 20); + // The crate docs' Memory Usage table. + assert_eq!(core::mem::size_of::(), 104); +} + +#[test] +fn test_algorithm() { + assert_eq!(SHA1::ALG_NAME, SHA1_NAME); + assert_eq!(SHA1_NAME, "SHA1"); + assert_eq!(SHA1::OID, &[1, 3, 14, 3, 2, 26]); + assert_eq!(SHA1::OID_DER, &[0x06, 0x05, 0x2B, 0x0E, 0x03, 0x02, 0x1A]); +} + +/// SHA-1 is credited with no security strength. +#[test] +fn test_security_strength() { + assert_eq!(SHA1::MAX_SECURITY_STRENGTH, SecurityStrength::None); + assert_eq!(SHA1::default().max_security_strength(), SecurityStrength::None); +} + +/// FIPS 180-4 s. 5.1: bit-oriented messages. Zero partial bits is the byte-oriented digest, more +/// than 7 is rejected, and only the top bits of the partial byte matter. +#[test] +fn partial_bits() { + let mut a = SHA1::new(); + a.do_update(b"abc"); + assert_eq!(a.do_final_partial_bits(0xFF, 0).unwrap(), SHA1::hash(b"abc")); + + for bad in [8usize, 9, 16, 64, usize::MAX] { + let mut sha1 = SHA1::new(); + sha1.do_update(b"abc"); + assert!( + matches!(sha1.do_final_partial_bits(0xFF, bad), Err(HashError::InvalidLength(_))), + "n={bad}" + ); + let mut out = [0u8; 20]; + assert!(matches!( + SHA1::new().do_final_partial_bits_out(0xFF, bad, &mut out), + Err(HashError::InvalidLength(_)) + )); + } + + for n in 1..=7usize { + let mask = (0xFF00u16 >> n) as u8; + let x = SHA1::new().do_final_partial_bits(0xA5, n).unwrap(); + let y = SHA1::new().do_final_partial_bits(0xA5 & mask, n).unwrap(); + let z = SHA1::new().do_final_partial_bits(0xA5 ^ 0x80, n).unwrap(); + assert_eq!(x, y, "n={n}"); + assert_ne!(x, z, "n={n}: the leading bit must change the digest"); + assert_ne!(x, SHA1::hash(&[]), "n={n}"); + assert_ne!(x, SHA1::hash(&[0xA5 & mask]), "n={n}"); + } +} + +/// Bit-oriented known answers from CAVP, including the lengths either side of the 448-bit point +/// where the padding takes a second block. +#[test] +fn partial_bits_known_answers() { + for (len_bits, msg, md) in CAVP_BITS { + let msg = h(msg); + let (whole, partial) = (len_bits / 8, len_bits % 8); + let mut sha1 = SHA1::new(); + sha1.do_update(&msg[..whole]); + assert_eq!(sha1.do_final_partial_bits(msg[whole], partial).unwrap(), h(md), "{len_bits}"); + // The out form reports the digest's length. + let mut sha1 = SHA1::new(); + sha1.do_update(&msg[..whole]); + let mut out = [0u8; 20]; + assert_eq!(sha1.do_final_partial_bits_out(msg[whole], partial, &mut out), Ok(20)); + assert_eq!(out.as_slice(), h(md), "{len_bits}"); + } +} + +#[test] +fn suspendable_state() { + use bouncycastle_core::traits::Suspendable; + use bouncycastle_core_test_framework::suspendable_state::TestFrameworkSuspendableState; + + let str = "Colorless green ideas sleep furiously"; + + let mut sha1 = SHA1::new(); + sha1.do_update(str.as_bytes()); + + // do the default tests + let test_framework = TestFrameworkSuspendableState::new(); + test_framework.test(&sha1); + + // serialize the in-progress state + let serialized_state = sha1.clone().suspend(); + assert_eq!(serialized_state.len(), SUSPENDED_SHA1_STATE_LEN); + assert_eq!(SUSPENDED_SHA1_STATE_LEN, 96); + + // finish the hash, then load from the state and finish again + let output = sha1.do_final(); + let output2 = SHA1::from_suspended(serialized_state).unwrap().do_final(); + assert_eq!(output, output2); + + // A state suspended across a block boundary resumes to the same digest as the unbroken hash. + let msg = [0x5Au8; 150]; + let mut first = SHA1::new(); + first.do_update(&msg[..100]); + let mut resumed = SHA1::from_suspended(first.suspend()).unwrap(); + resumed.do_update(&msg[100..]); + assert_eq!(resumed.do_final(), SHA1::hash(&msg)); + + // an x_buf_off past the block + let mut busted_state = serialized_state; + busted_state[3 + 92] = 65; + assert!(matches!(SHA1::from_suspended(busted_state), Err(SuspendableError::InvalidData))); + busted_state[3 + 92] = 64; + assert!(matches!(SHA1::from_suspended(busted_state), Err(SuspendableError::InvalidData))); + + // byte_count must agree with x_buf_off modulo the block length, and stay within the longest + // message the 64-bit length field can encode, 2^61 - 1 bytes. + let with_counts = |byte_count: u64, x_buf_off: u8| { + let mut state = serialized_state; + state[3 + 20..3 + 28].copy_from_slice(&byte_count.to_le_bytes()); + state[3 + 92] = x_buf_off; + SHA1::from_suspended(state) + }; + let off = serialized_state[3 + 92]; + assert!(with_counts(str.len() as u64 + 64, off).is_ok()); + assert!(matches!(with_counts(str.len() as u64 + 1, off), Err(SuspendableError::InvalidData))); + let max: u64 = (1 << 61) - 1; + assert!(with_counts(max, 63).is_ok()); + assert!(matches!(with_counts(max + 1, 0), Err(SuspendableError::InvalidData))); + assert!(matches!(with_counts(u64::MAX, 63), Err(SuspendableError::InvalidData))); +} diff --git a/crypto/ec/src/barrett.rs b/crypto/ec/src/barrett.rs index 1b905cda5..23c55d784 100644 --- a/crypto/ec/src/barrett.rs +++ b/crypto/ec/src/barrett.rs @@ -62,8 +62,12 @@ pub fn limbs_from_be_bytes_into(bytes: &[u8], out: &mut [u64; L /// `t mod m` for a `2L`-limb `t < m * 2^(64L)` and an `L`-limb modulus `2^(64L-1) < m < 2^(64L)`, /// given `mu_low = floor(2^(128L) / m) - 2^(64L)`. `L2` must be `2L` and `L1` must be `L + 1` -/// (the width `r < 4m` needs before its final subtractions); both are debug-asserted, as are the -/// preconditions on `t` and `m`. Branch-free in `t`. +/// (the width `r < 4m` needs before its final subtractions); both are checked when the function +/// is instantiated, and the preconditions on `t` and `m` are debug-asserted. Branch-free in `t`. +/// +/// ```compile_fail,E0080 +/// let _ = bouncycastle_ec::barrett::reduce::<2, 4, 4>(&[0; 4], &[1, 1 << 63], &[0; 2]); +/// ``` pub fn reduce( t: &[u64; L2], m: &[u64; L], @@ -83,8 +87,10 @@ pub fn reduce_into( mu_low: &[u64; L], out: &mut [u64; L], ) { - debug_assert_eq!(L2, 2 * L, "reduce's L2 must be exactly 2 * L"); - debug_assert_eq!(L1, L + 1, "reduce's L1 must be exactly L + 1"); + const { + assert!(L2 == 2 * L, "reduce's L2 must be exactly 2 * L"); + assert!(L1 == L + 1, "reduce's L1 must be exactly L + 1"); + } debug_assert!(m[L - 1] >> 63 == 1, "reduce needs a modulus with its top bit set"); // t_hi = floor(t / 2^k), the top L limbs; the precondition t < m * 2^k is t_hi < m. diff --git a/crypto/ec/src/montgomery.rs b/crypto/ec/src/montgomery.rs index e882ddeb4..c80ab8736 100644 --- a/crypto/ec/src/montgomery.rs +++ b/crypto/ec/src/montgomery.rs @@ -46,6 +46,16 @@ //! from the Python prototype used to check it. /// Schoolbook widening multiply of two `L`-limb operands into their `L2 = 2L`-limb product. +/// `L2` is checked when the function is instantiated: +/// +/// ```compile_fail,E0080 +/// let _ = bouncycastle_ec::montgomery::widening_mul::<2, 3>(&[1, 2], &[3, 4]); +/// ``` +/// +/// ``` +/// let product = bouncycastle_ec::montgomery::widening_mul::<2, 4>(&[1, 2], &[3, 4]); +/// assert_eq!(product, [3, 10, 8, 0]); +/// ``` // `inline(always)` on both entry points: with the modulus arriving as a runtime `&[u64; L]` // rather than a per-curve constant, inlining is what lets each call site's own `P_LIMBS`/ // `N_LIMBS` reach the multiply. Worth a consistent ~2% and measured, not assumed -- the two @@ -66,7 +76,7 @@ pub fn widening_mul_into( b: &[u64; L], result: &mut [u64; L2], ) { - debug_assert_eq!(L2, 2 * L, "widening_mul's L2 must be exactly 2 * L"); + const { assert!(L2 == 2 * L, "widening_mul's L2 must be exactly 2 * L") }; result.fill(0); for i in 0..L { let mut carry: u128 = 0; @@ -112,9 +122,15 @@ pub fn widening_mul_into( /// /// Verified against Python's arbitrary-precision `**2` over 20,000 random values at each of `L = /// 4, 6, 8, 9` plus the all-ones worst case, before being written here. +/// +/// `L2` is checked when the function is instantiated: +/// +/// ```compile_fail,E0080 +/// let _ = bouncycastle_ec::montgomery::widening_square::<2, 5>(&[1, 2]); +/// ``` #[inline(always)] pub fn widening_square(a: &[u64; L]) -> [u64; L2] { - debug_assert_eq!(L2, 2 * L, "widening_square's L2 must be exactly 2 * L"); + const { assert!(L2 == 2 * L, "widening_square's L2 must be exactly 2 * L") }; let mut result = [0u64; L2]; // Off-diagonal products, each formed once. @@ -160,14 +176,22 @@ pub fn widening_square(a: &[u64; L]) -> [u64; L /// 2^64`, returns `T * R⁻¹`, `< 2n` (proven, see the module docs) -- callers still need their own /// final conditional subtraction of `n` to reach the canonical `< n` representative, exactly as /// every hand-written per-curve `redc` in this crate already does. +/// +/// `L2` is `2L` and `L21` is `2L + 1`, checked when the function is instantiated: +/// +/// ```compile_fail,E0080 +/// let _ = bouncycastle_ec::montgomery::redc::<2, 4, 4>(&[0; 4], &[7, 0], 0x6db6db6db6db6db7); +/// ``` #[inline(always)] pub fn redc( t: &[u64; L2], modulus: &[u64; L], n_prime: u64, ) -> ([u64; L], u64) { - debug_assert_eq!(L2, 2 * L, "redc's L2 must be exactly 2 * L"); - debug_assert_eq!(L21, 2 * L + 1, "redc's L21 must be exactly 2 * L + 1"); + const { + assert!(L2 == 2 * L, "redc's L2 must be exactly 2 * L"); + assert!(L21 == 2 * L + 1, "redc's L21 must be exactly 2 * L + 1"); + } // The accumulator is `2L + 1` limbs (see the module docs for the bound) and is held flat, in // one array. Keeping the top limb in a separate `u64` instead -- which is what this did before // `L21` existed -- reintroduces exactly the split the module docs describe: measured, it cost diff --git a/crypto/rsa/Cargo.toml b/crypto/rsa/Cargo.toml new file mode 100644 index 000000000..c1fddc56d --- /dev/null +++ b/crypto/rsa/Cargo.toml @@ -0,0 +1,49 @@ +[package] +name = "bouncycastle-rsa" +version.workspace = true +edition.workspace = true + +[dependencies] +bouncycastle-core.workspace = true +bouncycastle-ec.workspace = true +bouncycastle-hkdf.workspace = true +bouncycastle-hmac.workspace = true +bouncycastle-digest.workspace = true +bouncycastle-sha2.workspace = true +bouncycastle-sha3.workspace = true +bouncycastle-utils.workspace = true + +# `bouncycastle_rsa_ct_harness` is set by dev_scripts/check_rsa_ct.sh alone; see `ct_harness` +# in src/lib.rs. +[lints.rust] +unexpected_cfgs = { level = "warn", check-cfg = ['cfg(bouncycastle_rsa_ct_harness)'] } + +[dev-dependencies] +bouncycastle-core-test-framework.workspace = true +bouncycastle-rng.workspace = true +criterion.workspace = true +serde_json = "1.0" + +[[bench]] +name = "rsa_1024_benches" +harness = false + +[[bench]] +name = "rsa_1536_benches" +harness = false + +[[bench]] +name = "rsa_2048_benches" +harness = false + +[[bench]] +name = "rsa_3072_benches" +harness = false + +[[bench]] +name = "rsa_4096_benches" +harness = false + +[[bench]] +name = "rsa_8192_benches" +harness = false diff --git a/crypto/rsa/benches/rsa_1024_benches.rs b/crypto/rsa/benches/rsa_1024_benches.rs new file mode 100644 index 000000000..2df2084ee --- /dev/null +++ b/crypto/rsa/benches/rsa_1024_benches.rs @@ -0,0 +1,67 @@ +//! Criterion benches for RSA-1024: verification only (see `bouncycastle_rsa::rsa_1024`'s docs -- +//! this crate has no RSA-1024 private key type at all). The public key and signature are Wycheproof +//! `rsa_pkcs1_1024_sig_gen_test.json`'s own genuine `(n, e)` and one real `(msg, sig)` pair, the +//! same provenance `tests/rsa_1024_tests.rs` uses. + +use bouncycastle_core::signature_key::OneShotVerifyingKey; +use criterion::{Criterion, criterion_group, criterion_main}; +use std::hint::black_box; + +use bouncycastle_core::hex::decode as hex_decode; +use bouncycastle_rsa::RSA1024; +use bouncycastle_rsa::keys::RsaPublicComponents; +use bouncycastle_rsa::rsa_1024::{RSASSA_PKCS1_v1_5_SHA256, RSASSA_PKCS1_v1_5_SHA384}; + +fn bench_rsa_1024(c: &mut Criterion) { + let n_sha256: [u64; 16] = [ + 0xd00343468eaacfbf, 0xb7c7044cc202dcca, 0x9686f30f478db649, 0x5179b54951fff6aa, + 0xbabb14f550d5d0dd, 0x5405db7c5c8f4cf6, 0x9816e2eda41fd7b9, 0xb31b6abd805bace9, + 0xb909dd0f4c6014f2, 0x9c8a5810b6d05990, 0x40760d1f23fe9250, 0x90adb011a919575a, + 0x45e48572113cab28, 0xcb9ca9ec12000fc8, 0x91b4fcaf62a14595, 0xac9048a7a4f560af, + ]; + let pk_sha256 = RsaPublicComponents::::new(&n_sha256, 0x10001).unwrap(); + let msg_sha256 = hex_decode("0000000000000000000000000000000000000000").unwrap(); + let sig_sha256: [u8; 128] = hex_decode( + "41339884a9b3940e8488d666bb158063c6a2a2717cae7f564834a876fcbf7098ecf3acbfabf37d38a8e6127b1e313744f1f896e165efdaea0b2e7673867842b9e94db0868ed9a92bcdcb370a4e20ff275c82595e4400a8b9e9f12482f014846b48216f321266ae6ae6338dbcdc41b711e483e6e3e728772e7f9f5ef95c30196b", + ) + .unwrap() + .try_into() + .unwrap(); + + let n_sha384: [u64; 16] = [ + 0x5cfd178f3f07ed01, 0x7c94e28878397cb4, 0x57dbd3d6d0f5b77f, 0x89f8ec36d7f5cae7, + 0x73d399b04ad55c0a, 0x33b063490cf7b670, 0x51996b97d5b25da9, 0x0af3f4b5efec3586, + 0xe60ee26a7b7cfccb, 0xaf86df2283c8e327, 0x7dea6692a1713516, 0xe94e94385dffc5e2, + 0x8cf0173a0a309a1e, 0x3ea5161e5450d16a, 0xba51135f78844d9a, 0xa1d3912e65d994e0, + ]; + let pk_sha384 = RsaPublicComponents::::new(&n_sha384, 0x10001).unwrap(); + let msg_sha384 = hex_decode("0000000000000000000000000000000000000000").unwrap(); + let sig_sha384: [u8; 128] = hex_decode( + "74b9a7b9548a281c5a258520c879e0e64d8a28812a7b6461c6e418e0502b61008a8e535a5b55fb64529a6a6df2f60ef33c1844b27f81532be2bc2992d0eb5e524112da90bf40adefcf206469639ff3895a9826674ee1acbdd623842ab0a9a36d48da13ba17c4ee069254da2ea418d5a8f135e2a414c0654a266d538621917545", + ) + .unwrap() + .try_into() + .unwrap(); + + let mut group = c.benchmark_group("rsa_1024"); + group.bench_function("pkcs1v15_verify_sha256", |b| { + b.iter(|| { + pk_sha256 + .key::() + .verify(black_box(&msg_sha256), None, black_box(&sig_sha256)) + .unwrap() + }) + }); + group.bench_function("pkcs1v15_verify_sha384", |b| { + b.iter(|| { + pk_sha384 + .key::() + .verify(black_box(&msg_sha384), None, black_box(&sig_sha384)) + .unwrap() + }) + }); + group.finish(); +} + +criterion_group!(benches, bench_rsa_1024); +criterion_main!(benches); diff --git a/crypto/rsa/benches/rsa_1536_benches.rs b/crypto/rsa/benches/rsa_1536_benches.rs new file mode 100644 index 000000000..87aef5f21 --- /dev/null +++ b/crypto/rsa/benches/rsa_1536_benches.rs @@ -0,0 +1,96 @@ +//! Criterion benches for RSA-1536: verification only (see `bouncycastle_rsa::rsa_1536`'s docs -- +//! this crate has no RSA-1536 private key type at all). Public keys and signatures are Wycheproof +//! `rsa_pkcs1_1536_sig_gen_test.json`'s own genuine `(n, e)` and real `(msg, sig)` pairs, the same +//! provenance `tests/rsa_1536_tests.rs` uses. + +use bouncycastle_core::signature_key::OneShotVerifyingKey; +use criterion::{Criterion, criterion_group, criterion_main}; +use std::hint::black_box; + +use bouncycastle_core::hex::decode as hex_decode; +use bouncycastle_rsa::RSA1536; +use bouncycastle_rsa::keys::RsaPublicComponents; +use bouncycastle_rsa::rsa_1536::{ + RSASSA_PKCS1_v1_5_SHA256, RSASSA_PKCS1_v1_5_SHA384, RSASSA_PKCS1_v1_5_SHA512, +}; + +fn bench_rsa_1536(c: &mut Criterion) { + let n_sha256: [u64; 24] = [ + 0xe58590d069a2a271, 0xb2909211b75f8182, 0x052fd6f0a20f6cde, 0x06d4eb560a8fddff, + 0x703a83c6cbfd949d, 0x553f827a27719c2c, 0x395bdb0865f22ac0, 0x12bdb15dde506945, + 0x16db14f2e1c9b8d3, 0x51702cfaa46fcaf7, 0xe62269e04112c194, 0x7728dcea18bc1193, + 0xab906e57364cac81, 0x852f673d3288544a, 0x9547f55a3d7b1d08, 0x8e6d3a99c058b1c8, + 0x5e2c811a56b5d946, 0x6c9fc8200b205487, 0x7b401487a9c85917, 0x41744b5872ccebc8, + 0x86eb04d51f21ac52, 0xe029a743f0649ae5, 0x6cf4930cf2615140, 0xeb477c90d46bd189, + ]; + let pk_sha256 = RsaPublicComponents::::new(&n_sha256, 0x10001).unwrap(); + let msg = hex_decode("0000000000000000000000000000000000000000").unwrap(); + let sig_sha256: [u8; 192] = hex_decode( + "8d2611d4c79f6b2087ae8bc76610905c361b9fe0a6629388197b4293f9e14ecbeb377206e4c1db35cdc0ab163dc5c51e8a7370a059e9ee8014d18ef0937f7936879d7825c792180a4f10a0d46e0a954f093d703b82bd076dcec0b8a66fc3be9bdf79ce4550c453015dc1c7397ec1bfceed040a4d777915546b9cbcf1eeb13eb71ac49c235e69cb07c315d529442f4863d61b7d5caa5ce07820edf649a9342211a26f8280dab9c5dd11af0752168326f8e8d5e834ddba3bce063f011eccc8f46d", + ) + .unwrap() + .try_into() + .unwrap(); + + let n_sha384: [u64; 24] = [ + 0x0c8a0645adb04d7f, 0x4913d26ff2dd0383, 0xe5567ac4c3edf882, 0x965f5b7b146663f4, + 0x6802e12716431e25, 0x8d39e0d5c93fe29a, 0xb940509dbf238383, 0x84fb9ca6ac2ffd03, + 0x67b11769af1178d2, 0x98fa3b27d4de0a32, 0xec385a5db04f4731, 0x065c58db8b8166aa, + 0x2ed95a2a8cfd33da, 0x821cb5e40dc781e7, 0x3cb9b09f241b0700, 0x30b30fe5ea0d2408, + 0xd7841125d38dd9f4, 0xb0ed9964c7b125da, 0x06d573f19163ae2a, 0xa7716c797d15afe5, + 0xcf19e47fadf98cfd, 0xdc9306f2f3646bbc, 0x9c3c1865cf6beaf5, 0xd1060fe7c6d185f0, + ]; + let pk_sha384 = RsaPublicComponents::::new(&n_sha384, 0x10001).unwrap(); + let sig_sha384: [u8; 192] = hex_decode( + "58c4c42da5eee1b757b31e3362a95d75180c0fee472c431527ff5500fe0b5c1d59968d79e6e41650f013a6b3e37c5a1d79233b818ef76c4ed469a09607becdc58987e6a548610de14ff06899ef284778dd5329a27b85072e8ffd46b63a5e8f7602ddb9fc5a07224c49818fc8057581ea36da033f2b936f0761186c7fd82b474e87d47aa1b7ec610642d3bcb16c59bb70ac68b1f081a9c9248f069474d6ed9b29c669fc40a979cdfc2053e1a3c0cf40efa29c01785323995f1d8f3850c32bdf92", + ) + .unwrap() + .try_into() + .unwrap(); + + let n_sha512: [u64; 24] = [ + 0xb4095eb4bf90b6e9, 0x4b57f8d656600e5f, 0x176e311fe8dbcac2, 0x115b2ec41eb9acc4, + 0xdb3ecfc281f8da29, 0xc93bc5bf6c2504fb, 0x0e7896e87fb399e6, 0x69ae5f32937a207e, + 0x230ddd8c067dae90, 0xed1e42ebfbe70645, 0xa16f8e2300ef7c35, 0x70b29f55dd21d2cb, + 0x7e3413f9891e2f8a, 0xa7e0de9008f3a9a6, 0x4df9f5c38e950175, 0xc8e722c8dedc065a, + 0xfe887a4a1fae6ca8, 0xa96a2bedc3e72738, 0xe2ad09578c749863, 0xffb63f097ed7b5c5, + 0xcea5ba02d99f0807, 0x1cb9a9b7b769d6df, 0xfd4c711aef054e29, 0xd1f33c4d0c3b127c, + ]; + let pk_sha512 = RsaPublicComponents::::new(&n_sha512, 0x10001).unwrap(); + let sig_sha512: [u8; 192] = hex_decode( + "5259fe9566e1bd81952a805384b1657374f33550ee0895b57b7a0869a831270d3b3b2db8e295a4eb98d8eb036183b3d228ad22b8e493c7eb0f9ab00eeab2e086f10f8018a8daaff4858ae745a4d70881a166963c64403216422e18974aa456d8229ef2e43002e0390166630c7fabd14efaa974a9521a72a69e0b446971db077ce80f6dd95cf797b6ed276873bbf6b1ba6a79df8c917c2a3fbbc0e5347b0bb99eec6ad0b6bdb7bc9d3e0a7f6b7b623f2aa9dba1e940676ec5629d39778286f261", + ) + .unwrap() + .try_into() + .unwrap(); + + let mut group = c.benchmark_group("rsa_1536"); + group.bench_function("pkcs1v15_verify_sha256", |b| { + b.iter(|| { + pk_sha256 + .key::() + .verify(black_box(&msg), None, black_box(&sig_sha256)) + .unwrap() + }) + }); + group.bench_function("pkcs1v15_verify_sha384", |b| { + b.iter(|| { + pk_sha384 + .key::() + .verify(black_box(&msg), None, black_box(&sig_sha384)) + .unwrap() + }) + }); + group.bench_function("pkcs1v15_verify_sha512", |b| { + b.iter(|| { + pk_sha512 + .key::() + .verify(black_box(&msg), None, black_box(&sig_sha512)) + .unwrap() + }) + }); + group.finish(); +} + +criterion_group!(benches, bench_rsa_1536); +criterion_main!(benches); diff --git a/crypto/rsa/benches/rsa_2048_benches.rs b/crypto/rsa/benches/rsa_2048_benches.rs new file mode 100644 index 000000000..f947cedf1 --- /dev/null +++ b/crypto/rsa/benches/rsa_2048_benches.rs @@ -0,0 +1,229 @@ +//! Criterion benches for RSA-2048: one `bench_function` per (scheme, hash) pairing this size +//! wires up, since each has a different performance profile (SHA-256/384/512 hash different +//! amounts of data per block; PSS additionally draws a fresh salt and runs MGF1/SHAKE). The +//! genuine key is the same one `tests/rsa_2048_pkcs1_v1_5_tests.rs` recovers from Wycheproof's +//! `rsa_pkcs1_2048_sig_gen_test.json` (see that file for the full, sourced provenance). + +use bouncycastle_core::kem_key::{DecapsulatingKey, EncapsulatingKey}; +use bouncycastle_core::signature_key::{ + DeterministicOneShotSigningKey, OneShotSigningKey, OneShotVerifyingKey, +}; +use bouncycastle_core::traits::{PrivateKey, PublicKey}; +use bouncycastle_rsa::RSA2048; +use bouncycastle_rsa::rsa_2048::{RSA2048KEMPrivateKey, RSA2048KEMPublicKey}; +use bouncycastle_rsa::rsaes_oaep::OaepParams; +use bouncycastle_rsa::size::RsaSigningSize; +use bouncycastle_sha2::SHA256; +use criterion::{Criterion, criterion_group, criterion_main}; +use std::hint::black_box; + +use bouncycastle_rng::DefaultRNG; +use bouncycastle_rsa::keys::{RsaPrivateComponents, RsaPublicComponents}; +use bouncycastle_rsa::rsa_2048::{ + RSASSA_PKCS1_v1_5_SHA256, RSASSA_PKCS1_v1_5_SHA384, RSASSA_PKCS1_v1_5_SHA512, + RSASSA_PSS_SHA256, RSASSA_PSS_SHA384, RSASSA_PSS_SHA512, RSASSA_PSS_SHAKE128, +}; + +const MSG: &[u8] = b"a representative message for benchmarking RSA-2048"; + +fn genuine_key() -> RsaPrivateComponents { + let p: [u64; 16] = [ + 0x0ea36cfb3a5b18f1, 0x48a6e65332119129, 0x110ad9e7b48a1c93, 0x569156b90113e2e9, + 0xe79813a575cfad9c, 0x69d659d143ec6f17, 0xe81e6bab5ddaa783, 0xbff1c5b80a69f788, + 0x978f6c35814f50ee, 0xe6a289ad4cfbf78f, 0x34d5681e5809d415, 0xbb028bda42eeb5d2, + 0x41c56e4de086b0d5, 0x58b8d1e24f3b55d0, 0xfb5248247d98cb7d, 0xdc431050f782e894, + ]; + let q: [u64; 16] = [ + 0x669f140cfbc20f25, 0xb97bb03677207d95, 0xfd4e06f3ed7299d4, 0x160f90536abc9492, + 0xf5b131f39098f7bc, 0xae8d72c57088d7ab, 0x89b94fbde542aba9, 0x3d3f9880ec47d5e0, + 0x1378a6868af3b7a0, 0x5544070beb057c94, 0x16611debc472fac4, 0xe500ffb79f5b8868, + 0x308a5e32196603b2, 0xea5fb19eb4eabc38, 0x122273ae3222b598, 0xbd1a81e7977f9898, + ]; + let d_p: [u64; 16] = [ + 0x209f33f09515d7c1, 0xb4a9b37656917205, 0x276933bb07e4efb9, 0x8c14019808e00414, + 0x289f96da220711e5, 0xfbbd2923d31532fe, 0xc06b414e61c0e1e7, 0x4c23c4588488961d, + 0x4dc48ae34514759c, 0x9c786961ae3e2c35, 0x497e8d9c650688e0, 0x18bf08472612dbe5, + 0x8885fb161870ee12, 0xf21d7c1479d99d47, 0x9121d91952ffd1c7, 0xa94b528b28f29159, + ]; + let d_q: [u64; 16] = [ + 0xf7597ffb68011d8d, 0x7b3cc538c4bab8c9, 0xa8fa480a81a925af, 0x6d6ede7251a383bf, + 0x8a63f788ce3a0f85, 0x0b920502eb478bc9, 0x7e37e755edfe70d9, 0x9cf9948422a16555, + 0x0d6d9ea1f2ef71fd, 0xf7efa32ea0cb6e00, 0x0629b114ca7f780f, 0xcf51176359654348, + 0x540cdcbd4ad35435, 0x31c02ff1a2bc437c, 0xff2503df78bafed5, 0x3af0e72a933aef09, + ]; + let q_inv: [u64; 16] = [ + 0x552fe4bfce945f7b, 0x67e50c999c67247b, 0xfb54ef17be3b2853, 0x241f5921b5ad3983, + 0x02de5eccd143cf31, 0x74e45f6fcc60f216, 0xafa5428a74f12708, 0x88d42294b6a2759b, + 0xe923e1097c0c562f, 0xc968b48a91c38b5b, 0x933e85179c0320b0, 0x7993d0445f758d51, + 0x9bfc042ee0924b1b, 0x41f956d90fa8a793, 0xee7a87b6483a66ee, 0x2640fbfbcfefb163, + ]; + RsaPrivateComponents::::from_crt_components(&p, &q, &d_p, &d_q, &q_inv, 0x10001) + .expect("genuine RSA-2048 CRT components must be accepted") +} + +fn bench_rsa_2048(c: &mut Criterion) { + let sk = genuine_key(); + let pk = RsaPublicComponents::::new(sk.n(), 0x10001).unwrap(); + let mut rng = DefaultRNG::default(); + + let sig_pkcs1_256 = sk.key::().sign_deterministic(MSG, None).unwrap(); + let sig_pkcs1_384 = sk.key::().sign_deterministic(MSG, None).unwrap(); + let sig_pkcs1_512 = sk.key::().sign_deterministic(MSG, None).unwrap(); + let sig_pss_256 = sk.key::().sign(&mut rng, MSG, None).unwrap(); + let sig_pss_384 = sk.key::().sign(&mut rng, MSG, None).unwrap(); + let sig_pss_512 = sk.key::().sign(&mut rng, MSG, None).unwrap(); + let sig_pss_shake128 = sk.key::().sign(&mut rng, MSG, None).unwrap(); + + let mut group = c.benchmark_group("rsa_2048"); + + group.bench_function("pkcs1v15_sign_sha256", |b| { + b.iter(|| { + black_box( + sk.key::() + .sign_deterministic(black_box(MSG), None) + .unwrap(), + ) + }) + }); + group.bench_function("pkcs1v15_verify_sha256", |b| { + b.iter(|| { + pk.key::() + .verify(black_box(MSG), None, black_box(&sig_pkcs1_256)) + .unwrap() + }) + }); + group.bench_function("pkcs1v15_sign_sha384", |b| { + b.iter(|| { + black_box( + sk.key::() + .sign_deterministic(black_box(MSG), None) + .unwrap(), + ) + }) + }); + group.bench_function("pkcs1v15_verify_sha384", |b| { + b.iter(|| { + pk.key::() + .verify(black_box(MSG), None, black_box(&sig_pkcs1_384)) + .unwrap() + }) + }); + group.bench_function("pkcs1v15_sign_sha512", |b| { + b.iter(|| { + black_box( + sk.key::() + .sign_deterministic(black_box(MSG), None) + .unwrap(), + ) + }) + }); + group.bench_function("pkcs1v15_verify_sha512", |b| { + b.iter(|| { + pk.key::() + .verify(black_box(MSG), None, black_box(&sig_pkcs1_512)) + .unwrap() + }) + }); + group.bench_function("pss_sign_sha256", |b| { + b.iter(|| { + black_box( + sk.key::() + .sign(&mut DefaultRNG::default(), black_box(MSG), None) + .unwrap(), + ) + }) + }); + group.bench_function("pss_verify_sha256", |b| { + b.iter(|| { + pk.key::() + .verify(black_box(MSG), None, black_box(&sig_pss_256)) + .unwrap() + }) + }); + group.bench_function("pss_sign_sha384", |b| { + b.iter(|| { + black_box( + sk.key::() + .sign(&mut DefaultRNG::default(), black_box(MSG), None) + .unwrap(), + ) + }) + }); + group.bench_function("pss_verify_sha384", |b| { + b.iter(|| { + pk.key::() + .verify(black_box(MSG), None, black_box(&sig_pss_384)) + .unwrap() + }) + }); + group.bench_function("pss_sign_sha512", |b| { + b.iter(|| { + black_box( + sk.key::() + .sign(&mut DefaultRNG::default(), black_box(MSG), None) + .unwrap(), + ) + }) + }); + group.bench_function("pss_verify_sha512", |b| { + b.iter(|| { + pk.key::() + .verify(black_box(MSG), None, black_box(&sig_pss_512)) + .unwrap() + }) + }); + group.bench_function("pss_sign_shake128", |b| { + b.iter(|| { + black_box( + sk.key::() + .sign(&mut DefaultRNG::default(), black_box(MSG), None) + .unwrap(), + ) + }) + }); + group.bench_function("pss_verify_shake128", |b| { + b.iter(|| { + pk.key::() + .verify(black_box(MSG), None, black_box(&sig_pss_shake128)) + .unwrap() + }) + }); + + // RSASVE (SP 800-56B Rev. 2 §7.2.1) under the same key material, re-read as KEM key types + // through the shared raw encoding. Encapsulation is one public-exponent modexp plus the RNG + // draw; decapsulation is the same CRT exponentiation signing does. + let kem_sk = RSA2048KEMPrivateKey::from_bytes(&sk.key::().encode()).unwrap(); + let kem_pk = RSA2048KEMPublicKey::from_bytes(&pk.key::().encode()).unwrap(); + let (_, kem_ct) = kem_pk.encaps(&mut rng, ()).unwrap(); + group.bench_function("rsasve_encaps", |b| { + b.iter(|| black_box(black_box(&kem_pk).encaps(&mut rng, ()).unwrap())) + }); + group.bench_function("rsasve_decaps", |b| { + b.iter(|| black_box(black_box(&kem_sk).decaps(black_box(&kem_ct), ()).unwrap())) + }); + + // RSAES-OAEP (RFC 8017 §7.1) on the same KEM keys, with SHA-256: the encoding around the + // same two exponentiations. + let oaep = OaepParams::::new(b""); + let (_, oaep_ct) = kem_pk.encaps(&mut rng, oaep).unwrap(); + group.bench_function("oaep_sha256_encaps", |b| { + b.iter(|| black_box(black_box(&kem_pk).encaps(&mut rng, oaep).unwrap())) + }); + group.bench_function("oaep_sha256_decaps", |b| { + b.iter(|| black_box(black_box(&kem_sk).decaps(black_box(&oaep_ct), oaep).unwrap())) + }); + + group.finish(); + + // FIPS 186-5 A.1.3 key generation: rejection sampling, so the run-to-run spread is large; + // ten samples is enough to see the order of magnitude without a multi-minute bench. + let mut keygen_group = c.benchmark_group("rsa_2048_keygen"); + keygen_group.sample_size(10); + keygen_group.bench_function("keygen", |b| { + b.iter(|| black_box(RSA2048::keygen(&mut DefaultRNG::default()).unwrap())) + }); + keygen_group.finish(); +} + +criterion_group!(benches, bench_rsa_2048); +criterion_main!(benches); diff --git a/crypto/rsa/benches/rsa_3072_benches.rs b/crypto/rsa/benches/rsa_3072_benches.rs new file mode 100644 index 000000000..567539cca --- /dev/null +++ b/crypto/rsa/benches/rsa_3072_benches.rs @@ -0,0 +1,236 @@ +//! Criterion benches for RSA-3072. See `rsa_2048_benches.rs`'s docs for the rationale; the genuine +//! key is the same one `tests/rsa_3072_tests.rs` recovers from Wycheproof's +//! `rsa_pkcs1_3072_sig_gen_test.json`. + +use bouncycastle_core::kem_key::{DecapsulatingKey, EncapsulatingKey}; +use bouncycastle_core::signature_key::{ + DeterministicOneShotSigningKey, OneShotSigningKey, OneShotVerifyingKey, +}; +use bouncycastle_core::traits::{PrivateKey, PublicKey}; +use bouncycastle_rsa::RSA3072; +use bouncycastle_rsa::rsa_3072::{RSA3072KEMPrivateKey, RSA3072KEMPublicKey}; +use bouncycastle_rsa::rsaes_oaep::OaepParams; +use bouncycastle_rsa::size::RsaSigningSize; +use bouncycastle_sha2::SHA256; +use criterion::{Criterion, criterion_group, criterion_main}; +use std::hint::black_box; + +use bouncycastle_rng::DefaultRNG; +use bouncycastle_rsa::keys::{RsaPrivateComponents, RsaPublicComponents}; +use bouncycastle_rsa::rsa_3072::{ + RSASSA_PKCS1_v1_5_SHA256, RSASSA_PKCS1_v1_5_SHA384, RSASSA_PKCS1_v1_5_SHA512, + RSASSA_PSS_SHA256, RSASSA_PSS_SHA384, RSASSA_PSS_SHA512, RSASSA_PSS_SHAKE128, +}; + +const MSG: &[u8] = b"a representative message for benchmarking RSA-3072"; + +fn genuine_key() -> RsaPrivateComponents { + let p: [u64; 24] = [ + 0xb26d973345bc4c5f, 0x23251a1d29962ca9, 0x554fc3f23d6c9046, 0x89ffe73b1401e9b8, + 0xe0b448b454670aca, 0xa73ea5c2413d1da2, 0xe9539bc7a8d3b351, 0x357984fc116af9cb, + 0xa93e40aac908e4e3, 0xae586c1e7f5c52cd, 0x80deaeaab651c7a9, 0xe261a4f7f4505580, + 0xc5a703b2fc28bfcf, 0x14521a6893f3f3c5, 0x0f08d649107f449a, 0xd96ceabb7ee83ce5, + 0x1b2e8a9b2bb69525, 0x383ead851fac07ad, 0x939deb88dff68550, 0xce9fa16a1cc92120, + 0x43604a7f2be2860f, 0xba55f20a964c4e63, 0x0ed9ac8a812545da, 0xf5eca16e0e83696b, + ]; + let q: [u64; 24] = [ + 0x7981610848c55cdd, 0x8bce03c5d339b975, 0xb8227d7b5d76ce8b, 0x6edee1e9d17781db, + 0x1c127ac3c4d0bd59, 0xb8b28f38951d7bee, 0x496086fa1300249a, 0x790e5c34729a8efb, + 0x9bdb81968f4a6d7c, 0x6018fd4ed9a3545f, 0x6ccb168d5b510dbe, 0xe1d845c6553c0a54, + 0x73ec1d97f669e298, 0x8b898025ef470e43, 0x160deb327e8ace01, 0x640191099b355611, + 0xe0ec501ccc94b2b0, 0x4f98c9ee4fdae41b, 0x0082a3bc42af1a14, 0x510a623c2b47a522, + 0x32057f9da6dbefc4, 0x95ad92b6f295d610, 0x19ddbfcfa2d96704, 0xcf25446f59cf5129, + ]; + let d_p: [u64; 24] = [ + 0xeeb10a8531c470ed, 0xbcd9be04cdc9d65c, 0xb684b458e4ab3854, 0x6a2dafd0d3b23a21, + 0xc812cbd3dccc8b35, 0x3e67363a947405c6, 0xa3ce9c7d391bdbb2, 0xf8bd10156b4bd580, + 0x3c1ce3ae99eb37da, 0xcfa5f4771567cc23, 0x35e0be9a437021c1, 0x8a527b7b967be52e, + 0xc649435b483585d6, 0x1dc154ddadf6bc20, 0x69105ecfc1144838, 0x3dad9bdd05d4f6d4, + 0xf95601b3d122be79, 0x92f1eed27a0ada46, 0x152e93f904cfe6e6, 0x5a6e6d9c19e8bdb3, + 0x6c0437d3cb7c843f, 0x370e84e9f5f0f931, 0x514c6940c20eb67b, 0x6357a59679d26801, + ]; + let d_q: [u64; 24] = [ + 0x1a4dbeba87772d29, 0xe51861bbb4e73e73, 0x9e86b2483e9bf22c, 0xc9ebcf4d7c2d6c9f, + 0xbe8fe9def6b7a62c, 0x4e8805a755ac2904, 0x734f44f3e4e88d18, 0x7626602fc90ae694, + 0xde97c88d40fa1ac4, 0x4eeaf1aafe2e1ba5, 0x25cd66f5205b038b, 0x8fa6bb6ae73b182d, + 0x0c85ab03068cbfee, 0x96f0ae48529b490f, 0xbb4cc906ba283d18, 0x4bf60c135a264919, + 0x4c2cf95ce74fe42c, 0xf4a5e8eed2a70c7a, 0x14ecee22e846a7d3, 0xd2a4139a39cec9df, + 0x4ba0e0801d31cbf5, 0x088a7986f6c2b8c0, 0x8bdc0f566f876191, 0x0004dadabfc15b1a, + ]; + let q_inv: [u64; 24] = [ + 0x45b268741fca195c, 0x94eacf955ae5dacd, 0x3ad1a334fd85aa87, 0xe8b01c83f2aec93e, + 0xd05fdc78929fa0cf, 0x0745ab95edda215b, 0xe5c81a2189f11467, 0xeded3f90e0ba4a97, + 0xfbf69baed9510be5, 0x6bee976c25dbaff8, 0x6ad65e9fe6c28038, 0xef6613dd6bf885c1, + 0x594990da705ebdf7, 0x8ee8b716f19429fb, 0x2662db8c85318de4, 0x22481fc74a7a3d62, + 0xfe6c3600d9b8e9a9, 0x744fac4daabf5488, 0xfbee6ec24b75fbf0, 0x8be552c8be44f139, + 0xfb0da96bd423759d, 0xb3443d93e7e8ca62, 0x36fe01b950885ecd, 0x214a1f73130e48b3, + ]; + RsaPrivateComponents::::from_crt_components(&p, &q, &d_p, &d_q, &q_inv, 0x10001) + .expect("genuine RSA-3072 CRT components must be accepted") +} + +fn bench_rsa_3072(c: &mut Criterion) { + let sk = genuine_key(); + let pk = RsaPublicComponents::::new(sk.n(), 0x10001).unwrap(); + let mut rng = DefaultRNG::default(); + + let sig_pkcs1_256 = sk.key::().sign_deterministic(MSG, None).unwrap(); + let sig_pkcs1_384 = sk.key::().sign_deterministic(MSG, None).unwrap(); + let sig_pkcs1_512 = sk.key::().sign_deterministic(MSG, None).unwrap(); + let sig_pss_256 = sk.key::().sign(&mut rng, MSG, None).unwrap(); + let sig_pss_384 = sk.key::().sign(&mut rng, MSG, None).unwrap(); + let sig_pss_512 = sk.key::().sign(&mut rng, MSG, None).unwrap(); + let sig_pss_shake128 = sk.key::().sign(&mut rng, MSG, None).unwrap(); + + let mut group = c.benchmark_group("rsa_3072"); + + group.bench_function("pkcs1v15_sign_sha256", |b| { + b.iter(|| { + black_box( + sk.key::() + .sign_deterministic(black_box(MSG), None) + .unwrap(), + ) + }) + }); + group.bench_function("pkcs1v15_verify_sha256", |b| { + b.iter(|| { + pk.key::() + .verify(black_box(MSG), None, black_box(&sig_pkcs1_256)) + .unwrap() + }) + }); + group.bench_function("pkcs1v15_sign_sha384", |b| { + b.iter(|| { + black_box( + sk.key::() + .sign_deterministic(black_box(MSG), None) + .unwrap(), + ) + }) + }); + group.bench_function("pkcs1v15_verify_sha384", |b| { + b.iter(|| { + pk.key::() + .verify(black_box(MSG), None, black_box(&sig_pkcs1_384)) + .unwrap() + }) + }); + group.bench_function("pkcs1v15_sign_sha512", |b| { + b.iter(|| { + black_box( + sk.key::() + .sign_deterministic(black_box(MSG), None) + .unwrap(), + ) + }) + }); + group.bench_function("pkcs1v15_verify_sha512", |b| { + b.iter(|| { + pk.key::() + .verify(black_box(MSG), None, black_box(&sig_pkcs1_512)) + .unwrap() + }) + }); + group.bench_function("pss_sign_sha256", |b| { + b.iter(|| { + black_box( + sk.key::() + .sign(&mut DefaultRNG::default(), black_box(MSG), None) + .unwrap(), + ) + }) + }); + group.bench_function("pss_verify_sha256", |b| { + b.iter(|| { + pk.key::() + .verify(black_box(MSG), None, black_box(&sig_pss_256)) + .unwrap() + }) + }); + group.bench_function("pss_sign_sha384", |b| { + b.iter(|| { + black_box( + sk.key::() + .sign(&mut DefaultRNG::default(), black_box(MSG), None) + .unwrap(), + ) + }) + }); + group.bench_function("pss_verify_sha384", |b| { + b.iter(|| { + pk.key::() + .verify(black_box(MSG), None, black_box(&sig_pss_384)) + .unwrap() + }) + }); + group.bench_function("pss_sign_sha512", |b| { + b.iter(|| { + black_box( + sk.key::() + .sign(&mut DefaultRNG::default(), black_box(MSG), None) + .unwrap(), + ) + }) + }); + group.bench_function("pss_verify_sha512", |b| { + b.iter(|| { + pk.key::() + .verify(black_box(MSG), None, black_box(&sig_pss_512)) + .unwrap() + }) + }); + group.bench_function("pss_sign_shake128", |b| { + b.iter(|| { + black_box( + sk.key::() + .sign(&mut DefaultRNG::default(), black_box(MSG), None) + .unwrap(), + ) + }) + }); + group.bench_function("pss_verify_shake128", |b| { + b.iter(|| { + pk.key::() + .verify(black_box(MSG), None, black_box(&sig_pss_shake128)) + .unwrap() + }) + }); + + // RSASVE (SP 800-56B Rev. 2 §7.2.1) under the same key material, re-read as KEM key types + // through the shared raw encoding. Encapsulation is one public-exponent modexp plus the RNG + // draw; decapsulation is the same CRT exponentiation signing does. + let kem_sk = RSA3072KEMPrivateKey::from_bytes(&sk.key::().encode()).unwrap(); + let kem_pk = RSA3072KEMPublicKey::from_bytes(&pk.key::().encode()).unwrap(); + let (_, kem_ct) = kem_pk.encaps(&mut rng, ()).unwrap(); + group.bench_function("rsasve_encaps", |b| { + b.iter(|| black_box(black_box(&kem_pk).encaps(&mut rng, ()).unwrap())) + }); + group.bench_function("rsasve_decaps", |b| { + b.iter(|| black_box(black_box(&kem_sk).decaps(black_box(&kem_ct), ()).unwrap())) + }); + + // RSAES-OAEP (RFC 8017 §7.1) on the same KEM keys, with SHA-256. + let oaep = OaepParams::::new(b""); + let (_, oaep_ct) = kem_pk.encaps(&mut rng, oaep).unwrap(); + group.bench_function("oaep_sha256_encaps", |b| { + b.iter(|| black_box(black_box(&kem_pk).encaps(&mut rng, oaep).unwrap())) + }); + group.bench_function("oaep_sha256_decaps", |b| { + b.iter(|| black_box(black_box(&kem_sk).decaps(black_box(&oaep_ct), oaep).unwrap())) + }); + + group.finish(); + + // FIPS 186-5 A.1.3 key generation: rejection sampling, so the run-to-run spread is large; + // ten samples is enough to see the order of magnitude without a multi-minute bench. + let mut keygen_group = c.benchmark_group("rsa_3072_keygen"); + keygen_group.sample_size(10); + keygen_group.bench_function("keygen", |b| { + b.iter(|| black_box(RSA3072::keygen(&mut DefaultRNG::default()).unwrap())) + }); + keygen_group.finish(); +} + +criterion_group!(benches, bench_rsa_3072); +criterion_main!(benches); diff --git a/crypto/rsa/benches/rsa_4096_benches.rs b/crypto/rsa/benches/rsa_4096_benches.rs new file mode 100644 index 000000000..d10c2ab20 --- /dev/null +++ b/crypto/rsa/benches/rsa_4096_benches.rs @@ -0,0 +1,237 @@ +//! Criterion benches for RSA-4096. See `rsa_2048_benches.rs`'s docs for the rationale; the genuine +//! key is the same one `tests/rsa_4096_tests.rs` recovers from Wycheproof's +//! `rsa_pkcs1_4096_sig_gen_test.json`. `shake256` (not `shake128`) is the SHAKE choice wired up at +//! this modulus size (RFC 8702 SS5). + +use bouncycastle_core::kem_key::{DecapsulatingKey, EncapsulatingKey}; +use bouncycastle_core::signature_key::{ + DeterministicOneShotSigningKey, OneShotSigningKey, OneShotVerifyingKey, +}; +use bouncycastle_core::traits::{PrivateKey, PublicKey}; +use bouncycastle_rsa::RSA4096; +use bouncycastle_rsa::rsa_4096::{RSA4096KEMPrivateKey, RSA4096KEMPublicKey}; +use bouncycastle_rsa::rsaes_oaep::OaepParams; +use bouncycastle_sha2::SHA256; +use criterion::{Criterion, criterion_group, criterion_main}; +use std::hint::black_box; + +use bouncycastle_rng::DefaultRNG; +use bouncycastle_rsa::keys::{RsaPrivateComponents, RsaPublicComponents}; +use bouncycastle_rsa::rsa_4096::{ + RSASSA_PKCS1_v1_5_SHA256, RSASSA_PKCS1_v1_5_SHA384, RSASSA_PKCS1_v1_5_SHA512, + RSASSA_PSS_SHA256, RSASSA_PSS_SHA384, RSASSA_PSS_SHA512, RSASSA_PSS_SHAKE256, +}; + +const MSG: &[u8] = b"a representative message for benchmarking RSA-4096"; + +fn genuine_key() -> RsaPrivateComponents { + let p: [u64; 32] = [ + 0x5141acd4afd4771f, 0x5857742b7e4032dc, 0xb7a9b97fe5371396, 0x4b1783c5bc91a6dc, + 0xaf5d0c912d97b728, 0xeb265a7f28b88976, 0x5e993302aa72f11d, 0xc007ad09d76ae22a, + 0x44cbb87b8bec8fd3, 0xf152f15c73b95ac5, 0x8dbdad655fbbad20, 0x59855d0de1c794ac, + 0x4c6060926d878a20, 0xf38860474e44993d, 0x177a91caeef98b13, 0xd1676123544d3def, + 0xc1673063d8487390, 0xfedd55ba2e233a6d, 0x016a5735b883c639, 0xbd813f9fb752805b, + 0x923a7b775b5ffaff, 0xb174e55ca6a12c21, 0x0373077895a6934a, 0x6b725388f54ffea3, + 0x953c09104e1fd2d3, 0x9114f39017871528, 0x33918eb72b786b3c, 0xf43b8626af13d14a, + 0x886a0904eb486140, 0x0037409b81f3a5b3, 0x19e44e26140d2ede, 0xc3c677495c2bd566, + ]; + let q: [u64; 32] = [ + 0xee0745546a6a1c73, 0x8b1050436d882425, 0xdc2e7872ce6fb2b7, 0xf98671ee4899050b, + 0x796a5dd847400804, 0x9ba1f51132355792, 0xc39066a9fc27985b, 0x81f4bca5d15e0962, + 0x6a46cf6dbb6d2ad9, 0xdf3d085ae7693b7e, 0xf58e3c750b6d978a, 0xb52b9000d3a7aab1, + 0xdbb07e23bce1960c, 0x4e291b5c8ddaa6a7, 0x0544a7a7cb3f0792, 0xc695e324fbb11beb, + 0xbded418507f2f175, 0x49fe5f47737ff436, 0xeb37f85b7554d7ad, 0x724d042aef25cea2, + 0xeadbd11dcd2fec7b, 0xb50812705b379f5d, 0xfc50fa98fb67b746, 0x16f2bdf5964b26c7, + 0xcc1c817507859246, 0x6810c2136ad81b16, 0xd7bc78d637e17e0e, 0x6882825347455782, + 0xcdb615d921f5e705, 0x0a982efbe6658e6b, 0x59e96686f7b8752f, 0xc357cf685f9b8d4e, + ]; + let d_p: [u64; 32] = [ + 0x3cd8e91fee6bcdd3, 0x074fdc015ab1c45f, 0x34135987a2288907, 0xf6961d44dfb7505c, + 0x251be32315a85b75, 0xe8982e8493a2ae78, 0xc268493861002977, 0x140fb5806735814e, + 0x35d426d719b12c41, 0xa5f194dbbf374226, 0xa0a6c5314c1a2375, 0x66899d59c04b60c4, + 0x5158d7867dbfec94, 0xec1dde997c00125e, 0x62e5a19b2a71decf, 0x310291892c37e8a2, + 0x223e06c9521f4a45, 0xe4f08e1d5543ed74, 0xcf4dc8de58b9e9ad, 0x9167ad4f122b3263, + 0xf110dbac286712f6, 0x2db237d0f39cda5f, 0xa54b67367c857476, 0x138b37b7b1ed2219, + 0x950d9f4e82aab9bc, 0x90943e671e928e23, 0x44791809c9fcf19f, 0xc70396da054ba478, + 0x77248f6fe00e31bd, 0xf3731b1415d5f2ee, 0xf5242aa6657760cd, 0xa6bbb5460638d2b2, + ]; + let d_q: [u64; 32] = [ + 0xfa935bd36284ea6b, 0x9c255a57d6b3ac0f, 0x35b350881ec52e99, 0xf48d35dd11598957, + 0x61fee5d3763b8cfb, 0xf86f5d1936a161ae, 0x3a8b852507264ae2, 0xe558f90950a572a2, + 0x205aeb15029c95a6, 0x0fa8cf020e960c3b, 0x6a793c66abfb0963, 0xa9c7d7b391d0cbee, + 0x6310f31421e85c6b, 0xc0de89d2edb32796, 0x1cf37af6eab4ed97, 0x1533eacf819c878e, + 0xc700fc7e2a482abe, 0x4d1c62a63d917682, 0x89141558095c3228, 0x029bb05df0b8f121, + 0xa239e00b24ba9b5b, 0x74c3c55d5051f35f, 0x2f45200123860c7d, 0x4fabf224d27abaf1, + 0x0acb80fbf7ed2d86, 0x87db455a8bee03ce, 0x980bbbd1afa8fac6, 0x9d9ee6515ded4930, + 0x4c62a05dae0f744b, 0x69ff90e2839348c9, 0xda141e6d351e42da, 0x178cd58f72bf5118, + ]; + let q_inv: [u64; 32] = [ + 0x5792505b857d3e8d, 0x8a13922b1240c0d2, 0xb5fcb8bf3df1f936, 0x74483606c2cd7ed8, + 0xd40f33bbfd9be093, 0xb5f40ed6632989f5, 0x7f2cc0cd8c8a0661, 0x87630c6b25dddeb5, + 0x7032a5af6ef7c20f, 0x90331600142e6cb9, 0x67b92645b68c6d8f, 0xb63517c7c39843cf, + 0xd50712bf8fc35882, 0x3c421e2447b1a989, 0x7a251afa7aaa6908, 0x43b4de11f99b2654, + 0x1e02735920ef48a3, 0x218fc24da34ce8f0, 0x280446e49b3b9b15, 0x8d96f07411c882bf, + 0x66e283f5d5fb0e6e, 0x0844efd28d853446, 0x5eb4def8dba57b99, 0x474111f92d19f3ab, + 0x748d7b5d94cacd4d, 0xcf634f3a07cea4b7, 0x8dbcca51f4da4379, 0x80774236a54ec9dc, + 0x6a1ef00ee582d3d1, 0xdecfb14ca1e80c8e, 0xc78af5f6c807cc99, 0x484ad86e79415ea3, + ]; + RsaPrivateComponents::::from_crt_components(&p, &q, &d_p, &d_q, &q_inv, 0x10001) + .expect("genuine RSA-4096 CRT components must be accepted") +} + +fn bench_rsa_4096(c: &mut Criterion) { + let sk = genuine_key(); + let pk = RsaPublicComponents::::new(sk.n(), 0x10001).unwrap(); + let mut rng = DefaultRNG::default(); + + let sig_pkcs1_256 = sk.key::().sign_deterministic(MSG, None).unwrap(); + let sig_pkcs1_384 = sk.key::().sign_deterministic(MSG, None).unwrap(); + let sig_pkcs1_512 = sk.key::().sign_deterministic(MSG, None).unwrap(); + let sig_pss_256 = sk.key::().sign(&mut rng, MSG, None).unwrap(); + let sig_pss_384 = sk.key::().sign(&mut rng, MSG, None).unwrap(); + let sig_pss_512 = sk.key::().sign(&mut rng, MSG, None).unwrap(); + let sig_pss_shake256 = sk.key::().sign(&mut rng, MSG, None).unwrap(); + + let mut group = c.benchmark_group("rsa_4096"); + + group.bench_function("pkcs1v15_sign_sha256", |b| { + b.iter(|| { + black_box( + sk.key::() + .sign_deterministic(black_box(MSG), None) + .unwrap(), + ) + }) + }); + group.bench_function("pkcs1v15_verify_sha256", |b| { + b.iter(|| { + pk.key::() + .verify(black_box(MSG), None, black_box(&sig_pkcs1_256)) + .unwrap() + }) + }); + group.bench_function("pkcs1v15_sign_sha384", |b| { + b.iter(|| { + black_box( + sk.key::() + .sign_deterministic(black_box(MSG), None) + .unwrap(), + ) + }) + }); + group.bench_function("pkcs1v15_verify_sha384", |b| { + b.iter(|| { + pk.key::() + .verify(black_box(MSG), None, black_box(&sig_pkcs1_384)) + .unwrap() + }) + }); + group.bench_function("pkcs1v15_sign_sha512", |b| { + b.iter(|| { + black_box( + sk.key::() + .sign_deterministic(black_box(MSG), None) + .unwrap(), + ) + }) + }); + group.bench_function("pkcs1v15_verify_sha512", |b| { + b.iter(|| { + pk.key::() + .verify(black_box(MSG), None, black_box(&sig_pkcs1_512)) + .unwrap() + }) + }); + group.bench_function("pss_sign_sha256", |b| { + b.iter(|| { + black_box( + sk.key::() + .sign(&mut DefaultRNG::default(), black_box(MSG), None) + .unwrap(), + ) + }) + }); + group.bench_function("pss_verify_sha256", |b| { + b.iter(|| { + pk.key::() + .verify(black_box(MSG), None, black_box(&sig_pss_256)) + .unwrap() + }) + }); + group.bench_function("pss_sign_sha384", |b| { + b.iter(|| { + black_box( + sk.key::() + .sign(&mut DefaultRNG::default(), black_box(MSG), None) + .unwrap(), + ) + }) + }); + group.bench_function("pss_verify_sha384", |b| { + b.iter(|| { + pk.key::() + .verify(black_box(MSG), None, black_box(&sig_pss_384)) + .unwrap() + }) + }); + group.bench_function("pss_sign_sha512", |b| { + b.iter(|| { + black_box( + sk.key::() + .sign(&mut DefaultRNG::default(), black_box(MSG), None) + .unwrap(), + ) + }) + }); + group.bench_function("pss_verify_sha512", |b| { + b.iter(|| { + pk.key::() + .verify(black_box(MSG), None, black_box(&sig_pss_512)) + .unwrap() + }) + }); + group.bench_function("pss_sign_shake256", |b| { + b.iter(|| { + black_box( + sk.key::() + .sign(&mut DefaultRNG::default(), black_box(MSG), None) + .unwrap(), + ) + }) + }); + group.bench_function("pss_verify_shake256", |b| { + b.iter(|| { + pk.key::() + .verify(black_box(MSG), None, black_box(&sig_pss_shake256)) + .unwrap() + }) + }); + + // RSASVE (SP 800-56B Rev. 2 §7.2.1) under the same key material, re-read as KEM key types + // through the shared raw encoding. Encapsulation is one public-exponent modexp plus the RNG + // draw; decapsulation is the same CRT exponentiation signing does. + let kem_sk = RSA4096KEMPrivateKey::from_bytes(&sk.key::().encode()).unwrap(); + let kem_pk = RSA4096KEMPublicKey::from_bytes(&pk.key::().encode()).unwrap(); + let (_, kem_ct) = kem_pk.encaps(&mut rng, ()).unwrap(); + group.bench_function("rsasve_encaps", |b| { + b.iter(|| black_box(black_box(&kem_pk).encaps(&mut rng, ()).unwrap())) + }); + group.bench_function("rsasve_decaps", |b| { + b.iter(|| black_box(black_box(&kem_sk).decaps(black_box(&kem_ct), ()).unwrap())) + }); + + // RSAES-OAEP (RFC 8017 §7.1) on the same KEM keys, with SHA-256. + let oaep = OaepParams::::new(b""); + let (_, oaep_ct) = kem_pk.encaps(&mut rng, oaep).unwrap(); + group.bench_function("oaep_sha256_encaps", |b| { + b.iter(|| black_box(black_box(&kem_pk).encaps(&mut rng, oaep).unwrap())) + }); + group.bench_function("oaep_sha256_decaps", |b| { + b.iter(|| black_box(black_box(&kem_sk).decaps(black_box(&oaep_ct), oaep).unwrap())) + }); + + group.finish(); +} + +criterion_group!(benches, bench_rsa_4096); +criterion_main!(benches); diff --git a/crypto/rsa/benches/rsa_8192_benches.rs b/crypto/rsa/benches/rsa_8192_benches.rs new file mode 100644 index 000000000..3f5c149cf --- /dev/null +++ b/crypto/rsa/benches/rsa_8192_benches.rs @@ -0,0 +1,260 @@ +//! Criterion benches for RSA-8192. See `rsa_2048_benches.rs`'s docs for the rationale; the genuine +//! key is the same fresh, self-generated one `tests/rsa_8192_tests.rs` uses for its BC Java +//! cross-check (see that file for the full provenance). No PSS-SHAKE variant is benched: none is +//! wired up at this modulus size (see `bouncycastle_rsa::rsa_8192`'s docs for why). + +use bouncycastle_core::kem_key::{DecapsulatingKey, EncapsulatingKey}; +use bouncycastle_core::signature_key::{ + DeterministicOneShotSigningKey, OneShotSigningKey, OneShotVerifyingKey, +}; +use bouncycastle_core::traits::{PrivateKey, PublicKey}; +use bouncycastle_rsa::RSA8192; +use bouncycastle_rsa::rsa_8192::{RSA8192KEMPrivateKey, RSA8192KEMPublicKey}; +use bouncycastle_rsa::rsaes_oaep::OaepParams; +use bouncycastle_sha2::SHA256; +use criterion::{Criterion, criterion_group, criterion_main}; +use std::hint::black_box; + +use bouncycastle_rng::DefaultRNG; +use bouncycastle_rsa::keys::{RsaPrivateComponents, RsaPublicComponents}; +use bouncycastle_rsa::rsa_8192::{ + RSASSA_PKCS1_v1_5_SHA256, RSASSA_PKCS1_v1_5_SHA384, RSASSA_PKCS1_v1_5_SHA512, + RSASSA_PSS_SHA256, RSASSA_PSS_SHA384, RSASSA_PSS_SHA512, +}; + +const MSG: &[u8] = b"a representative message for benchmarking RSA-8192"; + +fn genuine_key() -> RsaPrivateComponents { + let p: [u64; 64] = [ + 0xa9a87892c469b1e5, 0x038c3f4efcb198ac, 0xed4f14df1b8a1e1f, 0xef2330d78ee73020, + 0xd3093ddaf276904c, 0x94a438d69aeaff23, 0x48dbb3d700ad58ed, 0xbbd763b5346ff916, + 0xea402fb475938e3e, 0xcaed4c45c543aff3, 0xc0954c4255b90f57, 0x2fe6242da64a5099, + 0x3fd54a6b6175342c, 0xdf8dd0187588abbd, 0x4abc11d33376e220, 0x90d3482c7fc1397d, + 0xde925fb5a2cb1e7e, 0x062e99dfbd3c790b, 0x243ef703c0912a1e, 0x91ee31a02ef1a02e, + 0x13b19d3960842877, 0xc6e8036e26c4a339, 0xf2606f45a73314c9, 0x5dfe4c6dd0aa04ee, + 0x1385bfde55204d94, 0x454123829d28200d, 0x18a3d86f516f2a50, 0xcbe5e841cd2fdb17, + 0xc86825aae3031a2c, 0xf4726a6681852b6e, 0x3f16b45a496eee29, 0xd5c4b2319abff492, + 0x71077736745aee55, 0x72586dba7b765bbe, 0x681813f6851efdce, 0x196c13fa6d6781d2, + 0x4712ba3eb0734e43, 0xde2a9a8da6da8340, 0xc2f93a2af8ffbaaa, 0x4db552ab82a577ae, + 0x07c075eb13064f67, 0x818a7d0b31680682, 0xa58320f732d69460, 0xa5922479f4aaf594, + 0x4d545baa4cd73f39, 0xa20c87a2660869c4, 0x8350211511fe7d7a, 0x50174a372234ba89, + 0x6eefd36b20bd1ce7, 0x07d124cb61d25c8b, 0x7356e6380041dcd5, 0x6a7c98caab76211a, + 0x61ff7eaac65f815d, 0x1167dc0b28f418b3, 0x9fc8bf056efe8677, 0xf5ce4481e1670e10, + 0x6ae488da222292de, 0xcc786e194ea84d2a, 0x41b134cb6a8ae4f5, 0x870ff94b064466b7, + 0xc82ad608c14a9385, 0x5338550ac9d3f96d, 0xdce87e0d41f1ba9d, 0xef9beedb39920589, + ]; + let q: [u64; 64] = [ + 0x08798e2dd82b7d9f, 0x30208e668897171d, 0x8f73c28d70144ec6, 0x66f64ce7d2402ae0, + 0xdbc26c601d5cc3a3, 0x657176891201beee, 0x692812d7b9b796c5, 0xae27fa9062406a23, + 0x7b4e6ee5b4d2d22f, 0xd846e0e8fbeb0108, 0x52ca75d6866b780b, 0x2620152d7bb490c0, + 0xdca773f826ba9118, 0xb308499a61d0a4eb, 0x44ba0f58bff07ed5, 0x268483fe5829eb5c, + 0x02e7f0c1d3ee3856, 0x76eae3a004d0f37a, 0x99d9cb3aab5b3f1f, 0x0c9f76678a44f2c4, + 0xc82ba3f75883e512, 0x57719c85e8888746, 0x63c967ca1b81cf17, 0x6f4942a86e96bb6a, + 0x614105324fdb77ae, 0xdb6a0c777f7a4bbc, 0x184bf293127472d5, 0xc26798126a967a8f, + 0x45fa10ccadd5ef6e, 0x13cacbbf5cbc2722, 0x23b4e2f2d18785fd, 0x83a4d39485ad254b, + 0x3a096f5ddd674174, 0x6df8f2ed81ae9e7e, 0x77ee2d29fb78201d, 0x4b4c10c9ac8853eb, + 0x35690c51d0ff6208, 0x8de9a271cb50aa59, 0x51b0701f8cdd1505, 0x4cb715c9b578c63b, + 0x3c9b35776d94c3c7, 0xe952d6a7c34a2abb, 0xc432f1fcc2a5105f, 0x4f7f23a62cea2f81, + 0xfa507889f33eedd9, 0x7e37e435cb776085, 0x576b2ad8a4f39820, 0x0a85d1466d55ad69, + 0xb1dee047621be714, 0x216c6b3c1c945527, 0xe6298f6e1575e39e, 0xdd16506432adc399, + 0xc1c065319c823d2e, 0xf2d6f25d6f34a582, 0x75d6801f595c50fc, 0xccfcd556c20e1130, + 0xa24e6a1396173d85, 0xe2cbc5218657c80a, 0xe7bec5bf5a944815, 0x656f5fa54bf06f6c, + 0x7b68b002b0ea62d7, 0xa2eb84753d291781, 0xdd329e1ce00c2087, 0xcdb932d13e38ee0a, + ]; + let d_p: [u64; 64] = [ + 0x848c4d06bcab4c19, 0x2fa349116ae2bfd6, 0xcf9ea12f426f7eb3, 0xfa71d15136d85dff, + 0xc3e3a026e3968f1f, 0xd50f8056de82a33e, 0x68213465c1b3b2d7, 0x426387f62ee9c62e, + 0xeb14efe18920a873, 0xf3c385a60c9dc86c, 0x294ffd8852c4d95e, 0x940d14b53927fef5, + 0x3f709e3b4c8390c3, 0x3b9737d39c42994b, 0x5c02182c4dac78fe, 0x3b6b7c01fe0a0737, + 0x7adeedf6194f6d2c, 0x43c30f449d8ae36c, 0xb88cebf30dac95d4, 0x09fc3d623b8ceb6b, + 0x5d28293b759f2b09, 0xd350dee095846993, 0x1b323dc92b794164, 0xe19d52f0e7ef34bb, + 0x5ff017da15232c02, 0x58fa8d3b24b82973, 0x1c8aed916227e53f, 0xad49cd8938c909d4, + 0xc3d98be0501534a1, 0x91cec83019bd5bb6, 0x985b814d838ffdd2, 0x11df5cb357c86888, + 0xbc0d5590336b8dcf, 0xc25fa85b1912ac66, 0x390c8752384cadef, 0x07b54e62df65825a, + 0x7f7ad57e592cfc3b, 0xed1b7f53d6fe2a09, 0x41d9e577118adb13, 0xb6706780ace45139, + 0xbfbaadef8d19443b, 0x3dc42a1dccca1d87, 0xdb8a72a8ca8d4de7, 0xe10dec18507dbc43, + 0x66343911cfeb0313, 0xd29def907cf51b72, 0x998add714f12ef6f, 0x1c394a4b8053f8ec, + 0x46e0b76d81a07852, 0x498c3f81cb9f2b8d, 0x8fd0019a024e19be, 0xf2d405423b1d94e4, + 0x29ce52d9c49ff544, 0xd72643a03a2f9053, 0x1be76a355cfa02d2, 0x8db921cec169edf6, + 0x728f91a0f7d9dc15, 0xe34e3a4f3d41d26d, 0xab0a691f05332eb8, 0xb6241cc75fd5ee1b, + 0x5b8582afd5c1acda, 0xe405bceba411da3e, 0xd849aacac396ef0e, 0x57b5a6ebccd92cf9, + ]; + let d_q: [u64; 64] = [ + 0x77a312e8aa49ed35, 0x3bdc007b0396dd44, 0x187af52b1d2d6e88, 0x7d84fae3e1b134fa, + 0xb1af50faa281bf7d, 0xf868401279f57864, 0x1dba1e456f88eb01, 0xe2ee28d0f43ba792, + 0x3450781c72a68626, 0x30757ab4889c0c41, 0x7f34c53326389381, 0xa28e969fda4bc5e4, + 0x0ed664e6b7a53062, 0xfc9ad2c9c2bd3cf2, 0x1a7bb5627d58e8ba, 0x68b8c4da5a5a5104, + 0x5a0e586f0ebe7967, 0x2dcff7ca08c9b702, 0x89a724facd778478, 0x027fe07b2ad90a40, + 0xd2f67b0b487433d5, 0x28d451f2f0eaa3ad, 0xee8d5d55700c24ca, 0x584202d4e805a701, + 0xa1c40f0ed77d96a5, 0xc4055e480f1674ba, 0xf9fb2aeb561bf104, 0x6b846fe9ef936161, + 0x128295b5f01cf2ad, 0x4aaff225e483b5dd, 0x7cba43b61174a21c, 0xf68f9c7b4474bcbd, + 0xc8979d3dd627346e, 0x9c2b543e42af83ed, 0x221d3779bb596a50, 0xac4d7c5545e7c88b, + 0xa44c83a4cb2ffe15, 0x414d71c3a67b3563, 0xe22dd5c34f66bf5e, 0x6a9cd6374f4513e7, + 0x27765c4e3c8ee4d5, 0xf632603a9e123d3f, 0x748b0b2d39fcb6bd, 0x0bde2fc8edf891e6, + 0xded2b9cf10705222, 0xe5ca5d358eb8067a, 0x23368f3218b1bd0c, 0xe41d6519183900d0, + 0x36d90382237f0987, 0x858624f4663a543a, 0x2309265e924e5f4c, 0xfc548ae0263785e8, + 0xe010d5d5e76f3406, 0x963cc28c4228ff36, 0x4245a573c17ac537, 0x7e9ab38877e4d606, + 0xc69b8cfcee4fba17, 0xe127881203d02766, 0xf3b33254ff10a7b7, 0x4df7b087512a53dd, + 0x28ffecc1c7a3ee5d, 0x4c693f99aa4b22b7, 0x498cdaef4c3d1223, 0x78c24ba834042b07, + ]; + let q_inv: [u64; 64] = [ + 0xd87df1de9c759f36, 0x3ee1b8b22c8eab2d, 0xd6098595c2696717, 0xa922e4722b8304de, + 0x424bec1c55c1db54, 0x918f2f8bf0ac261a, 0x1e190b2089185564, 0xc0dedbfc6ee606bb, + 0x1d1d701caca565c9, 0x2d735f7a1c5b9d67, 0x8339684f656205db, 0xc2dc06896727d9ce, + 0x6c8d6fe334141d31, 0x5245e157c87cd8b4, 0x4975b68eb2eaad9a, 0xfbc3389ffb0e788d, + 0x5e9a45250d135847, 0x676e7e6a128cfa88, 0x74341d8b28dcbcb8, 0x8f7d07f37a0490e0, + 0x83a0eae9ecc99a0e, 0xa8188892180dc052, 0x3cd79e1eea7809cb, 0x3bcc1d769d917b24, + 0x1d8dc8edc7268e8d, 0x3ce2707055f522ca, 0x163ead0ca2eb5fee, 0xf147fb695aa70022, + 0xab406a6c89161f7d, 0x8fbbfe117a95f46e, 0xa16d4e65396165bd, 0xb54f52ab1bb357e5, + 0x67cdec7b6a349ed9, 0x303875e0d97cf3fa, 0x0af9378ecb114fd8, 0x4ada6f45b9d6b1df, + 0x9ef2cf55de53d0ed, 0x33e4c2070b165b52, 0x3feddf0f7a1158c0, 0x91463a2b1952e83a, + 0x65a9db73de55ef6b, 0x8e18c716a69a9a6a, 0x0ca44356ca6e2898, 0x7df214b19f2114f1, + 0x9af2aee9d5cf1077, 0x22fc8b019fd3d0ff, 0x50c6eead29ab18cd, 0xa7e6621f8eae45fe, + 0x588bde2d99b8692d, 0x339be0a07b4f0a7b, 0xcbdbdcc8717105d2, 0x78bbd3e3392a503e, + 0xb868f9db1cf14f74, 0x52f3dc7f028c9f7e, 0xa3629e034b453834, 0x52bab134f3ae91a2, + 0xd1aac2fe108f98c0, 0x1e799537a42b3060, 0xdbcce6fc287e449b, 0x1985969e5afbc524, + 0x61ba61f820f83597, 0x65c8523f0767bccc, 0xde04e1644a214f9a, 0x9748f8d853be7131, + ]; + RsaPrivateComponents::::from_crt_components(&p, &q, &d_p, &d_q, &q_inv, 0x10001) + .expect("genuine RSA-8192 CRT components must be accepted") +} + +fn bench_rsa_8192(c: &mut Criterion) { + let sk = genuine_key(); + let pk = RsaPublicComponents::::new(sk.n(), 0x10001).unwrap(); + let mut rng = DefaultRNG::default(); + + let sig_pkcs1_256 = sk.key::().sign_deterministic(MSG, None).unwrap(); + let sig_pkcs1_384 = sk.key::().sign_deterministic(MSG, None).unwrap(); + let sig_pkcs1_512 = sk.key::().sign_deterministic(MSG, None).unwrap(); + let sig_pss_256 = sk.key::().sign(&mut rng, MSG, None).unwrap(); + let sig_pss_384 = sk.key::().sign(&mut rng, MSG, None).unwrap(); + let sig_pss_512 = sk.key::().sign(&mut rng, MSG, None).unwrap(); + + let mut group = c.benchmark_group("rsa_8192"); + + group.bench_function("pkcs1v15_sign_sha256", |b| { + b.iter(|| { + black_box( + sk.key::() + .sign_deterministic(black_box(MSG), None) + .unwrap(), + ) + }) + }); + group.bench_function("pkcs1v15_verify_sha256", |b| { + b.iter(|| { + pk.key::() + .verify(black_box(MSG), None, black_box(&sig_pkcs1_256)) + .unwrap() + }) + }); + group.bench_function("pkcs1v15_sign_sha384", |b| { + b.iter(|| { + black_box( + sk.key::() + .sign_deterministic(black_box(MSG), None) + .unwrap(), + ) + }) + }); + group.bench_function("pkcs1v15_verify_sha384", |b| { + b.iter(|| { + pk.key::() + .verify(black_box(MSG), None, black_box(&sig_pkcs1_384)) + .unwrap() + }) + }); + group.bench_function("pkcs1v15_sign_sha512", |b| { + b.iter(|| { + black_box( + sk.key::() + .sign_deterministic(black_box(MSG), None) + .unwrap(), + ) + }) + }); + group.bench_function("pkcs1v15_verify_sha512", |b| { + b.iter(|| { + pk.key::() + .verify(black_box(MSG), None, black_box(&sig_pkcs1_512)) + .unwrap() + }) + }); + group.bench_function("pss_sign_sha256", |b| { + b.iter(|| { + black_box( + sk.key::() + .sign(&mut DefaultRNG::default(), black_box(MSG), None) + .unwrap(), + ) + }) + }); + group.bench_function("pss_verify_sha256", |b| { + b.iter(|| { + pk.key::() + .verify(black_box(MSG), None, black_box(&sig_pss_256)) + .unwrap() + }) + }); + group.bench_function("pss_sign_sha384", |b| { + b.iter(|| { + black_box( + sk.key::() + .sign(&mut DefaultRNG::default(), black_box(MSG), None) + .unwrap(), + ) + }) + }); + group.bench_function("pss_verify_sha384", |b| { + b.iter(|| { + pk.key::() + .verify(black_box(MSG), None, black_box(&sig_pss_384)) + .unwrap() + }) + }); + group.bench_function("pss_sign_sha512", |b| { + b.iter(|| { + black_box( + sk.key::() + .sign(&mut DefaultRNG::default(), black_box(MSG), None) + .unwrap(), + ) + }) + }); + group.bench_function("pss_verify_sha512", |b| { + b.iter(|| { + pk.key::() + .verify(black_box(MSG), None, black_box(&sig_pss_512)) + .unwrap() + }) + }); + + // RSASVE (SP 800-56B Rev. 2 §7.2.1) under the same key material, re-read as KEM key types + // through the shared raw encoding. Encapsulation is one public-exponent modexp plus the RNG + // draw; decapsulation is the same CRT exponentiation signing does. + let kem_sk = RSA8192KEMPrivateKey::from_bytes(&sk.key::().encode()).unwrap(); + let kem_pk = RSA8192KEMPublicKey::from_bytes(&pk.key::().encode()).unwrap(); + let (_, kem_ct) = kem_pk.encaps(&mut rng, ()).unwrap(); + group.bench_function("rsasve_encaps", |b| { + b.iter(|| black_box(black_box(&kem_pk).encaps(&mut rng, ()).unwrap())) + }); + group.bench_function("rsasve_decaps", |b| { + b.iter(|| black_box(black_box(&kem_sk).decaps(black_box(&kem_ct), ()).unwrap())) + }); + + // RSAES-OAEP (RFC 8017 §7.1) on the same KEM keys, with SHA-256. + let oaep = OaepParams::::new(b""); + let (_, oaep_ct) = kem_pk.encaps(&mut rng, oaep).unwrap(); + group.bench_function("oaep_sha256_encaps", |b| { + b.iter(|| black_box(black_box(&kem_pk).encaps(&mut rng, oaep).unwrap())) + }); + group.bench_function("oaep_sha256_decaps", |b| { + b.iter(|| black_box(black_box(&kem_sk).decaps(black_box(&oaep_ct), oaep).unwrap())) + }); + + group.finish(); +} + +criterion_group!(benches, bench_rsa_8192); +criterion_main!(benches); diff --git a/crypto/rsa/src/codec.rs b/crypto/rsa/src/codec.rs new file mode 100644 index 000000000..1b37d9596 --- /dev/null +++ b/crypto/rsa/src/codec.rs @@ -0,0 +1,33 @@ +//! Big-endian byte-string <-> little-endian limb-array conversion: RFC 8017 §4's OS2IP/I2OSP, +//! specialized to this crate's fixed-width keys (every modulus size this crate offers is a whole +//! number of 64-bit limbs, so the byte length is always exactly `8 * L`) rather than OS2IP's +//! arbitrary-length octet string. `BYTES = 8 * L` is a separate const parameter rather than a +//! computed one for the same reason [`bouncycastle_ec::montgomery`]'s `L2 = 2 * L` is: stable +//! Rust cannot express one const generic as a function of another. +//! +//! Fixed arrays throughout, not slices with a runtime length check: every caller in this crate +//! knows `BYTES` at compile time (it is the modulus's own byte length), so there is nothing to +//! validate at a boundary here -- both directions are infallible. + +/// OS2IP (RFC 8017 §4.2): a big-endian byte string into little-endian limbs. +pub fn limbs_from_be_bytes(bytes: &[u8; BYTES]) -> [u64; L] { + debug_assert_eq!(BYTES, 8 * L, "limbs_from_be_bytes needs BYTES == 8 * L"); + let mut limbs = [0u64; L]; + for i in 0..L { + let start = BYTES - (i + 1) * 8; + limbs[i] = u64::from_be_bytes(bytes[start..start + 8].try_into().expect("8-byte slice")); + } + limbs +} + +/// I2OSP (RFC 8017 §4.1): little-endian limbs into a big-endian byte string. I2OSP's "integer too +/// large" error cannot occur here: an `[u64; L]` is always `< 256^BYTES`. +pub fn be_bytes_from_limbs(limbs: &[u64; L]) -> [u8; BYTES] { + debug_assert_eq!(BYTES, 8 * L, "be_bytes_from_limbs needs BYTES == 8 * L"); + let mut bytes = [0u8; BYTES]; + for i in 0..L { + let start = BYTES - (i + 1) * 8; + bytes[start..start + 8].copy_from_slice(&limbs[i].to_be_bytes()); + } + bytes +} diff --git a/crypto/rsa/src/eme_oaep.rs b/crypto/rsa/src/eme_oaep.rs new file mode 100644 index 000000000..51044e7dd --- /dev/null +++ b/crypto/rsa/src/eme_oaep.rs @@ -0,0 +1,183 @@ +//! EME-OAEP (RFC 8017 §7.1.1 step 2 and §7.1.2 step 3): the encoding RSAES-OAEP puts a message +//! into before the RSA primitive, and the decoding that takes it back out, over a label hash +//! `H` and an MGF1 hash `M` (§B.2.1; SP 800-56B Rev. 2 §7.2.2.1 item 2: the MGF's hash "need +//! not be the same as the hash function H"). +//! +//! The decoding is the sensitive half. RFC 8017 §7.1.2's note: "Care must be taken to ensure +//! that an opponent cannot distinguish the different error conditions in Step 3.g, whether by +//! error message or timing, and, more generally, that an opponent cannot learn partial +//! information about the encoded message EM." [`decode_out`] folds every check into one mask, +//! reads the whole of `DB` whatever it holds, and moves the message out without branching or +//! indexing on where it starts. + +use crate::mgf1::{MAX_HASH_LEN, mgf1_xor}; +use bouncycastle_core::traits::{HashAlgParams, HashOneShot}; +use bouncycastle_utils::ct::value_barrier; +use bouncycastle_utils::secret::Secret; + +// The masks below are built the way `bouncycastle_utils::ct` builds its own (see its +// "Optimisation barrier" section and `acc_is_zero`): the identity "the top bit of x | -x is set +// exactly when x is not zero" is taken apart with a barrier after each step, because written in +// one piece the compiler recognises it as `x != 0` and some targets lower that to a compare and +// branch; and a mask is passed through a barrier again where it selects or is tested. + +/// 1 if `x` is not zero, else 0, without a branch. +fn not_zero_bit(x: u32) -> u32 { + let x = value_barrier(x); + let top = value_barrier(x | x.wrapping_neg()); + value_barrier(top >> 31) +} + +/// `0xFF` if `x` is not zero, else `0x00`, without a branch. +fn nonzero_mask(x: u8) -> u8 { + value_barrier((not_zero_bit(x as u32) as u8).wrapping_neg()) +} + +/// `0xFF` if `a == b`, else `0x00`, without a branch. +fn eq_mask_u32(a: u32, b: u32) -> u8 { + // The bit is 0 for equal values; subtracting 1 gives all ones. + value_barrier((not_zero_bit(a ^ b) as u8).wrapping_sub(1)) +} + +/// `lHash = Hash(L)` (§7.1.1 step 2.a) into the front of `out`; returns `hLen`. +pub(crate) fn label_hash( + label: &[u8], + out: &mut [u8; MAX_HASH_LEN], +) -> usize { + H::hash_out(label, &mut out[..H::OUTPUT_LEN]) +} + +/// EME-OAEP encoding (§7.1.1 step 2) of `msg` into `em`, the whole `k` bytes of it, with the +/// caller's `seed` (step 2.d's random octet string, `hLen` bytes). The caller has checked +/// `mLen <= k - 2hLen - 2` (step 1.b). +pub(crate) fn encode(l_hash: &[u8], seed: &[u8], msg: &[u8], em: &mut [u8]) +where + H: HashOneShot + HashAlgParams, + M: HashOneShot + HashAlgParams, +{ + let h_len = H::OUTPUT_LEN; + let k = em.len(); + debug_assert!(l_hash.len() == h_len && seed.len() == h_len); + debug_assert!(msg.len() + 2 * h_len + 2 <= k); + + // i. EM = 0x00 || maskedSeed || maskedDB, built in place. + let (y, rest) = em.split_at_mut(1); + let (seed_part, db) = rest.split_at_mut(h_len); + y[0] = 0x00; + // b., c. DB = lHash || PS || 0x01 || M, with PS of k - mLen - 2hLen - 2 zero octets. + let ps_end = db.len() - msg.len() - 1; + db[..h_len].copy_from_slice(l_hash); + db[h_len..ps_end].fill(0x00); + db[ps_end] = 0x01; + db[ps_end + 1..].copy_from_slice(msg); + // e., f. dbMask = MGF(seed, k - hLen - 1); maskedDB = DB xor dbMask. + mgf1_xor::(seed, db); + // g., h. seedMask = MGF(maskedDB, hLen); maskedSeed = seed xor seedMask. + seed_part.copy_from_slice(seed); + mgf1_xor::(db, seed_part); +} + +/// EME-OAEP decoding (§7.1.2 step 3) of `em`, all `k` bytes of it, which is unmasked in place: +/// the message into the front of `out`, and its length returned, or `None` for a decryption +/// error of any kind, with `out` zeroized. The caller has checked `k >= 2hLen + 2` (step 1.c) +/// and wipes `em`. +/// +/// With `exact_len` the message must be exactly that long, which is part of the same single +/// check; `out` must then be that long. Without it, a message longer than `out` is a decryption +/// error like any other. +/// +/// Constant time in `em`: the length of the padding string is not visible in the control flow +/// or in which memory is touched, on success or failure. Only the final success or failure is. +pub(crate) fn decode_out( + l_hash: &[u8], + em: &mut [u8], + exact_len: Option, + out: &mut [u8], +) -> Option +where + H: HashOneShot + HashAlgParams, + M: HashOneShot + HashAlgParams, +{ + let h_len = H::OUTPUT_LEN; + debug_assert!(l_hash.len() == h_len && em.len() >= 2 * h_len + 2); + out.fill(0); + + // b. EM = Y || maskedSeed || maskedDB. + let (y, rest) = em.split_at_mut(1); + let (seed, db) = rest.split_at_mut(h_len); + // c., d. seedMask = MGF(maskedDB, hLen); seed = maskedSeed xor seedMask. + mgf1_xor::(db, seed); + // e., f. dbMask = MGF(seed, k - hLen - 1); DB = maskedDB xor dbMask. + mgf1_xor::(seed, db); + + // g. DB = lHash' || PS || 0x01 || M. "If there is no octet with hexadecimal value 0x01 to + // separate PS from M, if lHash does not equal lHash', or if Y is nonzero, output + // "decryption error" and stop." `bad` gathers all three, and the length checks below. + let mut bad = nonzero_mask(y[0]); + let (l_hash_prime, ps_and_m) = db.split_at_mut(h_len); + let mut diff = 0u8; + for (a, b) in l_hash.iter().zip(l_hash_prime.iter()) { + diff |= a ^ b; + } + bad |= nonzero_mask(diff); + + // The separator is the first nonzero octet after lHash', and it must be 0x01. The scan + // reads every octet; `found` is all ones from the first nonzero octet on, and `index` is + // where it was. + let mut found = 0u8; + let mut index = 0u32; + for (i, b) in ps_and_m.iter().enumerate() { + let nonzero = nonzero_mask(*b); + let first = value_barrier(nonzero & !found); + bad |= first & nonzero_mask(*b ^ 0x01); + // index = first ? i : index, with `first` widened to 32 bits by a subtraction. + let first32 = value_barrier(0u32.wrapping_sub((first & 1) as u32)); + index = value_barrier((first32 & i as u32) | (!first32 & index)); + found = value_barrier(found | nonzero); + } + bad |= !found; + + // M is what follows the separator: ps_and_m[index + 1..], mLen bytes. + let m_start = index.wrapping_add(1); + let m_len = (ps_and_m.len() as u32).wrapping_sub(m_start); + match exact_len { + Some(len) => bad |= !eq_mask_u32(m_len, len as u32), + // m_len > out.len(): the subtraction borrows. + None => { + let borrow = value_barrier((out.len() as u32).wrapping_sub(value_barrier(m_len)) >> 31); + bad |= value_barrier((borrow as u8).wrapping_neg()); + } + } + + // The message is moved to the front of its buffer by a shift of m_start octets, done as + // one conditional shift per bit of m_start: every pass reads and writes every octet, + // whether or not it moves, so no address or branch depends on where the message starts. + let good = value_barrier(!bad); + let len = ps_and_m.len(); + let mut bit = 0; + while (1usize << bit) <= len { + let step = 1usize << bit; + let take = value_barrier(0u8.wrapping_sub(((m_start >> bit) & 1) as u8)); + for i in 0..len { + // The octet `step` places on, or zero past the end; `i + step` is public. + let from = if i + step < len { ps_and_m[i + step] } else { 0 }; + ps_and_m[i] = (ps_and_m[i] & !take) | (from & take); + } + bit += 1; + } + // The message is now ps_and_m[..m_len]; what `out` can hold of the buffer is copied, zeroed + // on failure, and the rest of `out` stays zero. A message longer than `out` is already in + // `bad`. + for (o, b) in out.iter_mut().zip(ps_and_m.iter()) { + *o = b & good; + } + + // The one visible outcome: the error, or the length. + if value_barrier(bad) != 0 { + return None; + } + Some(m_len as usize) +} + +/// A buffer for `lHash` and the seed: `hLen` bytes of [`MAX_HASH_LEN`]. +pub(crate) type HashBuf = Secret<[u8; MAX_HASH_LEN]>; diff --git a/crypto/rsa/src/emsa_pkcs1_v1_5.rs b/crypto/rsa/src/emsa_pkcs1_v1_5.rs new file mode 100644 index 000000000..4c37f1041 --- /dev/null +++ b/crypto/rsa/src/emsa_pkcs1_v1_5.rs @@ -0,0 +1,463 @@ +//! EMSA-PKCS1-v1_5 (RFC 8017 §9.2): deterministic signature encoding, generic over the hash +//! function `H` via its [`HashAlgParams`]/[`AlgorithmOID`] impls (e.g. +//! `bouncycastle_sha2::SHA256`), and specialized to this crate's fixed-width keys: RFC 8017's +//! `emLen` is always this crate's modulus byte length `K_LEN` (`8 * L`), never a generic +//! caller-chosen length. Both operations take the message's already-computed hash rather than +//! the message (step 1 of the encoding is the caller's), so that a streaming signer/verifier can +//! hash incrementally and hand in the result; `H` is never instantiated here. + +use bouncycastle_core::errors::SignatureError; +use bouncycastle_core::traits::{AlgorithmOID, HashAlgParams}; + +/// What the encodings return for a message hash that is not one output of the hash. +pub(crate) const HASH_LEN_ERROR: SignatureError = + SignatureError::LengthError("the message hash must be the hash's output length"); + +/// The largest `T` this crate builds: two SEQUENCE headers, an OID of at most 16 bytes with +/// its NULL, and a 64-byte digest behind its OCTET STRING header. +const MAX_T_LEN: usize = 2 + 2 + 16 + 2 + 2 + 64; + +/// `T`, the DER encoding of `DigestInfo { digestAlgorithm, digest }` (RFC 8017 §9.2 step 2): +/// +/// ```text +/// DigestInfo ::= SEQUENCE { digestAlgorithm AlgorithmIdentifier, digest OCTET STRING } +/// AlgorithmIdentifier ::= SEQUENCE { algorithm OBJECT IDENTIFIER, parameters NULL } +/// ``` +/// +/// Built directly from `H::OID_DER` (already the DER encoding of the `OBJECT IDENTIFIER` itself, +/// tag and length included) rather than a hand-copied table of the nine prefixes RFC 8017 §9.2 +/// note 1 lists for MD2/MD5/SHA-1/SHA-224/SHA-256/SHA-384/SHA-512/SHA-512-224/SHA-512-256: +/// wrapping `OID_DER` in the two surrounding `SEQUENCE`s and the `05 00` (`NULL`) parameters, then +/// appending the digest behind its own `04 ` (`OCTET STRING`) tag, reproduces exactly those +/// bytes -- checked against SHA-256/384/512 in this module's tests. Every DER length here +/// (`H::OID_DER.len()` and `H_LEN`) is well under 128 for every hash this crate could plausibly +/// support (SHA-3's largest output is 64 bytes), so each is a single length byte, not the +/// multi-byte long form; `debug_assert`'d, since it can only fail on a hash this crate does not +/// support, never on real input. +fn digest_info(digest: &[u8], t: &mut [u8; MAX_T_LEN]) -> usize { + let h_len = digest.len(); + debug_assert_eq!(h_len, H::OUTPUT_LEN, "digest_info: the caller checked the digest's length"); + let oid_der = H::OID_DER; + debug_assert!(oid_der.len() < 128 && h_len < 128, "DER length must fit in one byte"); + let inner_len = oid_der.len() + 2; // + 05 00 (the AlgorithmIdentifier's NULL parameters) + let outer_len = 4 + inner_len + h_len; // + "30 " and "04 " + let t_len = 2 + outer_len; + debug_assert!(t_len <= MAX_T_LEN, "digest_info: T fits MAX_T_LEN"); + t[0] = 0x30; + t[1] = outer_len as u8; + t[2] = 0x30; + t[3] = inner_len as u8; + t[4..4 + oid_der.len()].copy_from_slice(oid_der); + let mut i = 4 + oid_der.len(); + t[i] = 0x05; + t[i + 1] = 0x00; + t[i + 2] = 0x04; + t[i + 3] = h_len as u8; + i += 4; + t[i..i + h_len].copy_from_slice(digest); + t_len +} + +/// EMSA-PKCS1-v1_5-ENCODE (RFC 8017 §9.2) from the message hash, into the `K_LEN`-byte `EM`: +/// `00 || 01 || PS || 00 || T`, `PS` all `0xff` and at least 8 bytes, `T` the DER `DigestInfo` +/// of [`digest_info`]. `K_LEN >= tLen + 11` is a constant of the pairing; a pairing that +/// violates it does not exist here (the smallest modulus, 1024 bits, leaves 45 bytes of `PS` +/// under SHA-512), and is a `debug_assert`. +/// +/// A `digest` that is not `H::OUTPUT_LEN` bytes is [`HASH_LEN_ERROR`]: step 2's `DigestInfo` +/// holds `H = Hash(M)`, and no other length is a hash under `H`'s identifier. +pub fn emsa_pkcs1_v1_5_encode_from_hash( + digest: &[u8], +) -> Result<[u8; K_LEN], SignatureError> { + if digest.len() != H::OUTPUT_LEN { + return Err(HASH_LEN_ERROR); + } + let mut t = [0u8; MAX_T_LEN]; + let t_len = digest_info::(digest, &mut t); + + debug_assert!(K_LEN >= t_len + 11, "emsa_pkcs1_v1_5_encode: modulus too short for this hash"); + + let mut em = [0xffu8; K_LEN]; + em[0] = 0x00; + em[1] = 0x01; + em[K_LEN - t_len - 1] = 0x00; + em[K_LEN - t_len..].copy_from_slice(&t[..t_len]); + Ok(em) +} + +/// A single DER length octet in strict short form: `None` if the byte's top bit is set (BER's +/// long form, always rejected here -- see [`emsa_pkcs1_v1_5_verify_from_hash`]) or `bytes` doesn't reach +/// `pos`. +fn short_form_len(bytes: &[u8], pos: usize) -> Option { + let len = *bytes.get(pos)? as usize; + if len >= 0x80 { None } else { Some(len) } +} + +/// Checks that `t` is a `DigestInfo` DER encoding (RFC 8017 §9.2 step 2) of `digest` (the +/// message's hash under `H`), tolerating both `AlgorithmIdentifier` shapes: `parameters NULL` +/// (what [`digest_info`] always produces) and `parameters` ABSENT (not produced here, but present +/// in the wild: the `AlgorithmIdentifier`'s `parameters` field is `ANY DEFINED BY algorithm`, and +/// it needs none for a hash OID, so some implementations omit it) -- see +/// [`emsa_pkcs1_v1_5_verify_from_hash`]'s docs for why verification must accept it. Every other +/// check is a strict requirement: a DER length must be single-byte short form, and no byte of `t` +/// may go unaccounted for. +fn decode_digest_info(t: &[u8], digest: &[u8]) -> bool { + let mut pos = 0; + if t.first() != Some(&0x30) { + return false; + } + pos += 1; + let Some(outer_len) = short_form_len(t, pos) else { return false }; + pos += 1; + if pos + outer_len != t.len() { + return false; // T must be exactly outer_len + 2 bytes -- no trailing garbage. + } + if t.get(pos) != Some(&0x30) { + return false; + } + pos += 1; + let Some(inner_len) = short_form_len(t, pos) else { return false }; + pos += 1; + let inner_end = pos + inner_len; + // Mutating this `>` to `>=` is an accepted equivalent, not a gap: the boundary it would + // additionally reject (`inner_end == t.len()`) leaves no room after the AlgorithmIdentifier + // for the OCTET STRING tag a genuine DigestInfo always has, so `t.get(pos) != Some(&0x04)` + // below (reached once `pos` advances to `inner_end`) already rejects it -- one check later, + // same outcome. + if inner_end > t.len() { + return false; + } + let oid = H::OID_DER; + if pos + oid.len() > inner_end || t[pos..pos + oid.len()] != *oid { + return false; + } + pos += oid.len(); + if t.get(pos..pos + 2) == Some(&[0x05, 0x00]) { + pos += 2; // Optional NULL parameters -- see this function's docs. + } + if pos != inner_end { + return false; // Trailing bytes inside AlgorithmIdentifier that aren't a bare NULL. + } + if t.get(pos) != Some(&0x04) { + return false; + } + pos += 1; + let Some(digest_len) = short_form_len(t, pos) else { return false }; + pos += 1; + // Mutating this `||` to `&&` is an accepted equivalent, not a gap: the final `t[pos..]` + // comparison against `digest` (a fixed `[u8; H_LEN]`) already fails whenever either half of + // this condition is true alone -- a `digest_len` that disagrees with `H_LEN` or a + // `pos + digest_len` that disagrees with `t.len()` both show up as a slice/array length + // mismatch there, which `PartialEq` for `[u8]` against `[u8; H_LEN]` treats as unequal without + // panicking. This check exists to fail fast and by a clearer name, not because anything + // downstream depends on it having fired. + if digest_len != digest.len() || pos + digest_len != t.len() { + return false; + } + + t[pos..] == *digest +} + +/// EMSA-PKCS1-v1_5 verification of `em` against the message's hash `digest` (supplied by the +/// caller, as for [`emsa_pkcs1_v1_5_encode_from_hash`]): RFC 8017 §8.2.2's own note describes +/// this as an alternative to its step 4 ("apply a 'decoding' operation ... to recover the +/// underlying hash value, and then compare it to a newly computed hash value") -- required here, +/// rather than optional, because re-encoding the digest and comparing bytes (this crate's +/// [`emsa_pkcs1_v1_5_encode_from_hash`]) only ever produces one canonical `EM`, and +/// [`decode_digest_info`] must accept two. Checks `EM = 0x00 || 0x01 || PS || 0x00 || T` +/// structurally (at least 8 bytes of `0xff` padding, then the separator), then hands `T` to +/// [`decode_digest_info`]. +/// +/// Confirmed against every forgery-shaped case in Wycheproof's `rsa_signature_2048_sha256_test.json` +/// (`BerEncodedPadding`, `InvalidAsnInPadding`, `ModifiedPadding`, `WrongHash`, `InvalidPadding`, +/// `ShortPadding`, `NoHash`), and its one `MissingNull` "acceptable" case. +/// +/// A `digest` that is not `H::OUTPUT_LEN` bytes verifies nothing, whatever `em` holds. +pub fn emsa_pkcs1_v1_5_verify_from_hash( + digest: &[u8], + em: &[u8; K_LEN], +) -> bool { + if digest.len() != H::OUTPUT_LEN { + return false; + } + if em[0] != 0x00 || em[1] != 0x01 { + return false; + } + let mut i = 2; + while i < K_LEN && em[i] == 0xff { + i += 1; + } + // Mutating this `- 2` to `+ 2` or `/ 2` is an accepted equivalent, not a gap, for every + // concrete `(H, K_LEN)` this crate actually instantiates: `decode_digest_info` requires `T` + // to exactly fill whatever remains of `em` after the separator (no trailing garbage, RFC 8017 + // §9.2 note 1's structure, which `decode_digest_info` enforces), which pins `i` to one specific value + // for a genuine, hash-matching `DigestInfo` -- the same value regardless of how `ps_len` is + // computed from it, since `ps_len` is used only for the `< 8` comparison immediately below, + // and that real value of `i` is always thousands of bits' worth of padding away from the + // boundary where an off-by-a-constant miscalculation could flip the comparison's answer. + let ps_len = i - 2; + if ps_len < 8 || i >= K_LEN || em[i] != 0x00 { + return false; + } + + decode_digest_info::(&em[i + 1..], digest) +} + +#[cfg(test)] +mod tests { + //! `digest_info` is crate-private (only [`emsa_pkcs1_v1_5_encode_from_hash`] needs it + //! directly), so it is exercised here rather than from `tests/` -- the same "high-risk code + //! that cannot be reached through the public API" exception `rsa_core`'s tests use, though + //! `digest_info` itself is not high-risk so much as inconvenient to reach any other way. The + //! expected DER prefixes are RFC 8017 §9.2 note 1's own literal byte strings for + //! SHA-256/384/512. + + use super::*; + use bouncycastle_core::traits::HashOneShot; + use bouncycastle_sha2::{SHA256, SHA384, SHA512}; + + /// The whole EMSA-PKCS1-V1_5-ENCODE over a message, SHA-256: step 1 here, the rest in + /// [`emsa_pkcs1_v1_5_encode_from_hash`] -- what `rsassa_pkcs1_v1_5::sign` does, restated + /// locally so these tests can speak in terms of messages. + fn encode(message: &[u8]) -> [u8; K_LEN] { + let mut digest = [0u8; 32]; + SHA256::hash_out(message, &mut digest); + emsa_pkcs1_v1_5_encode_from_hash::(&digest).unwrap() + } + + /// [`encode`]'s verification counterpart, SHA-256. + fn verify(message: &[u8], em: &[u8; K_LEN]) -> bool { + let mut digest = [0u8; 32]; + SHA256::hash_out(message, &mut digest); + emsa_pkcs1_v1_5_verify_from_hash::(&digest, em) + } + + #[test] + fn digest_info_matches_rfc8017_sha256_prefix() { + let digest = [0xabu8; 32]; + let mut buf = [0u8; MAX_T_LEN]; + let t_len = digest_info::(&digest, &mut buf); + assert_eq!(t_len, 51); + let t = &buf[..51]; + let mut expected = [0u8; 51]; + expected[..19].copy_from_slice(&[ + 0x30, 0x31, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, + 0x01, 0x05, 0x00, 0x04, 0x20, + ]); + expected[19..].copy_from_slice(&digest); + assert_eq!(t, expected); + } + + #[test] + fn digest_info_matches_rfc8017_sha384_prefix() { + let digest = [0xcdu8; 48]; + let mut buf = [0u8; MAX_T_LEN]; + let t_len = digest_info::(&digest, &mut buf); + assert_eq!(t_len, 67); + let t = &buf[..67]; + let mut expected = [0u8; 67]; + expected[..19].copy_from_slice(&[ + 0x30, 0x41, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, + 0x02, 0x05, 0x00, 0x04, 0x30, + ]); + expected[19..].copy_from_slice(&digest); + assert_eq!(t, expected); + } + + #[test] + fn digest_info_matches_rfc8017_sha512_prefix() { + let digest = [0xefu8; 64]; + let mut buf = [0u8; MAX_T_LEN]; + let t_len = digest_info::(&digest, &mut buf); + assert_eq!(t_len, 83); + let t = &buf[..83]; + let mut expected = [0u8; 83]; + expected[..19].copy_from_slice(&[ + 0x30, 0x51, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, + 0x03, 0x05, 0x00, 0x04, 0x40, + ]); + expected[19..].copy_from_slice(&digest); + assert_eq!(t, expected); + } + + #[test] + fn encode_layout_is_00_01_ff_dot_dot_dot_00_t() { + let em = encode::<256>(b"hello"); + assert_eq!(em[0], 0x00); + assert_eq!(em[1], 0x01); + assert!(em[2..256 - 51 - 1].iter().all(|&b| b == 0xff)); + assert_eq!(em[256 - 51 - 1], 0x00); + assert_eq!(&em[256 - 51..256 - 51 + 19][..2], &[0x30, 0x31]); + } + + #[test] + fn encode_is_deterministic() { + let a = encode::<256>(b"same message"); + let b = encode::<256>(b"same message"); + assert_eq!(a, b); + } + + #[test] + fn encode_differs_for_different_messages() { + let a = encode::<256>(b"message one"); + let b = encode::<256>(b"message two"); + assert_ne!(a, b); + } + + #[test] + fn verify_accepts_what_encode_produces() { + let em = encode::<256>(b"hello"); + assert!(verify::<256>(b"hello", &em)); + } + + #[test] + fn verify_rejects_wrong_message() { + let em = encode::<256>(b"hello"); + assert!(!verify::<256>(b"goodbye", &em)); + } + + /// The `MissingNull` case Wycheproof's `rsa_signature_2048_sha256_test.json` marks + /// "acceptable": a `DigestInfo` whose `AlgorithmIdentifier` omits the `NULL` parameters this + /// crate's own [`emsa_pkcs1_v1_5_encode_from_hash`] always includes. + #[test] + fn verify_accepts_digest_info_with_null_parameters_absent() { + let mut digest = [0u8; 32]; + SHA256::hash_out(b"hello", &mut digest); + let oid = ::OID_DER; // 11 bytes: 06 09 <9-byte OID> + // T without "05 00": 30 30 04 20 , i.e. 2 bytes + // shorter than digest_info's own (NULL-including) T for the same hash. + let mut t = [0u8; 49]; + t[0] = 0x30; + t[1] = 47; + t[2] = 0x30; + t[3] = oid.len() as u8; + t[4..4 + oid.len()].copy_from_slice(oid); + let mut i = 4 + oid.len(); + t[i] = 0x04; + t[i + 1] = 32; + i += 2; + t[i..i + 32].copy_from_slice(&digest); + + let mut em = [0xffu8; 256]; + em[0] = 0x00; + em[1] = 0x01; + em[256 - 49 - 1] = 0x00; + em[256 - 49..].copy_from_slice(&t); + + assert!(verify::<256>(b"hello", &em)); + } + + /// Wycheproof's `BerEncodedPadding`: a `DigestInfo` length re-encoded in BER long form (top + /// bit set) rather than DER's required single-byte short form -- must be rejected outright, + /// since accepting any non-canonical length encoding is exactly the class of leniency + /// Bleichenbacher-style forgeries exploit, regardless of what value it happens to encode. + #[test] + fn verify_rejects_ber_long_form_length() { + let mut em = encode::<256>(b"hello"); + let t_start = 256 - 51; + assert_eq!(em[t_start], 0x30); + assert_eq!(em[t_start + 1], 49); // outer_len + em[t_start + 1] |= 0x80; + assert!(!verify::<256>(b"hello", &em)); + } + + /// Wycheproof's `InvalidAsnInPadding`: a `DigestInfo` length off by one from the true value. + #[test] + fn verify_rejects_wrong_der_length() { + let mut em = encode::<256>(b"hello"); + let t_start = 256 - 51; + em[t_start + 1] += 1; + assert!(!verify::<256>(b"hello", &em)); + } + + /// Wycheproof's `ModifiedPadding` ("appending 0's to digestInfo"): two extra zero bytes appended + /// after an otherwise-valid `DigestInfo`, with `PS` shrunk by two bytes to keep `EM`'s total + /// length fixed. A check that only confirms `EM` *starts with* the right bytes would miss + /// this; requiring every byte of `T` to be accounted for by the parse does not. + #[test] + fn verify_rejects_trailing_garbage_after_digest_info() { + let good = encode::<256>(b"hello"); + let mut em = [0xffu8; 256]; + em[0] = 0x00; + em[1] = 0x01; + em[256 - 51 - 2 - 1] = 0x00; // PS is 2 bytes shorter than the valid encoding's. + em[256 - 51 - 2..256 - 2].copy_from_slice(&good[256 - 51..]); // the valid T, unmodified. + em[256 - 2..].copy_from_slice(&[0x00, 0x00]); // two bytes appended after it. + assert!(!verify::<256>(b"hello", &em)); + } + + /// Wycheproof's `ShortPadding`: fewer than the required 8 `0xff` bytes. + #[test] + fn verify_rejects_short_padding() { + let mut em = [0u8; 256]; + em[0] = 0x00; + em[1] = 0x01; + em[2] = 0x00; // PS has length 0, not >= 8 + assert!(!verify::<256>(b"hello", &em)); + } + + /// Wycheproof's `WrongHash`: the OID in the padding names a different hash than the one used + /// to verify. + #[test] + fn verify_rejects_wrong_hash_oid() { + let mut em = encode::<256>(b"hello"); + let t_start = 256 - 51; + em[t_start + 4] ^= 0xff; // flip a byte inside the OID + assert!(!verify::<256>(b"hello", &em)); + } + + /// A crafted `EM` whose `DigestInfo` claims an `AlgorithmIdentifier` length long enough to run + /// past the end of the (very short, in this construction) remaining buffer. `decode_digest_info` + /// must reject this cleanly via its `inner_end > t.len()` check rather than let a + /// later, unguarded slice (`t[pos..pos + oid.len()]`) index past the real buffer and panic: + /// `pos + oid.len()` is fixed (4 + 11 = 15 for SHA-256) and does not itself depend on the + /// claimed length, so nothing downstream catches an inflated `inner_end` before that slice + /// runs -- this early check is the one thing standing between a malformed signature and a + /// crash, not merely a spec-conformance nicety. RSA verification exists to be run on + /// adversarial input, so a signature that panics the verifier is a real (if effortful to find, + /// since the attacker only controls `s`, not `s^e mod n` directly) denial-of-service vector. + #[test] + fn verify_rejects_digest_info_length_that_would_overrun_the_buffer_instead_of_panicking() { + let mut em = [0xffu8; 256]; + em[0] = 0x00; + em[1] = 0x01; + em[251] = 0x00; // separator; PS is em[2..251], 249 bytes, comfortably >= 8 + // T = em[252..256], only 4 bytes: 30 02 30 64 -- an AlgorithmIdentifier claiming 100 + // (0x64) content bytes where only 0 remain. + em[252] = 0x30; + em[253] = 0x02; + em[254] = 0x30; + em[255] = 0x64; + assert!(!verify::<256>(b"hello", &em)); + } + + /// RFC 8017 §9.2 step 4: "The length of PS will be at least 8 octets" -- exactly 8 must be + /// accepted, not just "8 or more" in the abstract. `K_LEN = 62` is the minimum modulus width + /// this hash's `DigestInfo` (`T_LEN = 51`) allows at all (the `K_LEN >= T_LEN + 11` bound + /// [`emsa_pkcs1_v1_5_encode_from_hash`]'s docs describe), which pins `PS` to exactly 8 bytes -- the one + /// pairing that distinguishes "`< 8`" from "`<= 8`" or "`== 8`" as the rejection condition. + #[test] + fn verify_accepts_the_minimum_8_byte_ps_boundary() { + let em = encode::<62>(b"hello"); + assert_eq!(em[2..2 + 8], [0xff; 8], "this construction must exercise ps_len == 8 exactly"); + assert!(verify::<62>(b"hello", &em)); + } + + /// RFC 8017 §9.2 step 5: `EM`'s block type byte (`em[1]`) must be exactly `0x01`. `em[0]` + /// stays correct (`0x00`) so this exercises only the block-type half of the check. + #[test] + fn verify_rejects_wrong_block_type() { + let mut em = encode::<256>(b"hello"); + em[1] = 0x02; + assert!(!verify::<256>(b"hello", &em)); + } + + /// RFC 8017 §9.2 step 5: `EM`'s leading byte (`em[0]`) must be exactly `0x00`. `em[1]` stays + /// correct (`0x01`) so this exercises only the leading-byte half of the check. + #[test] + fn verify_rejects_wrong_leading_byte() { + let mut em = encode::<256>(b"hello"); + em[0] = 0x01; + assert!(!verify::<256>(b"hello", &em)); + } +} diff --git a/crypto/rsa/src/emsa_pss.rs b/crypto/rsa/src/emsa_pss.rs new file mode 100644 index 000000000..396d60323 --- /dev/null +++ b/crypto/rsa/src/emsa_pss.rs @@ -0,0 +1,387 @@ +//! EMSA-PSS (RFC 8017 §9.1): probabilistic signature encoding, once over the hash `H` and the +//! parameters `P` ([`PssParams`]): the mask generation function (MGF1 over a hash, or a SHAKE +//! used natively per RFC 8702 §3.2.1, "the SHAKEs MUST be used natively as the MGF, instead of +//! the MGF1 algorithm") and the salt length. +//! +//! # The `8 * K_LEN - emBits == 1` simplification +//! +//! RFC 8017 encodes into `emLen = ceil(emBits / 8)` octets, where `emBits = modBits - 1`, and +//! steps 11/9 clear the leftmost `8 * emLen - emBits` bits of the encoded message's first octet +//! so that `OS2IP(EM) < 2^emBits <= n`. Every modulus size this crate offers is a whole number of +//! 64-bit limbs, and a key's modulus has exactly its size's bit length: the constructors +//! [`RsaPublicComponents::new`](crate::keys::RsaPublicComponents::new) and +//! [`RsaPrivateComponents::from_crt_components`](crate::keys::RsaPrivateComponents::from_crt_components), +//! which every key and every decoding goes through, refuse a modulus whose top bit is clear. So +//! `modBits = 8 * K_LEN` and `emLen = K_LEN`, which makes +//! `8 * K_LEN - emBits = 8 * K_LEN - (8 * K_LEN - 1) = 1` for every key there is, and this +//! module hard-codes "clear the top bit of the first octet" instead of threading a generic +//! bit-count parameter through for a case that cannot arise. + +use crate::emsa_pkcs1_v1_5::HASH_LEN_ERROR; +use crate::mgf1::MAX_HASH_LEN; +use crate::rsassa_pss::PssParams; +use bouncycastle_core::errors::SignatureError; +use bouncycastle_core::traits::{HashAlgParams, HashOneShot}; + +/// What the encoding returns for a salt that is not the parameters' `sLen`. +pub(crate) const SALT_LEN_ERROR: SignatureError = + SignatureError::LengthError("the salt must be the parameters' salt length"); + +/// EMSA-PSS-ENCODE (RFC 8017 §9.1.1) from the message hash `m_hash` (step 2's `mHash`, +/// `H::OUTPUT_LEN` bytes) and the salt (`sLen = P::SALT_LEN` bytes), with `P`'s mask, into the +/// `K_LEN`-byte `EM`. The lengths every other width derives from are `K_LEN` and the hash's: +/// `DB` is `K_LEN - hLen - 1` bytes, `M'` is `8 + hLen + sLen`. +/// +/// An `m_hash` that is not `H::OUTPUT_LEN` bytes is [`HASH_LEN_ERROR`] and a `salt` that is not +/// `P::SALT_LEN` bytes is [`SALT_LEN_ERROR`]: the caller's slices, checked in every build. +/// Step 3's error ("encoding error", `emLen < hLen + sLen + 2`) is +/// [`SignatureError::EncodingError`]: a pairing can be named whose modulus is too short for its +/// hash and salt (RSA-1024 with SHA-512 and a 64-byte salt needs 130 bytes of 128). +pub fn emsa_pss_encode_from_hash( + m_hash: &[u8], + salt: &[u8], +) -> Result<[u8; K_LEN], SignatureError> +where + H: HashOneShot + HashAlgParams, + P: PssParams, +{ + let h_len = H::OUTPUT_LEN; + let s_len = P::SALT_LEN; + if m_hash.len() != h_len { + return Err(HASH_LEN_ERROR); + } + if salt.len() != s_len { + return Err(SALT_LEN_ERROR); + } + // Step 3: "If emLen < hLen + sLen + 2, output "encoding error" and stop." + if K_LEN < h_len + s_len + 2 { + return Err(SignatureError::EncodingError( + "the modulus is too short for this hash and salt length", + )); + } + let db_len = K_LEN - h_len - 1; + + // Steps 5-6: M' = 8 zero octets || mHash || salt; H = Hash(M'). + let mut m_prime = [0u8; 8 + 2 * MAX_HASH_LEN]; + m_prime[8..8 + h_len].copy_from_slice(m_hash); + m_prime[8 + h_len..8 + h_len + s_len].copy_from_slice(salt); + let mut h = [0u8; MAX_HASH_LEN]; + H::hash_out(&m_prime[..8 + h_len + s_len], &mut h[..h_len]); + + // Steps 7-8: DB = PS || 0x01 || salt (PS is all-zero, already the buffer's initial value). + let mut db = [0u8; K_LEN]; + db[db_len - s_len - 1] = 0x01; + db[db_len - s_len..db_len].copy_from_slice(salt); + + // Steps 9-11: maskedDB = DB xor MGF(H, DB_LEN), the parameters' mask, then clear the top + // bit (see module docs). + let mut db_mask = [0u8; K_LEN]; + P::mask(&h[..h_len], &mut db_mask[..db_len]); + let mut em = [0u8; K_LEN]; + for i in 0..db_len { + em[i] = db[i] ^ db_mask[i]; + } + em[0] &= 0x7f; + + // Step 12: EM = maskedDB || H || 0xbc. + em[db_len..db_len + h_len].copy_from_slice(&h[..h_len]); + em[K_LEN - 1] = 0xbc; + Ok(em) +} + +/// EMSA-PSS-VERIFY (RFC 8017 §9.1.2) of the `K_LEN`-byte `em` against the message hash +/// `m_hash` (step 2's `mHash`), with `sLen = P::SALT_LEN` and `P`'s mask. An `m_hash` that is +/// not `H::OUTPUT_LEN` bytes is consistent with nothing. +pub fn emsa_pss_verify_from_hash(m_hash: &[u8], em: &[u8; K_LEN]) -> bool +where + H: HashOneShot + HashAlgParams, + P: PssParams, +{ + let h_len = H::OUTPUT_LEN; + let s_len = P::SALT_LEN; + if m_hash.len() != h_len { + return false; + } + // Step 3: emLen < hLen + sLen + 2 is "inconsistent"; a constant of the pairing. + if K_LEN < h_len + s_len + 2 { + return false; + } + let db_len = K_LEN - h_len - 1; + + // Step 4. + if em[K_LEN - 1] != 0xbc { + return false; + } + // Step 6 (checked directly on `em[0]`, which is maskedDB's own leftmost octet). + if em[0] & 0x80 != 0 { + return false; + } + // Step 5. + let masked_db = &em[..db_len]; + let h = &em[db_len..db_len + h_len]; + + // Steps 7-9. + let mut db = [0u8; K_LEN]; + P::mask(h, &mut db[..db_len]); + for i in 0..db_len { + db[i] ^= masked_db[i]; + } + db[0] &= 0x7f; + + // Step 10. + let ps_len = db_len - s_len - 1; + if db[..ps_len].iter().any(|&b| b != 0) || db[ps_len] != 0x01 { + return false; + } + // Step 11. + let salt = &db[db_len - s_len..db_len]; + + // Steps 12-14 (step 2's mHash is the caller's `m_hash`). + let mut m_prime = [0u8; 8 + 2 * MAX_HASH_LEN]; + m_prime[8..8 + h_len].copy_from_slice(m_hash); + m_prime[8 + h_len..8 + h_len + s_len].copy_from_slice(salt); + let mut h_prime = [0u8; MAX_HASH_LEN]; + H::hash_out(&m_prime[..8 + h_len + s_len], &mut h_prime[..h_len]); + h == &h_prime[..h_len] +} + +#[cfg(test)] +mod tests { + //! `emsa_pss_encode_from_hash`/`emsa_pss_verify_from_hash` are crate-private (only + //! [`crate::rsassa_pss`] needs them), so they are exercised here rather than from `tests/` -- + //! the same "high-risk code that cannot be reached through the public API" exception + //! `rsa_core`'s tests use. The KAT is a direct Python transliteration of RFC 8017 SS9.1.1's + //! own steps (not from recall), reusing this crate's own `mgf1` reference values (`mgf1.rs`'s + //! own tests) for the mask. The `encode`/`verify` helpers below add step 2's `mHash = Hash(M)` + //! back on top, so the tests can speak in terms of messages. + + use super::*; + use crate::rsassa_pss::Conventional; + use bouncycastle_sha2::SHA256; + use bouncycastle_sha3::SHAKE128; + + const SALT: [u8; 32] = [ + 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, + 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, + 0x1e, 0x1f, + ]; + const EXPECTED_EM: [u8; 256] = [ + 0x62, 0x2c, 0x85, 0xcc, 0xb1, 0xe5, 0x9b, 0xb7, 0x46, 0x99, 0x27, 0xba, 0xab, 0xa2, 0x37, + 0x72, 0xd6, 0x77, 0xe5, 0xd9, 0x2d, 0x4c, 0x40, 0xc8, 0x08, 0x2c, 0x00, 0xbc, 0xed, 0x77, + 0x17, 0x75, 0x34, 0x88, 0x46, 0xd1, 0x8a, 0xa9, 0x77, 0x6e, 0xd8, 0x4e, 0xa4, 0x9f, 0x07, + 0x23, 0xd6, 0x60, 0xc7, 0xa3, 0x86, 0x1f, 0x24, 0x6b, 0x3a, 0x79, 0xec, 0x72, 0x9f, 0x33, + 0x4f, 0x8a, 0x10, 0x03, 0xdc, 0x56, 0x35, 0x4e, 0xef, 0x23, 0x05, 0xd7, 0x4b, 0x52, 0xde, + 0x1e, 0x26, 0x74, 0xaf, 0x4e, 0xd1, 0xdf, 0xd5, 0x75, 0x17, 0x18, 0x23, 0x4b, 0xd8, 0x67, + 0xd3, 0xc7, 0x3e, 0x57, 0xc7, 0xf1, 0xf7, 0xae, 0xa6, 0xf6, 0xa7, 0xa4, 0xb1, 0x87, 0xc0, + 0xde, 0x14, 0xa8, 0x5b, 0x64, 0x7c, 0x69, 0xe1, 0x3c, 0x81, 0xc1, 0x09, 0x23, 0xd3, 0x24, + 0xad, 0xbb, 0x71, 0xe5, 0xdf, 0x09, 0x93, 0x21, 0x4c, 0x0f, 0x7d, 0x0d, 0x1d, 0x4f, 0x54, + 0x27, 0xd3, 0xb9, 0x6e, 0xb6, 0x7d, 0x43, 0x11, 0x1c, 0x62, 0xd7, 0xa3, 0x2e, 0xcf, 0x8c, + 0x83, 0x4b, 0x2d, 0xe0, 0xe2, 0x65, 0x1f, 0x91, 0x71, 0x67, 0x6c, 0xab, 0xbb, 0x0b, 0x62, + 0x11, 0xe0, 0x43, 0xf6, 0xe6, 0xe7, 0xcc, 0xf9, 0x41, 0x85, 0xb5, 0xc1, 0x76, 0x55, 0xd1, + 0xe6, 0xd2, 0x87, 0xc5, 0x2a, 0xcf, 0x83, 0x90, 0x42, 0x5a, 0xe2, 0xf7, 0x9b, 0xca, 0x09, + 0x2c, 0x3f, 0x2a, 0xb6, 0x1d, 0x59, 0xce, 0xe0, 0x3b, 0x94, 0x9e, 0x81, 0x6d, 0xed, 0x08, + 0x88, 0xc4, 0xc2, 0xa2, 0xab, 0x47, 0x3b, 0x48, 0x1d, 0xea, 0xc1, 0xe0, 0x43, 0x09, 0x46, + 0xab, 0x31, 0x4e, 0x5e, 0x81, 0x09, 0x3b, 0x00, 0xda, 0xe0, 0xc4, 0x35, 0x58, 0x4e, 0xb8, + 0xf6, 0xc7, 0xda, 0x8c, 0xf2, 0xba, 0xb0, 0xb1, 0x04, 0xff, 0x46, 0xbb, 0x51, 0x84, 0xa3, + 0xbc, + ]; + + fn m_hash(message: &[u8]) -> [u8; 32] { + let mut m_hash = [0u8; 32]; + SHA256::hash_out(message, &mut m_hash); + m_hash + } + + fn encode(message: &[u8], salt: &[u8; 32]) -> [u8; 256] { + emsa_pss_encode_from_hash::(&m_hash(message), salt).unwrap() + } + + fn verify(message: &[u8], em: &[u8; 256]) -> bool { + emsa_pss_verify_from_hash::(&m_hash(message), em) + } + + #[test] + fn encode_matches_python_kat() { + assert_eq!(encode(b"hello", &SALT), EXPECTED_EM); + } + + #[test] + fn verify_accepts_the_kat() { + assert!(verify(b"hello", &EXPECTED_EM)); + } + + #[test] + fn verify_rejects_wrong_message() { + assert!(!verify(b"goodbye", &EXPECTED_EM)); + } + + #[test] + fn different_salts_give_different_but_both_valid_encodings() { + let salt_b: [u8; 32] = { + let mut s = SALT; + s[0] ^= 0xff; + s + }; + let em_a = encode(b"hello", &SALT); + let em_b = encode(b"hello", &salt_b); + assert_ne!(em_a, em_b, "PSS is randomized: different salts must give different EM"); + assert!(verify(b"hello", &em_a)); + assert!(verify(b"hello", &em_b)); + } + + /// RFC 8017 SS9.1.2 step 4: the trailer byte must be `0xbc`. + #[test] + fn verify_rejects_wrong_trailer_byte() { + let mut em = EXPECTED_EM; + em[255] = 0xbd; + assert!(!verify(b"hello", &em)); + } + + /// RFC 8017 SS9.1.2 step 6: the leftmost bit of `maskedDB`'s first octet must already be 0 + /// (see the module docs on why this crate always needs exactly one bit clear). + #[test] + fn verify_rejects_top_bit_set() { + let mut em = EXPECTED_EM; + em[0] |= 0x80; + assert!(!verify(b"hello", &em)); + } + + /// RFC 8017 SS9.1.2 step 10: every byte of `PS` must be zero. + #[test] + fn verify_rejects_nonzero_padding() { + let mut em = EXPECTED_EM; + // Corrupt a byte inside the (unmasked) PS region by flipping the corresponding bit of the + // masked byte directly -- em[0] is PS's first (masked) byte after the top-bit clear. + em[0] ^= 0x40; + assert!(!verify(b"hello", &em)); + } + + /// RFC 8017 SS9.1.2 step 10: the octet right before the salt must be exactly `0x01`. + #[test] + fn verify_rejects_wrong_separator_byte() { + // The byte at DB position (DB_LEN - S_LEN - 1) = 223 - 32 - 1 = 190, masked. Flipping its + // least-significant bit changes the unmasked separator from 0x01 to 0x00. + let mut em = EXPECTED_EM; + em[190] ^= 0x01; + assert!(!verify(b"hello", &em)); + } + + mod shake { + + //! The SHAKE parameters: the KAT is a direct Python transliteration of RFC 8017 + //! SS9.1.1's own steps with RFC 8702 SS3.2.1's native-SHAKE mask substituted for MGF1 (not from + //! recall), using `hashlib.shake_128`. The `encode`/`verify` helpers below add step 2's + //! `mHash = Hash(M)` back on top, so the tests can speak in terms of messages. + + use super::*; + + const SALT: [u8; 32] = [ + 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, + 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, + 0x1c, 0x1d, 0x1e, 0x1f, + ]; + + fn m_hash(message: &[u8]) -> [u8; 32] { + let mut m_hash = [0u8; 32]; + SHAKE128::hash_out(message, &mut m_hash); + m_hash + } + + fn encode(message: &[u8], salt: &[u8; 32]) -> [u8; 256] { + emsa_pss_encode_from_hash::(&m_hash(message), salt) + .unwrap() + } + + fn verify(message: &[u8], em: &[u8; 256]) -> bool { + emsa_pss_verify_from_hash::(&m_hash(message), em) + } + + #[test] + fn encode_matches_python_kat() { + // hashlib.shake_128, following EMSA-PSS-ENCODE (RFC 8017 SS9.1.1) with the SHAKE-native + // mask of RFC 8702 SS3.2.1 substituted for MGF1 -- not from recall. + let expected_em: [u8; 256] = [ + 0x44, 0x7f, 0x52, 0xb3, 0xea, 0xb3, 0x57, 0x7d, 0xe7, 0x42, 0xb3, 0x95, 0xf6, 0x85, + 0xc1, 0x72, 0x43, 0xf1, 0xe1, 0x00, 0xca, 0x98, 0x51, 0x95, 0x9b, 0x49, 0x94, 0x8c, + 0x34, 0xe8, 0x80, 0x43, 0xb3, 0x7a, 0xe6, 0xf9, 0x58, 0x55, 0x1c, 0x24, 0x67, 0x2c, + 0x5c, 0x67, 0x89, 0xd6, 0x70, 0xd9, 0x01, 0x5c, 0x21, 0x06, 0xdf, 0xdf, 0x2c, 0x99, + 0x36, 0x25, 0xb7, 0x42, 0x0e, 0xcb, 0x9d, 0x06, 0xac, 0xe7, 0x28, 0x81, 0x01, 0xe3, + 0x37, 0xb0, 0x20, 0x84, 0x01, 0x39, 0x2a, 0x9b, 0x5c, 0xf7, 0x05, 0xef, 0x4c, 0xb2, + 0x41, 0xc6, 0x33, 0x88, 0x2f, 0x45, 0x8a, 0x70, 0xfc, 0xe2, 0xb9, 0xd1, 0xcb, 0x0a, + 0xe7, 0x8d, 0x94, 0xfa, 0x99, 0xf6, 0x28, 0xbc, 0x25, 0x38, 0x11, 0xc9, 0xfa, 0xfd, + 0xd0, 0x3e, 0x51, 0x0f, 0xc9, 0xd1, 0x1f, 0x2a, 0x21, 0x08, 0x26, 0xe8, 0xb3, 0x5a, + 0xc7, 0x08, 0xbf, 0xfe, 0xd9, 0x88, 0xde, 0xad, 0x26, 0xec, 0x86, 0x9c, 0x76, 0xb9, + 0x0e, 0xca, 0x0d, 0xfe, 0xad, 0x99, 0x16, 0x57, 0x45, 0x7f, 0x9f, 0x94, 0x4b, 0x8e, + 0x3f, 0xfb, 0xff, 0x11, 0x95, 0xf7, 0x70, 0x1b, 0x2c, 0xbc, 0xb4, 0xbd, 0x6c, 0x2f, + 0xe7, 0x10, 0xad, 0x21, 0xaa, 0xfc, 0x72, 0xfa, 0xd1, 0x79, 0x98, 0xcc, 0x1c, 0xfc, + 0x7c, 0x57, 0xca, 0xf9, 0x28, 0x54, 0xd5, 0xbf, 0x9c, 0x19, 0x6e, 0xea, 0x48, 0x46, + 0xdb, 0x40, 0xcf, 0x69, 0x12, 0x19, 0xfe, 0xe9, 0x0c, 0x2b, 0x5e, 0xbc, 0xe1, 0x23, + 0x28, 0x6b, 0xe8, 0x99, 0x00, 0x35, 0x0a, 0x45, 0x48, 0x06, 0xcd, 0xe0, 0x56, 0xf8, + 0xe6, 0x24, 0x68, 0x9f, 0x87, 0x9b, 0x7a, 0xa5, 0x0e, 0x5c, 0x42, 0xd3, 0x29, 0xab, + 0xe0, 0xa3, 0x21, 0xc7, 0xe2, 0x11, 0xfb, 0x27, 0x45, 0xbc, 0x20, 0x21, 0x41, 0xa6, + 0xd6, 0xc1, 0xd0, 0xbc, + ]; + assert_eq!(encode(b"hello", &SALT), expected_em); + } + + #[test] + fn round_trip_own_encoding() { + let em = encode(b"hello", &SALT); + assert!(verify(b"hello", &em)); + } + + #[test] + fn verify_rejects_wrong_message() { + let em = encode(b"hello", &SALT); + assert!(!verify(b"goodbye", &em)); + } + + #[test] + fn different_salts_give_different_but_both_valid_encodings() { + let salt_b: [u8; 32] = { + let mut s = SALT; + s[0] ^= 0xff; + s + }; + let em_a = encode(b"hello", &SALT); + let em_b = encode(b"hello", &salt_b); + assert_ne!(em_a, em_b, "PSS is randomized: different salts must give different EM"); + assert!(verify(b"hello", &em_a)); + assert!(verify(b"hello", &em_b)); + } + + /// RFC 8017 §9.1.2 step 4: the trailer byte must be `0xbc`. + #[test] + fn verify_rejects_wrong_trailer_byte() { + let mut em = encode(b"hello", &SALT); + em[255] = 0xbd; + assert!(!verify(b"hello", &em)); + } + + /// RFC 8017 §9.1.2 step 6: the leftmost bit of `maskedDB`'s first octet must already be 0. + #[test] + fn verify_rejects_top_bit_set() { + let mut em = encode(b"hello", &SALT); + em[0] |= 0x80; + assert!(!verify(b"hello", &em)); + } + + /// RFC 8017 §9.1.2 step 10: every byte of `PS` must be zero. + #[test] + fn verify_rejects_nonzero_padding() { + let mut em = encode(b"hello", &SALT); + em[0] ^= 0x40; + assert!(!verify(b"hello", &em)); + } + + /// RFC 8017 §9.1.2 step 10: the octet right before the salt must be exactly `0x01`. + #[test] + fn verify_rejects_wrong_separator_byte() { + // The byte at DB position (DB_LEN - S_LEN - 1) = 223 - 32 - 1 = 190, masked. Flipping its + // least-significant bit changes the unmasked separator from 0x01 to 0x00. + let mut em = encode(b"hello", &SALT); + em[190] ^= 0x01; + assert!(!verify(b"hello", &em)); + } + } +} diff --git a/crypto/rsa/src/keygen.rs b/crypto/rsa/src/keygen.rs new file mode 100644 index 000000000..38fed50de --- /dev/null +++ b/crypto/rsa/src/keygen.rs @@ -0,0 +1,936 @@ +//! RSA key pair generation: FIPS 186-5 Appendix A.1.3, "Generation of Random Primes that are +//! Probably Prime", with Appendix B.3.1's Miller-Rabin test (behind Appendix B.7-style trial +//! division) and Appendix A.1.1's criteria on `e`, `p`, `q` and `d`, over this crate's fixed-width +//! limb arithmetic -- there is no arbitrary-precision integer type here, as in the rest of the +//! crate. Structured after BC Java's `org.bouncycastle.crypto.generators.RSAKeyPairGenerator` +//! (its candidate loop, small-factor sieve and `d` lower-bound check are what this follows), with +//! FIPS 186-5 as the reference for every step and cited inline. +//! +//! The sizes wire this up as `RsaSigningSize::keygen`, which the size markers' generators wrap: +//! `nlen` is fixed by the width, `e` by +//! [`PUBLIC_EXPONENT`], the Miller-Rabin round count by `RsaSigningSize::MR_ROUNDS` and the required +//! RNG strength by each size's row of SP 800-57 Part 1 Table 2. +//! +//! # What is and is not constant-time here +//! +//! Key generation is rejection sampling: how many candidates are drawn, and where each one is +//! rejected (a small factor, the `|p - q|` bound, a Miller-Rabin witness), is inherently +//! data-dependent, and the small-modulus arithmetic on a candidate -- its residues modulo the +//! trial-division primes and modulo `e`, the binary GCD and the one long division behind +//! `lcm(p - 1, q - 1)` -- uses ordinary variable-time integer operations. That is the same +//! position BC Java's `BigInteger`-based generator takes, for a one-off operation with no +//! attacker-supplied input. The secret-exponent work generation does do, `qInv = q^(p - 2) mod p`, +//! goes through [`crate::modexp::mod_pow`]'s constant-time ladder, the same one every signature +//! uses; and the `MontgomeryContext` built over each candidate is the constant-time construction +//! `rsa_core::rsasp1` builds over the secret primes on every signature. + +use crate::keys::{RsaPrivateComponents, RsaPublicComponents}; +use crate::modexp::{MontgomeryContext, check_widths, mod_pow, mul_mod, reduce_wide}; +use crate::rsa_core::{WipeStackBelowOnReturn, wipe_stack_below}; +use crate::size::{RsaSigningSize, RsaSize}; +use bouncycastle_core::errors::{RNGError, SignatureError}; +use bouncycastle_core::security_strength::SecurityStrength; +use bouncycastle_core::traits::RNG; +use bouncycastle_ec::montgomery; +use bouncycastle_ec::nat; +use bouncycastle_utils::secret::{Secret, zeroize_in_place}; +use core::num::NonZeroUsize; + +/// The public exponent every key pair this crate generates uses: `F4 = 2^16 + 1 = 65537`. +/// FIPS 186-5 Appendix A.1.1 criterion 1 asks for an odd `e` with `2^16 < e < 2^256`, "selected +/// prior to generating the primes"; this is the smallest such value and the near-universal choice +/// (it is what Wycheproof's and BC Java's test keys use). Its primality is what lets criterion +/// 2(a), `GCD(p - 1, e) = 1`, be checked as "`e` does not divide `p - 1`" (step 4.5 below). +pub const PUBLIC_EXPONENT: u64 = 65537; + +/// Trial-division bound: every prime below this is divided out of a candidate before the +/// Miller-Rabin test runs (FIPS 186-5 Appendix B.7, "if convenient, `c` may be divided by +/// composite numbers" -- the primes are bundled into `u64` products, as BC Java's +/// `Primes.hasAnySmallFactors` does). `2^10` is a round choice well inside Appendix B.8's +/// "typical" `10^3` to `10^5`; about 84% of odd candidates are caught here (the share of odd +/// integers with an odd prime factor below 1024, one minus the product of `1 - 1/p` over those +/// 171 primes, is 0.8387), sparing that many modular exponentiations. +pub const SMALL_PRIME_LIMIT: usize = 1024; + +/// `pi(1024)`: the number of primes below [`SMALL_PRIME_LIMIT`]. +const SMALL_PRIME_COUNT: usize = 172; + +/// The primes below [`SMALL_PRIME_LIMIT`], from a compile-time sieve of Eratosthenes (Appendix +/// B.8's sieve procedure, at its simplest). +const SMALL_PRIMES: [u16; SMALL_PRIME_COUNT] = small_primes(); + +const fn small_primes() -> [u16; SMALL_PRIME_COUNT] { + let mut composite = [false; SMALL_PRIME_LIMIT]; + let mut primes = [0u16; SMALL_PRIME_COUNT]; + let mut found = 0; + let mut i = 2; + while i < SMALL_PRIME_LIMIT { + if !composite[i] { + primes[found] = i as u16; + found += 1; + let mut j = i * i; + while j < SMALL_PRIME_LIMIT { + composite[j] = true; + j += i; + } + } + i += 1; + } + assert!(found == SMALL_PRIME_COUNT, "SMALL_PRIME_COUNT must be pi(SMALL_PRIME_LIMIT)"); + primes +} + +// ---- small-integer helpers over `[u64; N]` little-endian limbs ------------------------------ + +/// `a mod m` for a small modulus `m`, by schoolbook long division one limb at a time. +fn mod_u64(a: &[u64; N], m: u64) -> u64 { + let mut rem: u128 = 0; + for limb in a.iter().rev() { + rem = ((rem << 64) | u128::from(*limb)) % u128::from(m); + } + rem as u64 +} + +/// `a * k + add`, as `N` limbs plus the carry limb. +fn mul_u64_add(a: &[u64; N], k: u64, add: u64) -> ([u64; N], u64) { + let mut out = [0u64; N]; + let mut carry = u128::from(add); + for i in 0..N { + let t = u128::from(a[i]) * u128::from(k) + carry; + out[i] = t as u64; + carry = t >> 64; + } + (out, carry as u64) +} + +/// `(hi || a) / d` and the remainder, for `hi < d`, by schoolbook long division one limb at a +/// time; the quotient then fits in `N` limbs. +fn div_u64(hi: u64, a: &[u64; N], d: u64) -> ([u64; N], u64) { + debug_assert!(hi < d, "div_u64: the quotient must fit in N limbs"); + let mut quotient = [0u64; N]; + let mut rem = u128::from(hi); + for i in (0..N).rev() { + let cur = (rem << 64) | u128::from(a[i]); + quotient[i] = (cur / u128::from(d)) as u64; + rem = cur % u128::from(d); + } + (quotient, rem as u64) +} + +/// `r^-1 mod e` for `0 < r < e` with `GCD(r, e) = 1`, by the extended Euclidean algorithm of +/// FIPS 186-5 Appendix B.1 on single words. +fn inv_mod_u64(r: u64, e: u64) -> u64 { + debug_assert!(r != 0 && r < e); + // Invariant: t0 * r == r0 and t1 * r == r1 (mod e), with |t0|, |t1| <= e. + let (mut r0, mut r1) = (i128::from(e), i128::from(r)); + let (mut t0, mut t1) = (0i128, 1i128); + while r1 != 0 { + let quotient = r0 / r1; + (r0, r1) = (r1, r0 - quotient * r1); + (t0, t1) = (t1, t0 - quotient * t1); + } + debug_assert_eq!(r0, 1, "r and e must be coprime"); + t0.rem_euclid(i128::from(e)) as u64 +} + +/// `e^-1 mod m` for `m > 1` and an `e > 1` with `GCD(m, e) = 1`. +/// +/// FIPS 186-5 Appendix B.1 gives the extended Euclidean algorithm for reference and allows +/// "other algorithms that produce an equivalent result". Because `e` is one word, the +/// inverse comes without a multi-limb division: with `r = m mod e` and `k = -r^-1 mod e` (so +/// `k*m + 1 ≡ 0 mod e`), `d = (k*m + 1) / e` is an exact integer with `e*d = 1 + k*m ≡ 1 mod m`, +/// and `0 < d < m` since `0 < k < e`. The only multi-limb operations are one multiply by `k` and +/// one exact division by `e`. +fn inverse_of_e_mod(m: &[u64; N], e: u64) -> [u64; N] { + let r = mod_u64(m, e); + // `GCD(m, e) = 1` is the caller's invariant. `keygen` discards any `p` (or `q`) with + // `e | p - 1` at step 4.5, and `LCM(p - 1, q - 1)` then cannot be divisible by `e` either; + // a key's constructor has checked that `e` has an inverse modulo `p - 1` and `q - 1`. + debug_assert_ne!(r, 0, "e must not divide m"); + let k = e - inv_mod_u64(r, e); + let (lo, hi) = mul_u64_add(m, k, 1); + let (d, rem) = div_u64(hi, &lo, e); + debug_assert_eq!(rem, 0, "k*m + 1 is divisible by e by construction"); + d +} + +// ---- multi-limb helpers ---------------------------------------------------------------------- + +fn is_zero(a: &[u64; N]) -> bool { + nat::is_zero(a).to_bool() +} + +/// `a < b`. +fn lt(a: &[u64; N], b: &[u64; N]) -> bool { + nat::sub(a, b).1 == 1 +} + +fn trailing_zeros(a: &[u64; N]) -> u32 { + let mut count = 0; + for limb in a { + if *limb == 0 { + count += 64; + } else { + return count + limb.trailing_zeros(); + } + } + count +} + +fn leading_zeros(a: &[u64; N]) -> u32 { + let mut count = 0; + for limb in a.iter().rev() { + if *limb == 0 { + count += 64; + } else { + return count + limb.leading_zeros(); + } + } + count +} + +/// Clears every bit of `a` at position `bits` or above. +fn mask_to_bits(a: &mut [u64; N], bits: u32) { + for (i, limb) in a.iter_mut().enumerate() { + let lo = 64 * i as u32; + if bits <= lo { + *limb = 0; + } else if bits < lo + 64 { + *limb &= (1u64 << (bits - lo)) - 1; + } + } +} + +fn shr(a: &[u64; N], shift: u32) -> [u64; N] { + let mut out = [0u64; N]; + let limbs = (shift / 64) as usize; + let bits = shift % 64; + for i in 0..N.saturating_sub(limbs) { + let lo = a[i + limbs] >> bits; + let hi = if bits != 0 && i + limbs + 1 < N { a[i + limbs + 1] << (64 - bits) } else { 0 }; + out[i] = lo | hi; + } + out +} + +fn shl(a: &[u64; N], shift: u32) -> [u64; N] { + let mut out = [0u64; N]; + let limbs = (shift / 64) as usize; + let bits = shift % 64; + for i in limbs..N { + let lo = a[i - limbs] << bits; + let hi = if bits != 0 && i > limbs { a[i - limbs - 1] >> (64 - bits) } else { 0 }; + out[i] = lo | hi; + } + out +} + +/// `a - k` for a small `k <= a`. +fn sub_u64(a: &[u64; N], k: u64) -> [u64; N] { + let mut k_limbs = [0u64; N]; + k_limbs[0] = k; + let (diff, borrow) = nat::sub(a, &k_limbs); + debug_assert_eq!(borrow, 0); + diff +} + +/// `GCD(a, b)` by Stein's binary algorithm; variable time (see the module docs). +fn gcd(a: &[u64; N], b: &[u64; N]) -> [u64; N] { + if is_zero(a) { + return *b; + } + if is_zero(b) { + return *a; + } + let common_twos = trailing_zeros(a).min(trailing_zeros(b)); + let mut a = shr(a, trailing_zeros(a)); + let mut b = shr(b, trailing_zeros(b)); + loop { + // Both odd here, so `a - b` is even (or zero); dividing its powers of two out keeps the + // invariant, and the larger operand strictly shrinks each round. + if lt(&a, &b) { + core::mem::swap(&mut a, &mut b); + } + let (diff, _) = nat::sub(&a, &b); + if is_zero(&diff) { + break; + } + a = shr(&diff, trailing_zeros(&diff)); + } + shl(&b, common_twos) +} + +/// `a / d` for `d != 0`, by bit-serial schoolbook long division; variable time (see the module +/// docs). Used once per key pair, for `(q - 1) / GCD(p - 1, q - 1)`. +fn div(a: &[u64; N], d: &[u64; N]) -> [u64; N] { + debug_assert!(!is_zero(d)); + let mut rem = [0u64; N]; + let mut quotient = [0u64; N]; + for limb in (0..N).rev() { + for bit in (0..64).rev() { + // rem = 2*rem + next bit; rem < d before, so the true value is < 2d and one + // conditional subtraction restores rem < d. The bit that leaves the top limb is the + // "carry" case, in which the subtraction is always due. + let carry = rem[N - 1] >> 63; + rem = shl(&rem, 1); + rem[0] |= (a[limb] >> bit) & 1; + let (diff, borrow) = nat::sub(&rem, d); + if carry == 1 || borrow == 0 { + rem = diff; + quotient[limb] |= 1 << bit; + } + } + } + quotient +} + +/// Fills the whole of `out` from `rng`, for every draw this crate makes. `RNG::next_bytes_out` +/// returns the number of bytes it wrote, and a count short of the buffer is the RNG failing to +/// deliver: an error, as its own error is, with `out` wiped either way, since what it holds +/// then is part of a prime candidate, a salt, a seed or a key. +pub(crate) fn fill_bytes(rng: &mut dyn RNG, out: &mut [u8]) -> Result<(), RNGError> { + let result = match rng.next_bytes_out(out) { + Ok(written) if written == out.len() => return Ok(()), + Ok(_) => Err(RNGError::GenericError("the RNG wrote fewer bytes than it was asked for")), + Err(e) => Err(e), + }; + for byte in out.iter_mut() { + zeroize_in_place(byte); + } + result +} + +/// Fills `out` with `64 * N` bits from `rng`, eight bytes to a limb in the order drawn: the +/// first eight bytes are limb 0, the least significant, and each eight are big-endian within +/// their limb. FIPS 186-5 Appendix B.2.1 reads a bit string most significant bit first, so the +/// integer here is that reading of the string drawn with its eight-byte groups in reverse +/// order. It is as uniform; a candidate reproduced from a given byte stream needs this order. +fn fill_random( + rng: &mut dyn RNG, + out: &mut [u64; N], +) -> Result<(), SignatureError> { + let mut buf = [0u8; 8]; + for limb in out.iter_mut() { + fill_bytes(rng, &mut buf).map_err(SignatureError::RNGError)?; + *limb = u64::from_be_bytes(buf); + } + Ok(()) +} + +// ---- primality ------------------------------------------------------------------------------- + +/// Whether some prime below [`SMALL_PRIME_LIMIT`] divides `w` -- other than `w` itself, so a small +/// prime is not reported as its own factor. The primes are bundled into `u64` products and each +/// bundle costs one multi-limb reduction (Appendix B.7's "may be divided by composite numbers"). +fn has_small_factor(w: &[u64; N]) -> bool { + let fits_u64 = w[1..].iter().all(|&l| l == 0); + let mut i = 0; + while i < SMALL_PRIME_COUNT { + let start = i; + let mut product: u64 = 1; + while i < SMALL_PRIME_COUNT { + match product.checked_mul(u64::from(SMALL_PRIMES[i])) { + Some(next) => { + product = next; + i += 1; + } + None => break, + } + } + let r = mod_u64(w, product); + for &p in &SMALL_PRIMES[start..i] { + let p = u64::from(p); + if r % p == 0 && !(fits_u64 && w[0] == p) { + return true; + } + } + } + false +} + +/// FIPS 186-5 Appendix B.3.1, the Miller-Rabin probabilistic primality test, with `rounds` +/// iterations whose bases come from `rng`: `Ok(true)` is PROBABLY PRIME, `Ok(false)` is COMPOSITE. +/// Preceded by trial division against the primes below [`SMALL_PRIME_LIMIT`] (Appendix B.7), +/// which is conclusive on its own for `w < 2^20` and otherwise only ever rejects. +/// +/// For a candidate drawn at random, `rounds` must be at least the value FIPS 186-5 Table B.1 +/// gives for its length and the caller's target error probability. For a number from +/// elsewhere only the bound that holds of every composite applies, `4^-rounds`; a key's primes +/// are tested at that bound by `RsaPrivateComponents::validate`. The type rules out zero +/// rounds at compile time. Bases that fall outside `[2, w - 2]` are +/// redrawn (step 4.2); an RNG that cannot produce one in 128 draws is reported as +/// `Err(GenericError)`, so a broken RNG cannot hang the test. +/// +/// `N2` is `2 * N` and `N21` is `2 * N + 1`, checked when the function is instantiated: +/// +/// ```compile_fail,E0080 +/// use bouncycastle_rng::DefaultRNG; +/// use bouncycastle_rsa::keygen::is_probable_prime; +/// use core::num::NonZeroUsize; +/// let rounds = NonZeroUsize::new(5).unwrap(); +/// let _ = is_probable_prime::<2, 4, 6>(&[0xffffffffffffffc5, 0], rounds, &mut DefaultRNG::default()); +/// ``` +/// +/// ``` +/// use bouncycastle_rng::DefaultRNG; +/// use bouncycastle_rsa::keygen::is_probable_prime; +/// use core::num::NonZeroUsize; +/// let rounds = NonZeroUsize::new(5).unwrap(); +/// // 2^64 - 59 is the largest prime below 2^64. +/// let prime = is_probable_prime::<2, 4, 5>(&[0xffffffffffffffc5, 0], rounds, &mut DefaultRNG::default()); +/// assert_eq!(prime, Ok(true)); +/// ``` +pub fn is_probable_prime( + w: &[u64; N], + rounds: NonZeroUsize, + rng: &mut dyn RNG, +) -> Result { + const { check_widths::() }; + let verdict = is_probable_prime_in_own_frame::(w, rounds, rng); + // `w` may be a prime of a private key: the context over it and the powers of the bases + // pass through frames that no `Secret` names, as in the CRT. + wipe_stack_below::<[u64; N], PRIMALITY_STACK_PER_LIMB, PRIMALITY_STACK_FIXED>(); + verdict +} + +/// What `wipe_stack_below` overwrites after [`is_probable_prime`]: this many `[u64; N]` values +/// and this many words. Measured in x86-64 release builds (rustc 1.88 and 1.97) with the +/// workspace's hash DRBG as the RNG, the test uses 4600 bytes at 16 limbs (a prime of RSA-2048), +/// 6488 at 24, 8328 at 32 and 13768 at 64; these cover 5504, 7552, 9600 and 17792, the +/// difference being room for a compiler that lays the frames out less tightly. +const PRIMALITY_STACK_PER_LIMB: usize = 32; +const PRIMALITY_STACK_FIXED: usize = 176; + +/// [`is_probable_prime`] for a caller that wipes: key generation, whose own frame covers every +/// test it makes. Never inlined, so that what the test leaves lies below its caller's frame. +#[inline(never)] +fn is_probable_prime_in_own_frame( + w: &[u64; N], + rounds: NonZeroUsize, + rng: &mut dyn RNG, +) -> Result { + let mut one = [0u64; N]; + one[0] = 1; + let mut two = [0u64; N]; + two[0] = 2; + if is_zero(w) || *w == one { + return Ok(false); + } + if w[0] & 1 == 0 { + return Ok(*w == two); + } + let fits_u64 = w[1..].iter().all(|&l| l == 0); + if fits_u64 && w[0] < (SMALL_PRIME_LIMIT * SMALL_PRIME_LIMIT) as u64 { + // Appendix B.7: no prime factor up to sqrt(w) means prime. + return Ok(!has_small_factor(w)); + } + if has_small_factor(w) { + return Ok(false); + } + + // Steps 1-2: w - 1 = 2^a * m with m odd. `w` is a candidate for a private prime, so these + // and the context over `w` are held in `Secret`, scrubbed on each of this function's exits. + let mut w_minus_1 = Secret::<[u64; N]>::new(); + *w_minus_1 = sub_u64(w, 1); + let a = trailing_zeros(&w_minus_1); + let mut m = Secret::<[u64; N]>::new(); + *m = shr(&w_minus_1, a); + // w is odd and greater than 1 here (checked above), as the constructor requires. + let mut ctx = Secret::>::new(); + *ctx = MontgomeryContext::for_secret_modulus(w); + + // Step 3: wlen = len(w), the bit length of w -- the bases are drawn at that length (not the + // full limb width), so that for a w well short of the width a draw still lands below w - 1 + // with probability at least 1/2. + let wlen = 64 * N as u32 - leading_zeros(w); + + // Step 4. + for _ in 0..rounds.get() { + // Steps 4.1-4.2: a random base b of wlen bits, redrawn unless in [2, w - 2]. + let mut b = [0u64; N]; + let mut drawn = false; + for _ in 0..128 { + fill_random(rng, &mut b)?; + mask_to_bits(&mut b, wlen); + if lt(&one, &b) && lt(&b, &w_minus_1) { + drawn = true; + break; + } + } + if !drawn { + return Err(SignatureError::GenericError( + "RNG produced no usable Miller-Rabin base in 128 draws", + )); + } + // Step 4.3. + let mut z = Secret::<[u64; N]>::new(); + *z = mod_pow::(&b, &m, &ctx); + // Step 4.4. + if *z == one || *z == *w_minus_1 { + continue; + } + // Step 4.5. + let mut witness = true; + for _ in 1..a { + *z = mul_mod::(&z, &z, &ctx); + if *z == *w_minus_1 { + witness = false; + break; + } + if *z == one { + break; + } + } + if witness { + // Step 4.6. + return Ok(false); + } + } + // Step 5. + Ok(true) +} + +// ---- key pair generation --------------------------------------------------------------------- + +/// A candidate for `p` or `q` (FIPS 186-5 Appendix A.1.3 steps 4.2-4.3 / 5.2-5.3): `64 * N` +/// random bits with the two most significant bits set (step 4.2.1's option) and forced odd (step +/// 4.3, "if p is not odd, then p = p + 1"). Setting both top bits makes step 4.4's lower bound +/// `p >= sqrt(2) * 2^(nlen/2 - 1)` hold by construction -- `0.75 * 2^(nlen/2) > 0.7071 * +/// 2^(nlen/2)` -- and makes `n = p * q` exactly `nlen` bits, so the bound is only +/// `debug_assert`ed rather than tested and retried. +fn candidate(rng: &mut dyn RNG, out: &mut [u64; N]) -> Result<(), SignatureError> { + fill_random(rng, out)?; + out[N - 1] |= 0b11 << 62; + out[0] |= 1; + // sqrt(2) * 2^63 = 0xB504F333F9DE6484...: with the top two bits set the top limb is at least + // 0xC000..., so this cannot fail. + debug_assert!(out[N - 1] > 0xB504_F333_F9DE_6484, "step 4.4's lower bound"); + Ok(()) +} + +/// FIPS 186-5 Appendix A.1.3 step 4 or 5: repeatedly draws a candidate until one passes +/// `GCD(p - 1, e) = 1` (step 4.5, as `e` not dividing `p - 1`, since `e` is prime), trial +/// division, and `rounds` of Miller-Rabin (step 4.5.1), giving up after `max_attempts` candidates +/// (step 4.7 / 5.8). `extra_check` is step 5.5's `|p - q|` test for `q`, and nothing for `p`. +fn random_prime( + rng: &mut dyn RNG, + rounds: NonZeroUsize, + max_attempts: usize, + out: &mut [u64; N], + extra_check: &dyn Fn(&[u64; N]) -> bool, +) -> Result<(), SignatureError> { + for _ in 0..max_attempts { + candidate(rng, out)?; + if !extra_check(out) { + continue; + } + // Step 4.5: GCD(p - 1, e) = 1, i.e. p mod e != 1 for prime e. + if mod_u64(out, PUBLIC_EXPONENT) == 1 { + continue; + } + if is_probable_prime_in_own_frame::(out, rounds, rng)? { + return Ok(()); + } + } + // Step 4.7 / 5.8: FAILURE. Zero the last candidate before reporting, as the spec's zero + // outputs do. + *out = [0u64; N]; + Err(SignatureError::GenericError( + "RSA key generation exhausted FIPS 186-5 A.1.3's candidate limit without finding a prime", + )) +} + +/// Step 5.5: `|p - q| <= 2^(nlen/2 - 100)` rejects `q` (Appendix A.1.1 criterion 2(d) asks for +/// `|p - q| > 2^(nlen/2 - 100)`). `nlen/2 = 64 * N` here. +fn primes_too_close(p: &[u64; N], q: &[u64; N]) -> bool { + let (mut d1, borrow) = nat::sub(q, p); + let (mut d2, _) = nat::sub(p, q); + let mut diff = if borrow == 1 { d2 } else { d1 }; + let threshold_bit = 64 * N as u32 - 100; + let mut high = shr(&diff, threshold_bit); + let mut one = [0u64; N]; + one[0] = 1; + // `|p - q| < 2^(nlen/2 - 100)`, or exactly `2^(nlen/2 - 100)`, which is also "<=": the high + // part is 1 and nothing is set below it. + let too_close = is_zero(&high) || (high == one && diff == shl(&one, threshold_bit)); + // The differences are functions of both primes: scrubbed before returning. + zeroize_in_place(&mut d1); + zeroize_in_place(&mut d2); + zeroize_in_place(&mut diff); + zeroize_in_place(&mut high); + too_close +} + +/// FIPS 186-5 Appendix A.1.1 criterion 3(a) on the `d` of criterion 3(b): whether +/// `d = e^-1 mod LCM(p - 1, q - 1)` exceeds `2^(nlen/2)`, `nlen/2` being `64 * HALF`. `e` has an +/// inverse modulo `p - 1` and modulo `q - 1`, which is the caller's to have established. +fn private_exponent_exceeds_half( + p_minus_1: &[u64; HALF], + q_minus_1: &[u64; HALF], + e: u64, +) -> bool { + let mut lcm = Secret::<[u64; HALF2]>::new(); + { + let mut g = gcd(p_minus_1, q_minus_1); + let mut q_minus_1_over_g = div(q_minus_1, &g); + *lcm = montgomery::widening_mul::(p_minus_1, &q_minus_1_over_g); + zeroize_in_place(&mut g); + zeroize_in_place(&mut q_minus_1_over_g); + } + let mut d = Secret::<[u64; HALF2]>::new(); + *d = inverse_of_e_mod(&lcm, e); + let d_high = &d[HALF..]; + let d_low = &d[..HALF]; + let mut one_high = [0u64; HALF]; + one_high[0] = 1; + d_high.iter().any(|&l| l != 0) && !(d_high == one_high && d_low.iter().all(|&l| l == 0)) +} + +/// Whether `x >= sqrt(2) * 2^(64 * HALF - 1)`, the lower bound FIPS 186-5 Appendix A.1.1 +/// criteria 2(b) and 2(c) put on a prime of `64 * HALF` bits. `sqrt(2) * 2^k` is not an +/// integer, so this is `x^2 >= 2^(128 * HALF - 1)`: the square's top bit. +fn at_least_sqrt2_scaled(x: &[u64; HALF]) -> bool { + let mut square = montgomery::widening_square::(x); + let top_bit_set = square[HALF2 - 1] >> 63 == 1; + zeroize_in_place(&mut square); + top_bit_set +} + +/// SP 800-56B Rev. 2 §6.4.1.4.3, `crt_pkv`: validation of a key pair held in the CRT form, +/// whichever way its public exponent was chosen. The steps are §6.4.1.2.1's with that +/// section's replacements, and the ones not computed here hold of every +/// [`RsaPrivateComponents`]: its constructor has checked them, or the type cannot hold a key +/// that fails them. `HALF2` is `2 * HALF` and `HALF21` is `2 * HALF + 1`. +/// +/// Not constant time in the key, as key generation is not: the same primality test, GCD and +/// division run over `p` and `q`. +pub(crate) fn validate_key_pair( + sk: &RsaPrivateComponents, + rng: &mut dyn RNG, +) -> Result<(), SignatureError> +where + K: RsaSigningSize + RsaSize, +{ + const { check_widths::() }; + let verdict = validate_key_pair_in_own_frame::(sk, rng); + // Key generation's wipe: validation makes the same computations over the primes, less + // the search, and measured 5344, 7304, 9656 and 16392 bytes at the four sizes. + wipe_stack_below::<[u64; HALF2], KEYGEN_STACK_PER_LIMB, KEYGEN_STACK_FIXED>(); + verdict +} + +/// The work of [`validate_key_pair`]. Never inlined, so that what it leaves lies below its +/// caller's frame, where `wipe_stack_below` reaches it. +#[inline(never)] +fn validate_key_pair_in_own_frame( + sk: &RsaPrivateComponents, + rng: &mut dyn RNG, +) -> Result<(), SignatureError> +where + K: RsaSigningSize + RsaSize, +{ + // The Miller-Rabin bases of step 5 come from the RNG (FIPS 186-5 Appendix B.3.1, "an + // approved deterministic random bit generator"), held to the strength key generation + // asks of it. + if rng.security_strength() < K::STRENGTH { + return Err(SignatureError::RNGError(RNGError::SecurityStrengthInsufficientForAlgorithm)); + } + // Step 1.a, 1.b: the targeted strength is the size's, which is at least 112 bits. + // Step 1.c: "If epub is not an odd integer such that 65,537 <= epub < 2^256". Odd by the + // key's constructor, and below 2^64 by its type. + if sk.e() < 65_537 { + return Err(SignatureError::DecodingError("the public exponent is below 65537")); + } + // Step 3: n = p * q of exactly nBits bits, by the key's constructor. + let (p, q) = (sk.p(), sk.q()); + // Step 5.a, 5.b: sqrt(2) * 2^(nBits/2 - 1) <= p, q <= 2^(nBits/2) - 1. The upper bound is + // the width of a prime. + if !at_least_sqrt2_scaled::(p) || !at_least_sqrt2_scaled::(q) { + return Err(SignatureError::DecodingError( + "a prime factor is below sqrt(2) * 2^(nBits/2 - 1)", + )); + } + // Step 5.c: "If |p - q| <= 2^(nBits/2 - 100)". + if primes_too_close(p, q) { + return Err(SignatureError::DecodingError("the prime factors are too close together")); + } + // Step 5.d, 5.e: GCD(p - 1, e) = GCD(q - 1, e) = 1, since e has the inverses dP and dQ + // modulo p - 1 and q - 1 (step 7.d, 7.e, checked by the key's constructor). + // Step 5.f, 5.g: "The probability that p or q may be incorrectly classified as prime by + // the test used in step 5 shall be less than or equal to 2^-ES(nBits)". The key is someone + // else's, so the bound is the one that holds of every composite: at most 1/4 of the bases + // pass one, and ES(nBits) / 2 rounds give 4^-(ES/2). + let rounds = K::VALIDATION_MR_ROUNDS; + if !is_probable_prime_in_own_frame::(p, rounds, rng)? + || !is_probable_prime_in_own_frame::(q, rounds, rng)? + { + return Err(SignatureError::DecodingError("a prime factor is composite")); + } + // Step 6: 2^(nBits/2) < d < LCM(p - 1, q - 1) and 1 = (d * e) mod LCM(p - 1, q - 1). The + // key holds no d: it is the inverse 6.b defines, which is below the LCM, so 6.a's lower + // bound is what is left. + let mut p_minus_1 = Secret::<[u64; HALF]>::new(); + *p_minus_1 = sub_u64(p, 1); + let mut q_minus_1 = Secret::<[u64; HALF]>::new(); + *q_minus_1 = sub_u64(q, 1); + if !private_exponent_exceeds_half::(&p_minus_1, &q_minus_1, sk.e()) { + return Err(SignatureError::DecodingError("the private exponent is not above 2^(nBits/2)")); + } + // Step 7: the CRT components, by the key's constructor. + Ok(()) +} + +/// FIPS 186-5 Appendix A.1.3, the whole process, for a modulus of `HALF2` limbs (`nlen = 64 * +/// HALF2` bits) built from two `HALF`-limb primes. `rounds` is the Miller-Rabin iteration count +/// (at least Table B.1's) and `required_strength` the security strength SP 800-57 Part 1 associates with +/// `nlen`, which the RNG must meet (step 3 and the paragraph above the process). The size modules +/// fix all three; see `RSA2048`'s `RsaSigningSize` impl for the RSA-2048 values. +/// +/// Returns the pair as this crate's key types: `(n, e)` and the CRT quintuple, with `dP = e^-1 mod +/// (p - 1)`, `dQ = e^-1 mod (q - 1)` (which equal `d mod (p - 1)` and `d mod (q - 1)` for the +/// `d = e^-1 mod LCM(p - 1, q - 1)` of Appendix A.1.1 criterion 3(b)) and `qInv = q^-1 mod p`. +/// Criterion 3(a), `d > 2^(nlen/2)`, is checked on that `d` and the whole process restarts if it +/// fails -- "the extremely rare event" the spec describes, of probability about `2^-(nlen/2)`. +/// +/// Errors: `RNGError(SecurityStrengthInsufficientForAlgorithm)` if `rng` is weaker than +/// `required_strength`; `RNGError` for an RNG failure; `GenericError` if the candidate limits of +/// steps 4.7/5.8 (`5 * nlen` for `p`, `10 * nlen` for `q`) are exhausted, which a working RNG +/// does not do. +/// +/// `HALF2` is `2 * HALF` and `HALF21` is `2 * HALF + 1`, checked when the function is +/// instantiated: +/// +/// ```compile_fail,E0080 +/// use bouncycastle_rng::DefaultRNG; +/// use bouncycastle_rsa::RSA2048; +/// use bouncycastle_rsa::keygen::keygen_from_rng; +/// use bouncycastle_rsa::size::{RsaSigningSize, RsaSize}; +/// let _ = keygen_from_rng::( +/// &mut DefaultRNG::default(), +/// RSA2048::MR_ROUNDS, +/// RSA2048::STRENGTH, +/// ); +/// ``` +/// +/// ```no_run +/// use bouncycastle_rng::DefaultRNG; +/// use bouncycastle_rsa::RSA2048; +/// use bouncycastle_rsa::keygen::keygen_from_rng; +/// use bouncycastle_rsa::size::{RsaSigningSize, RsaSize}; +/// let _ = keygen_from_rng::( +/// &mut DefaultRNG::default(), +/// RSA2048::MR_ROUNDS, +/// RSA2048::STRENGTH, +/// ); +/// ``` +pub fn keygen_from_rng( + rng: &mut dyn RNG, + rounds: NonZeroUsize, + required_strength: SecurityStrength, +) -> Result<(RsaPublicComponents, RsaPrivateComponents), SignatureError> +where + K: RsaSigningSize + RsaSize, +{ + const { check_widths::() }; + // The primes, the exponents and what is derived from them pass through locals, return + // slots and the frames of the primality test that no `Secret` names. + let _wipe = + WipeStackBelowOnReturn::<[u64; HALF2], KEYGEN_STACK_PER_LIMB, KEYGEN_STACK_FIXED>::new(); + keygen_in_own_frame::(rng, rounds, required_strength) +} + +/// [`RsaSigningSize::keygen`]'s pair handed to `finish`, which makes of it what the caller +/// returns: keys for a scheme, key-establishment keys. `finish` runs inside a frame that is +/// wiped, so a caller that ends with this call stages no copy of the new key in a frame of its +/// own, as with `RsaPrivateComponents::from_crt_components_as`. +pub(crate) fn keygen_as( + rng: &mut dyn RNG, + finish: impl FnOnce( + Result<(RsaPublicComponents, RsaPrivateComponents), SignatureError>, + ) -> Result, +) -> Result { + let _wipe = + WipeStackBelowOnReturn::::new(); + keygen_as_in_own_frame::(rng, finish) +} + +/// The work of [`keygen_as`]. Never inlined, so that what it leaves lies below its caller's +/// frame, where `wipe_stack_below` reaches it. +#[inline(never)] +fn keygen_as_in_own_frame( + rng: &mut dyn RNG, + finish: impl FnOnce( + Result<(RsaPublicComponents, RsaPrivateComponents), SignatureError>, + ) -> Result, +) -> Result { + finish(K::keygen(rng)) +} + +/// What `wipe_stack_below` overwrites after key generation: this many `[u64; HALF2]` values +/// and this many words. Measured in x86-64 release builds (rustc 1.88 and 1.97), key +/// generation uses 11480 bytes at RSA-2048, 16600 at RSA-3072, 21976 at RSA-4096 and 41144 at +/// RSA-8192; these cover 13568, 19328, 25088 and 48128, the difference being room for a +/// compiler that lays the frames out less tightly. +const KEYGEN_STACK_PER_LIMB: usize = 45; +const KEYGEN_STACK_FIXED: usize = 256; + +/// The work of [`keygen_from_rng`]. Never inlined, so that what it leaves lies below its +/// caller's frame, where `wipe_stack_below` reaches it. +#[inline(never)] +fn keygen_in_own_frame( + rng: &mut dyn RNG, + rounds: NonZeroUsize, + required_strength: SecurityStrength, +) -> Result<(RsaPublicComponents, RsaPrivateComponents), SignatureError> +where + K: RsaSigningSize + RsaSize, +{ + // Step 3 (and A.1.3's preamble): the DRBG's strength must meet the modulus's. + if rng.security_strength() < required_strength { + return Err(SignatureError::RNGError(RNGError::SecurityStrengthInsufficientForAlgorithm)); + } + let nlen = 64 * HALF2; + + loop { + // Held in `Secret` so the primes and everything derived from them are scrubbed when this + // function returns (or restarts), not left on the stack. + let mut p = Secret::<[u64; HALF]>::new(); + let mut q = Secret::<[u64; HALF]>::new(); + + // Step 4: generate p (up to 5 * nlen candidates). + random_prime::(rng, rounds, 5 * nlen, &mut p, &|_| true)?; + // Step 5: generate q (up to 10 * nlen candidates), rejecting one too close to p (5.5). + { + let p_ref: &[u64; HALF] = &p; + random_prime::(rng, rounds, 10 * nlen, &mut q, &|cand| { + !primes_too_close(p_ref, cand) + })?; + } + + // Appendix A.1.1 criterion 3: d = e^-1 mod LCM(p - 1, q - 1) must exceed 2^(nlen/2). + let mut p_minus_1 = Secret::<[u64; HALF]>::new(); + *p_minus_1 = sub_u64(&p, 1); + let mut q_minus_1 = Secret::<[u64; HALF]>::new(); + *q_minus_1 = sub_u64(&q, 1); + if !private_exponent_exceeds_half::(&p_minus_1, &q_minus_1, PUBLIC_EXPONENT) { + // "then new values for p, q, and d shall be determined." + continue; + } + + // The CRT quintuple (RFC 8017 §3.2). dP and dQ are the same inverse taken modulo p - 1 + // and q - 1 directly, which is what `d mod (p - 1)` and `d mod (q - 1)` come to. + let mut d_p = Secret::<[u64; HALF]>::new(); + *d_p = inverse_of_e_mod(&p_minus_1, PUBLIC_EXPONENT); + let mut d_q = Secret::<[u64; HALF]>::new(); + *d_q = inverse_of_e_mod(&q_minus_1, PUBLIC_EXPONENT); + // qInv = q^-1 mod p = q^(p - 2) mod p (Fermat; p is prime and does not divide q), through + // the constant-time ladder with p - 2 as the exponent. + let mut q_inv = Secret::<[u64; HALF]>::new(); + { + let mut q_mod_p = reduce_wide::(&q, &p); + let mut p_minus_2 = sub_u64(&p, 2); + // p is odd by construction (step 4.3), as the constructor requires. + let mut ctx_p = Secret::>::new(); + *ctx_p = MontgomeryContext::for_secret_modulus(&p); + *q_inv = mod_pow::(&q_mod_p, &p_minus_2, &ctx_p); + zeroize_in_place(&mut q_mod_p); + zeroize_in_place(&mut p_minus_2); + } + + let sk = RsaPrivateComponents::::from_crt_components( + &p, &q, &d_p, &d_q, &q_inv, PUBLIC_EXPONENT, + )?; + let pk = RsaPublicComponents::::new(sk.n(), PUBLIC_EXPONENT)?; + return Ok((pk, sk)); + } +} + +// `primes_too_close` is private and, through `keygen_from_rng`, only ever reached on two +// independently drawn `nlen/2`-bit primes, which land within `2^(nlen/2 - 100)` of each other with +// probability about `2^-100`: no integration test through the public API can exercise its reject +// path or pin its boundary, so the QUALITY_AND_STYLE.md private-function, known-answer exception +// applies. Known answers at `N = 2` (`threshold_bit = 28`): a difference below `2^28`, or exactly +// `2^28`, is too close (Appendix A.1.1 criterion 2(d) is `|p - q| > 2^(nlen/2 - 100)`, so equality +// fails it); `2^28 + 1` and above is not; and the order of `p` and `q` does not matter. +// +// `fill_bytes`'s wipe of a buffer the RNG did not fill is likewise invisible from outside: every +// caller's buffer is a local that an error discards. +#[cfg(test)] +mod tests { + use super::*; + use bouncycastle_core::key_material::KeyMaterialTrait; + + /// An RNG that writes `written` bytes of `0xA5` and returns `result`. + struct Writes { + written: usize, + result: Result, + } + + impl RNG for Writes { + fn add_seed_keymaterial(&mut self, _: &dyn KeyMaterialTrait) -> Result<(), RNGError> { + Err(RNGError::GenericError("not used")) + } + fn next_int(&mut self) -> Result { + Err(RNGError::GenericError("not used")) + } + fn next_bytes_out(&mut self, out: &mut [u8]) -> Result { + out[..self.written].fill(0xA5); + match &self.result { + Ok(count) => Ok(*count), + Err(_) => Err(RNGError::ReseedRequired), + } + } + fn fill_keymaterial_out( + &mut self, + _: &mut dyn KeyMaterialTrait, + ) -> Result { + Err(RNGError::GenericError("not used")) + } + fn security_strength(&self) -> SecurityStrength { + SecurityStrength::_256bit + } + } + + #[test] + fn fill_bytes_takes_a_full_draw_and_wipes_any_other() { + let mut out = [0u8; 8]; + assert_eq!(fill_bytes(&mut Writes { written: 8, result: Ok(8) }, &mut out), Ok(())); + assert_eq!(out, [0xA5; 8]); + + let short = Err(RNGError::GenericError("the RNG wrote fewer bytes than it was asked for")); + // One byte short, by the count; and a count that is not the length at all. + for (written, count) in [(7, 7), (4, 4), (0, 0), (8, 7), (8, 9)] { + let mut out = [0xFFu8; 8]; + assert_eq!(fill_bytes(&mut Writes { written, result: Ok(count) }, &mut out), short); + assert_eq!(out, [0u8; 8], "wrote {written}, returned {count}"); + } + + // The RNG's own error comes back as it is, over a wiped buffer. + let mut out = [0xFFu8; 8]; + let mut failing = Writes { written: 3, result: Err(RNGError::ReseedRequired) }; + assert_eq!(fill_bytes(&mut failing, &mut out), Err(RNGError::ReseedRequired)); + assert_eq!(out, [0u8; 8]); + } + + const P: [u64; 2] = [0x1234_5678_9abc_def1, 0xc000_0000_0000_0001]; + + fn p_plus(d: u64) -> [u64; 2] { + nat::add(&P, &[d, 0]).0 + } + + #[test] + fn primes_too_close_boundary_cases() { + assert!(primes_too_close(&P, &p_plus(1))); + assert!(primes_too_close(&P, &p_plus(4))); + assert!(primes_too_close(&P, &p_plus(1 << 28))); + assert!(!primes_too_close(&P, &p_plus((1 << 28) + 1))); + assert!(!primes_too_close(&P, &p_plus(1 << 29))); + } + + #[test] + fn primes_too_close_is_symmetric_in_its_arguments() { + assert!(primes_too_close(&p_plus(1), &P)); + assert!(primes_too_close(&p_plus(1 << 28), &P)); + assert!(!primes_too_close(&p_plus((1 << 28) + 1), &P)); + } +} diff --git a/crypto/rsa/src/keys.rs b/crypto/rsa/src/keys.rs new file mode 100644 index 000000000..fd8dfb92e --- /dev/null +++ b/crypto/rsa/src/keys.rs @@ -0,0 +1,735 @@ +//! RSA key material and the signature keys over it. [`RsaPublicComponents`] (RFC 8017 §3.1's +//! `(n, e)`) and [`RsaPrivateComponents`] (§3.2's "second representation", the CRT quintuple +//! `p`, `q`, `dP`, `dQ`, `qInv`, with `e`), generic over the modulus size [`RsaSize`], are what a key is +//! made of and implement no role. [`RsaPublicKey`] and [`RsaPrivateKey`] wrap them for one +//! signature algorithm `A` ([`RsaSignatureAlgorithm`]: `RSASSA_PSS` and so on), +//! so a key signs and verifies under the scheme and hash its type names, `sk.sign(..)` and +//! `pk.verify(..)`, and a PSS key cannot sign PKCS#1 v1.5: SP 800-57 Part 1 Rev. 5's one scheme +//! per key pair, in the type system, as the ECDSA keys carry their curve and hash. The +//! key-establishment keys of [`crate::rsasve`] wrap the same components under the KEM roles. +//! +//! Components come either from [`crate::keygen`] (FIPS 186-5 Appendix A.1.3, through +//! [`RsaSigningSize::keygen`] and the generators of [`crate::size::SignatureKeyPair`]) or from +//! externally supplied key material (CAVP and Wycheproof vectors, a key produced by another +//! implementation) through [`RsaPrivateComponents::from_crt_components`] or the keys' own +//! `from_crt_components`. RFC 8017's first representation, the plain `(n, d)` pair, is not +//! supported: every real RSA private key ships as the CRT form because CRT-based signing (RFC +//! 8017 §5.2.1 step 2.b) is the only signing path this crate implements. +//! +//! The keys implement `bouncycastle_core`'s `PublicKey` / `PrivateKey`, the +//! private key only at a [`RsaSigningSize`], with the byte layouts described on the components. +//! The scheme is not encoded, so a key file is decoded under the key type it is for. + +use crate::rsa_core::{WipeStackBelowOnReturn, wipe_stack_below}; +use crate::rsassa::RsaSignatureAlgorithm; +use crate::size::{RsaSigningSize, RsaSize}; +use bouncycastle_core::errors::{KeyDecodingError, SignatureError}; +use bouncycastle_core::security_strength::SecurityStrength; +use bouncycastle_core::traits::{PrivateKey, PublicKey, RNG}; +use bouncycastle_utils::secret::{Secret, ZeroizablePrimitive}; +use core::fmt; +use core::fmt::{Debug, Display, Formatter}; +use core::marker::PhantomData; + +/// RSA public key material: RFC 8017 §3.1's `(n, e)`, at the size `K`. Not a key: the keys over +/// it are [`RsaPublicKey`] and [`crate::rsasve::RsaKEMPublicKey`]. +/// +/// # Encoding +/// +/// The keys' `PublicKey::encode`/`from_bytes` use the raw layout `n || e`: `n` as `K::K_LEN` +/// big-endian bytes (RFC 8017 §4.1's I2OSP), then `e` as 8 big-endian bytes, `K::PK_LEN` in all. +/// Not an RFC 8017 or ASN.1 format -- this crate has no DER encoder/decoder -- just a fixed-width +/// layout that round-trips, for `cli/src/rsa_cmd.rs` to read and write public keys as files. +/// Decoding validates `(n, e)` the same way [`Self::new`] does; the scheme is not encoded. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct RsaPublicComponents { + n: K::Limbs, + e: u64, +} + +/// Whether the modulus's top bit is set: `n` has exactly the size's bit length, `K::BITS`. +fn has_full_bit_length(n: &K::Limbs) -> bool { + n.as_ref()[n.as_ref().len() - 1] >> 63 == 1 +} + +/// What both constructors return for a modulus shorter than its size. +const MODULUS_NOT_FULL_LENGTH: SignatureError = + SignatureError::DecodingError("RSA modulus must have its top bit set"); + +/// RFC 8017 §3.1: `e` is odd and at least 3, in the public key and in the private key's copy. +fn check_public_exponent(e: u64) -> Result<(), SignatureError> { + if e < 3 || e & 1 == 0 { + return Err(SignatureError::DecodingError( + "RSA public exponent must be odd and at least 3", + )); + } + Ok(()) +} + +impl RsaPublicComponents { + /// Builds a public key from its modulus and exponent. Returns + /// `Err(`[`SignatureError::DecodingError`]`)` if `n` is even (a product of two odd primes + /// never is), if `n` is not exactly `K::BITS` bits long (its top bit is clear), or if `e` + /// is even or below 3 (RFC 8017 §3.1: `e` is odd and at least 3). + pub fn new(n: &K::Limbs, e: u64) -> Result { + if n.as_ref()[0] & 1 == 0 { + return Err(SignatureError::DecodingError("RSA modulus must be odd")); + } + // A size is its modulus's exact bit length. RSASSA-PSS depends on it: RFC 8017 §8.1.1 + // step 1 and §8.1.2 step 3 encode and verify at emBits = modBits - 1, which + // `emsa_pss` takes as 8 * K_LEN - 1. + if !has_full_bit_length::(n) { + return Err(MODULUS_NOT_FULL_LENGTH); + } + check_public_exponent(e)?; + Ok(Self { n: *n, e }) + } + + /// The modulus `n`, as little-endian limbs. + pub fn n(&self) -> &K::Limbs { + &self.n + } + + /// The public exponent `e`. + pub fn e(&self) -> u64 { + self.e + } + + /// A copy of these components as the public key of `A`. + pub fn key>(&self) -> RsaPublicKey { + RsaPublicKey::from_components(self.clone()) + } + + /// These components as the public key of `A`. + pub fn into_key>(self) -> RsaPublicKey { + RsaPublicKey::from_components(self) + } + + /// The `# Encoding` layout. + pub(crate) fn encode_raw(&self) -> K::PublicKeyEncoded { + let mut out = K::PublicKeyEncoded::ZEROED; + out.as_mut()[..K::K_LEN].copy_from_slice(K::be_bytes_from_limbs(&self.n).as_ref()); + out.as_mut()[K::K_LEN..].copy_from_slice(&self.e.to_be_bytes()); + out + } + + /// The `# Encoding` layout decoded and validated as [`Self::new`] validates. + pub(crate) fn from_bytes_raw(bytes: &K::PublicKeyEncoded) -> Result { + let bytes = bytes.as_ref(); + let mut n_bytes = K::Modulus::ZEROED; + n_bytes.as_mut().copy_from_slice(&bytes[..K::K_LEN]); + let n = K::limbs_from_be_bytes(&n_bytes); + let e_bytes: [u8; 8] = bytes[K::K_LEN..].try_into().expect("PK_LEN is K_LEN + 8"); + Self::new(&n, u64::from_be_bytes(e_bytes)) + } +} + +/// RSA private key material in RFC 8017 §3.2's CRT ("second representation") form: `p`, `q`, +/// `dP`, `dQ`, `qInv`, at the size `K`, each component a prime-width integer (`K::HalfLimbs`), +/// and the public exponent `e`, which every private-key operation checks its result against +/// (the crate's `# Security Considerations`). +/// Not a key: the keys over it are [`RsaPrivateKey`] and [`crate::rsasve::RsaKEMPrivateKey`]. +/// +/// # Encoding +/// +/// The keys' `PrivateKey::encode`/`from_bytes`, at a signing size, use the raw layout +/// `p || q || dP || dQ || qInv || e`: the five CRT components each `K::K_LEN / 2` big-endian +/// bytes, then `e` as 8 big-endian bytes, `K::SK_LEN = 5 * K::K_LEN / 2 + 8` in all. Not an +/// RFC 8017 or ASN.1 format -- see [`RsaPublicComponents`]'s `# Encoding` for why -- just a +/// fixed-width layout that round-trips, for `cli/src/rsa_cmd.rs` to read and write private +/// keys as files. +/// Decoding validates the components the same way [`Self::from_crt_components`] does. +#[derive(Debug, PartialEq, Eq)] +pub struct RsaPrivateComponents { + p: Secret, + q: Secret, + d_p: Secret, + d_q: Secret, + q_inv: Secret, + /// `p * q`, kept so signing's range check and the public key need no recomputation; public. + n: K::Limbs, + /// The public exponent, kept so a private-key operation can check its result; public. + e: u64, +} + +/// What [`wipe_stack_below`] overwrites after a private key is constructed or decoded: this +/// many `K::Limbs` values and this many words. Measured in x86-64 release builds (rustc 1.88 +/// and 1.97), decoding, the deeper of the two, uses at most 6016 bytes at RSA-2048, 9040 at +/// RSA-3072, 11832 at RSA-4096 and 24104 at RSA-8192; these cover 7232, 10688, 14144 and +/// 27968, the difference being room for a compiler that lays the frames out less tightly. +const KEY_STACK_PER_LIMB: usize = 27; +const KEY_STACK_FIXED: usize = 40; + +/// The same after a private key is encoded or cloned, which use 1944, 2856, 3752 and 7336 +/// bytes at those sizes; these cover 2304, 3328, 4352 and 8448. +const COPY_STACK_PER_LIMB: usize = 8; +const COPY_STACK_FIXED: usize = 32; + +// Written out rather than derived, to run in a frame of its own: a copy of five secret +// components passes through return slots that no `Secret` names. +impl Clone for RsaPrivateComponents { + fn clone(&self) -> Self { + let _wipe = + WipeStackBelowOnReturn::::new(); + self.clone_in_own_frame() + } +} + +impl RsaPrivateComponents { + /// The copy [`Clone::clone`] makes. Never inlined, so that what it leaves lies below its + /// caller's frame, where [`wipe_stack_below`] reaches it. + #[inline(never)] + fn clone_in_own_frame(&self) -> Self { + Self { + p: self.p.clone(), + q: self.q.clone(), + d_p: self.d_p.clone(), + d_q: self.d_q.clone(), + q_inv: self.q_inv.clone(), + n: self.n, + e: self.e, + } + } +} + +// The constructors are a signing size's: RSA-1024 and RSA-1536 verify only, so no private key +// value exists at those sizes (the crate's `# Scope`). +impl RsaPrivateComponents { + /// Builds a private key from its CRT components and the public exponent of its key pair, + /// computing `n = p * q`. Returns `Err(`[`SignatureError::DecodingError`]`)` if `p` or `q` + /// is even, `p == q`, `dP`, `dQ` or `qInv` is not below its prime, `n` is not exactly + /// `K::BITS` bits long (its top bit is clear), `e` is even or below 3, or the components + /// and `e` do not belong together: `dP` and `dQ` are not the inverses of `e` modulo `p - 1` + /// and `q - 1`, or `qInv` is not the inverse of `q` modulo `p` (RFC 8017 §3.2). Primality + /// is not checked (see the crate's `# Security Considerations`); [`Self::validate`] does. + pub fn from_crt_components( + p: &K::HalfLimbs, + q: &K::HalfLimbs, + d_p: &K::HalfLimbs, + d_q: &K::HalfLimbs, + q_inv: &K::HalfLimbs, + e: u64, + ) -> Result { + Self::from_crt_components_as(p, q, d_p, d_q, q_inv, e, |components| components) + } + + /// [`Self::from_crt_components`] with its result handed to `finish`, which makes of it what + /// the caller returns: a key type over the components, another error. `finish` runs inside + /// the frame that is wiped, so a caller that ends with this call stages no copy of the key + /// in a frame of its own: the key is written once, into the `Result` that caller returns. + /// What is done with that `Result` afterwards is not covered: taking the key out of it + /// is a move, as the crate's Security Considerations say. + pub(crate) fn from_crt_components_as( + p: &K::HalfLimbs, + q: &K::HalfLimbs, + d_p: &K::HalfLimbs, + d_q: &K::HalfLimbs, + q_inv: &K::HalfLimbs, + e: u64, + finish: impl FnOnce(Result) -> Result, + ) -> Result { + let _wipe = WipeStackBelowOnReturn::::new(); + Self::from_crt_components_in_own_frame(p, q, d_p, d_q, q_inv, e, finish) + } + + /// The work of [`Self::from_crt_components_as`]. Never inlined, so that the copies of the + /// components it leaves lie below its caller's frame, where [`wipe_stack_below`] reaches + /// them. + #[inline(never)] + fn from_crt_components_in_own_frame( + p: &K::HalfLimbs, + q: &K::HalfLimbs, + d_p: &K::HalfLimbs, + d_q: &K::HalfLimbs, + q_inv: &K::HalfLimbs, + e: u64, + finish: impl FnOnce(Result) -> Result, + ) -> Result { + finish(Self::validated(p, q, d_p, d_q, q_inv, e)) + } + + /// The checks and the key of [`Self::from_crt_components`], for a caller that runs under a + /// wipe of its own. + fn validated( + p: &K::HalfLimbs, + q: &K::HalfLimbs, + d_p: &K::HalfLimbs, + d_q: &K::HalfLimbs, + q_inv: &K::HalfLimbs, + e: u64, + ) -> Result { + check_public_exponent(e)?; + if p.as_ref()[0] & 1 == 0 { + return Err(SignatureError::DecodingError("p must be odd")); + } + if q.as_ref()[0] & 1 == 0 { + return Err(SignatureError::DecodingError("q must be odd")); + } + if p == q { + return Err(SignatureError::DecodingError("p and q must be distinct")); + } + if !K::half_is_less(d_p, p) { + return Err(SignatureError::DecodingError("dP must be less than p")); + } + if !K::half_is_less(d_q, q) { + return Err(SignatureError::DecodingError("dQ must be less than q")); + } + if !K::half_is_less(q_inv, p) { + return Err(SignatureError::DecodingError("qInv must be less than p")); + } + + // `p * q` is exact, never reduced, since it is the modulus itself, and must be full + // length for the reason `RsaPublicComponents::new` gives. + let n = K::modulus_from_primes(p, q); + if !has_full_bit_length::(&n) { + return Err(MODULUS_NOT_FULL_LENGTH); + } + // RFC 8017 §3.2: the components and `e` are one key. All three verdicts are computed + // before any is looked at. + let [d_p_ok, d_q_ok, q_inv_ok] = K::crt_congruences(p, q, d_p, d_q, q_inv, e); + if !d_p_ok.to_bool() { + return Err(SignatureError::DecodingError("dP is not the inverse of e modulo p - 1")); + } + if !d_q_ok.to_bool() { + return Err(SignatureError::DecodingError("dQ is not the inverse of e modulo q - 1")); + } + if !q_inv_ok.to_bool() { + return Err(SignatureError::DecodingError("qInv is not the inverse of q modulo p")); + } + + let mut key = Self { + p: Secret::new(), + q: Secret::new(), + d_p: Secret::new(), + d_q: Secret::new(), + q_inv: Secret::new(), + n, + e, + }; + *key.p = *p; + *key.q = *q; + *key.d_p = *d_p; + *key.d_q = *d_q; + *key.q_inv = *q_inv; + Ok(key) + } +} + +impl RsaPrivateComponents { + /// Validates the key pair these components and their `n` and `e` make, as SP 800-56B Rev. 2 + /// §6.4.1.4.3 (`crt_pkv`) does: beyond what the constructor checked, that `e` is at least + /// 65,537, that `p` and `q` are each at least `sqrt(2) * 2^(nBits/2 - 1)`, more than + /// `2^(nBits/2 - 100)` apart and probably prime, and that the private exponent + /// `d = e^-1 mod LCM(p - 1, q - 1)` is above `2^(nBits/2)`. A key from this crate's key + /// generation passes; this is for a key from elsewhere. + /// + /// Primality is the Miller-Rabin test with bases from `rng`, at + /// [`VALIDATION_MR_ROUNDS`](RsaSigningSize::VALIDATION_MR_ROUNDS) rounds, so that a composite + /// passes with probability at most `2^-ES(nBits)` however it was chosen. That is the work + /// of about that many private-key operations: 56 at RSA-2048. + /// + /// # Errors + /// [`SignatureError::DecodingError`], naming the criterion, if the key pair is not valid; + /// [`SignatureError::RNGError`] if `rng` is weaker than the size's + /// [`STRENGTH`](RsaSize::STRENGTH) or fails to deliver; [`SignatureError::GenericError`] if + /// it gave no usable Miller-Rabin base in 128 draws. + /// + /// # 🚨 Security Considerations 🚨 + /// + /// Not constant time in the key, as key generation is not. + pub fn validate(&self, rng: &mut dyn RNG) -> Result<(), SignatureError> { + K::validate_key_pair(self, rng) + } +} + +impl RsaPrivateComponents { + /// The modulus `n = p * q`, as little-endian limbs. + pub fn n(&self) -> &K::Limbs { + &self.n + } + + /// The public exponent `e` of the key pair. + pub fn e(&self) -> u64 { + self.e + } + + /// A copy of these components as the private key of `A`. + pub fn key>(&self) -> RsaPrivateKey { + // The copy is made in the key, not handed to a constructor through this frame. + RsaPrivateKey { components: self.clone(), _alg: PhantomData } + } + + /// These components as the private key of `A`. + pub fn into_key>(self) -> RsaPrivateKey { + RsaPrivateKey::from_components(self) + } + + pub(crate) fn p(&self) -> &K::HalfLimbs { + &self.p + } + + pub(crate) fn q(&self) -> &K::HalfLimbs { + &self.q + } + + pub(crate) fn d_p(&self) -> &K::HalfLimbs { + &self.d_p + } + + pub(crate) fn d_q(&self) -> &K::HalfLimbs { + &self.d_q + } + + pub(crate) fn q_inv(&self) -> &K::HalfLimbs { + &self.q_inv + } +} + +impl RsaPrivateComponents { + /// The `# Encoding` layout. + pub(crate) fn encode_raw(&self) -> K::PrivateKeyEncoded { + let _wipe = + WipeStackBelowOnReturn::::new(); + self.encode_raw_in_own_frame() + } + + /// The `# Encoding` layout into `out`. + pub(crate) fn encode_raw_out(&self, out: &mut K::PrivateKeyEncoded) { + self.encode_raw_out_in_own_frame(out); + wipe_stack_below::(); + } + + /// The work of [`Self::encode_raw`]. Never inlined: see + /// [`Self::from_crt_components_in_own_frame`]. + #[inline(never)] + fn encode_raw_in_own_frame(&self) -> K::PrivateKeyEncoded { + self.encoded() + } + + /// The work of [`Self::encode_raw_out`]. Never inlined: see + /// [`Self::from_crt_components_in_own_frame`]. + #[inline(never)] + fn encode_raw_out_in_own_frame(&self, out: &mut K::PrivateKeyEncoded) { + *out = self.encoded(); + } + + /// The encoding, for a caller that runs under a wipe of its own. + fn encoded(&self) -> K::PrivateKeyEncoded { + let half = K::K_LEN / 2; + let mut out = K::PrivateKeyEncoded::ZEROED; + for (i, component) in + [&self.p, &self.q, &self.d_p, &self.d_q, &self.q_inv].into_iter().enumerate() + { + out.as_mut()[i * half..(i + 1) * half] + .copy_from_slice(K::half_be_bytes_from_limbs(component).as_ref()); + } + out.as_mut()[5 * half..].copy_from_slice(&self.e.to_be_bytes()); + out + } + + /// The `# Encoding` layout decoded and validated as [`Self::from_crt_components`] + /// validates. Each component is staged in a `Secret` on the way to its limbs, scrubbed + /// before returning; the caller's buffer is the one other copy of the encoding. + /// + /// The result is handed to `finish`, as [`Self::from_crt_components_as`] hands its own and + /// for the same reason. + pub(crate) fn from_bytes_raw_as( + bytes: &K::PrivateKeyEncoded, + finish: impl FnOnce(Result) -> Result, + ) -> Result { + let _wipe = WipeStackBelowOnReturn::::new(); + Self::from_bytes_raw_in_own_frame(bytes, finish) + } + + /// The work of [`Self::from_bytes_raw_as`]. Never inlined: see + /// [`Self::from_crt_components_in_own_frame`]. + #[inline(never)] + fn from_bytes_raw_in_own_frame( + bytes: &K::PrivateKeyEncoded, + finish: impl FnOnce(Result) -> Result, + ) -> Result { + finish(Self::decoded(bytes)) + } + + /// The decoding, for a caller that runs under a wipe of its own. + fn decoded(bytes: &K::PrivateKeyEncoded) -> Result { + let half = K::K_LEN / 2; + let bytes = bytes.as_ref(); + let mut staged = Secret::::new(); + let mut components: [Secret; 5] = core::array::from_fn(|_| Secret::new()); + for (i, component) in components.iter_mut().enumerate() { + staged.as_mut().copy_from_slice(&bytes[i * half..(i + 1) * half]); + **component = K::half_limbs_from_be_bytes(&staged); + } + let [p, q, d_p, d_q, q_inv] = &components; + let e_bytes: [u8; 8] = bytes[5 * half..].try_into().expect("SK_LEN is 5 * K_LEN / 2 + 8"); + Self::validated(p, q, d_p, d_q, q_inv, u64::from_be_bytes(e_bytes)) + } +} + +/// An RSA public key for the signature algorithm `A`: [`RsaPublicComponents`] under +/// [`VerifyingKey`](bouncycastle_core::signature_key::VerifyingKey) for `A`, so `pk.verify(..)` +/// is `A`'s verification. The same bytes decoded under another `A` are another key. +pub struct RsaPublicKey { + components: RsaPublicComponents, + _alg: PhantomData, +} + +impl RsaPublicKey { + /// A key from its modulus and exponent, validated as [`RsaPublicComponents::new`] validates. + /// + /// # Errors + /// As [`RsaPublicComponents::new`]. + pub fn new(n: &::Limbs, e: u64) -> Result { + Ok(Self::from_components(RsaPublicComponents::new(n, e)?)) + } + + /// A key over validated components. + pub fn from_components(components: RsaPublicComponents) -> Self { + Self { components, _alg: PhantomData } + } + + /// The components. + pub fn components(&self) -> &RsaPublicComponents { + &self.components + } + + /// The modulus `n`, as little-endian limbs. + pub fn n(&self) -> &::Limbs { + self.components.n() + } + + /// The public exponent `e`. + pub fn e(&self) -> u64 { + self.components.e() + } +} + +// Written out rather than derived: a derive would bound `A`, which is a marker. +impl Clone for RsaPublicKey { + fn clone(&self) -> Self { + Self { components: self.components.clone(), _alg: PhantomData } + } +} + +impl Debug for RsaPublicKey { + fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { + f.debug_struct("RsaPublicKey") + .field("algorithm", &A::ALG_NAME) + .field("components", &self.components) + .finish() + } +} + +impl PartialEq for RsaPublicKey { + fn eq(&self, other: &Self) -> bool { + self.components == other.components + } +} + +impl Eq for RsaPublicKey {} + +impl PublicKey for RsaPublicKey +where + A: RsaSignatureAlgorithm, + A::Size: RsaSize, +{ + fn encode(&self) -> [u8; PK_LEN] { + self.components.encode_raw() + } + + fn encode_out(&self, out: &mut [u8; PK_LEN]) -> usize { + *out = self.components.encode_raw(); + PK_LEN + } + + fn from_bytes(bytes: &[u8]) -> Result { + let bytes: &[u8; PK_LEN] = bytes.try_into().map_err(|_| { + KeyDecodingError("an RSA public key is the modulus length plus eight bytes") + })?; + Ok(Self::from_components( + RsaPublicComponents::from_bytes_raw(bytes).map_err(decoding_error)?, + )) + } +} + +/// `RsaPublicKey { n: , e: }`, `n` as one big-endian hex +/// string (the limbs are stored least-significant first, so they are printed in reverse). +/// Required by `PublicKey`'s `Display` supertrait; public data only, so nothing is +/// redacted. +impl Display for RsaPublicKey { + fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { + write!(f, "RsaPublicKey<{}, {}> {{ n: ", A::ALG_NAME, A::Size::NAME)?; + for limb in self.components.n().as_ref().iter().rev() { + write!(f, "{limb:016x}")?; + } + write!(f, ", e: {:x} }}", self.components.e()) + } +} + +/// An RSA private key for the signature algorithm `A`: [`RsaPrivateComponents`] under +/// [`SigningKey`](bouncycastle_core::signature_key::SigningKey) or +/// [`DeterministicSigningKey`](bouncycastle_core::signature_key::DeterministicSigningKey) for +/// `A`, whichever `A`'s scheme is, so `sk.sign(..)` or `sk.sign_deterministic(..)` is `A`'s +/// signing and no other scheme's. Exists only at a [`RsaSigningSize`]. +pub struct RsaPrivateKey { + components: RsaPrivateComponents, + _alg: PhantomData, +} + +impl RsaPrivateKey +where + A::Size: RsaSigningSize, +{ + /// A key from its CRT components and public exponent, validated as + /// [`RsaPrivateComponents::from_crt_components`] validates. + /// + /// # Errors + /// As [`RsaPrivateComponents::from_crt_components`]. + pub fn from_crt_components( + p: &::HalfLimbs, + q: &::HalfLimbs, + d_p: &::HalfLimbs, + d_q: &::HalfLimbs, + q_inv: &::HalfLimbs, + e: u64, + ) -> Result { + RsaPrivateComponents::from_crt_components_as(p, q, d_p, d_q, q_inv, e, |components| { + components.map(Self::from_components) + }) + } +} + +impl RsaPrivateKey { + /// A key over validated components. + pub fn from_components(components: RsaPrivateComponents) -> Self { + Self { components, _alg: PhantomData } + } + + /// The components. + pub fn components(&self) -> &RsaPrivateComponents { + &self.components + } + + /// The modulus `n = p * q`, as little-endian limbs. + pub fn n(&self) -> &::Limbs { + self.components.n() + } + + /// The public exponent `e` of the key pair. + pub fn e(&self) -> u64 { + self.components.e() + } +} + +impl Clone for RsaPrivateKey { + fn clone(&self) -> Self { + Self { components: self.components.clone(), _alg: PhantomData } + } +} + +impl Debug for RsaPrivateKey { + fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { + f.debug_struct("RsaPrivateKey") + .field("algorithm", &A::ALG_NAME) + .field("components", &self.components) + .finish() + } +} + +impl PartialEq for RsaPrivateKey { + fn eq(&self, other: &Self) -> bool { + self.components == other.components + } +} + +impl Eq for RsaPrivateKey {} + +impl PrivateKey for RsaPrivateKey +where + A: RsaSignatureAlgorithm, + A::Size: RsaSigningSize + RsaSize, +{ + fn encode(&self) -> [u8; SK_LEN] { + self.components.encode_raw() + } + + fn encode_out(&self, out: &mut [u8; SK_LEN]) -> usize { + self.components.encode_raw_out(out); + SK_LEN + } + + fn from_bytes(bytes: &[u8]) -> Result { + let bytes: &[u8; SK_LEN] = bytes.try_into().map_err(|_| { + KeyDecodingError( + "an RSA private key is five components of half the modulus length and eight bytes", + ) + })?; + RsaPrivateComponents::from_bytes_raw_as(bytes, |components| { + components.map(Self::from_components).map_err(decoding_error) + }) + } +} + +/// The security strength SP 800-57 Part 1 Rev. 5 Table 2 assigns an RSA modulus of `limbs` +/// 64-bit limbs: 112 bits at 2048, 128 at 3072 and 4096, 192 at 7680 and above, and none below +/// 2048 (the legacy sizes this crate verifies with but will not sign with). +pub const fn modulus_strength(limbs: usize) -> SecurityStrength { + let bits = limbs * 64; + if bits >= 7680 { + SecurityStrength::_192bit + } else if bits >= 3072 { + SecurityStrength::_128bit + } else if bits >= 2048 { + SecurityStrength::_112bit + } else { + SecurityStrength::None + } +} + +/// A key layer failure as the error a key's `from_bytes` returns, keeping the message of a +/// decoding failure, which is the only kind the raw decoders produce. +pub(crate) fn decoding_error(e: SignatureError) -> KeyDecodingError { + match e { + SignatureError::DecodingError(msg) => KeyDecodingError(msg), + _ => KeyDecodingError("invalid RSA key encoding"), + } +} + +// A private-key operation checks its result (`rsa_core::crt_exp_checked`). The constructor +// above refuses a key whose `dP`, `dQ`, `qInv` or `e` is not its own, so a test of the check on +// one damaged component needs a key built past the constructor: the QUALITY_AND_STYLE.md +// exception for behaviour that cannot be reached through the public API. (A key with a +// composite prime does pass the constructor: `tests/keys_tests.rs` runs the check on one.) +#[cfg(test)] +mod tests { + use super::*; + + impl RsaPrivateComponents { + /// The components as a key, with `n = p * q` and nothing checked. + pub(crate) fn unvalidated( + p: &K::HalfLimbs, + q: &K::HalfLimbs, + d_p: &K::HalfLimbs, + d_q: &K::HalfLimbs, + q_inv: &K::HalfLimbs, + e: u64, + ) -> Self { + let mut key = Self { + p: Secret::new(), + q: Secret::new(), + d_p: Secret::new(), + d_q: Secret::new(), + q_inv: Secret::new(), + n: K::modulus_from_primes(p, q), + e, + }; + *key.p = *p; + *key.q = *q; + *key.d_p = *d_p; + *key.d_q = *d_q; + *key.q_inv = *q_inv; + key + } + } +} diff --git a/crypto/rsa/src/lib.rs b/crypto/rsa/src/lib.rs new file mode 100644 index 000000000..1b60c9165 --- /dev/null +++ b/crypto/rsa/src/lib.rs @@ -0,0 +1,448 @@ +//! RSA digital signatures, RSASSA-PKCS1-v1_5 and RSASSA-PSS (RFC 8017 §8), the RSASVE +//! key-encapsulation mechanism (NIST SP 800-56B Rev. 2 §7.2.1) and RSAES-OAEP key transport +//! (RFC 8017 §7.1, SP 800-56B Rev. 2 §7.2.2), built on +//! [`bouncycastle_ec`]'s constant-time limb arithmetic ([`bouncycastle_ec::nat`], +//! [`bouncycastle_ec::montgomery`]) rather than a dedicated bignum type, for the same +//! constant-time reasoning that motivates that crate's own custom-curve arithmetic: a modular +//! exponentiation over a secret exponent has to run in the same time regardless of the exponent's +//! value, which needs limbs of a fixed width known at compile time. +//! +//! # Scope +//! +//! Signature schemes, plus RSASVE as a KEM ([`rsasve`]; see below) and RSAES-OAEP for +//! transporting keys ([`rsaes_oaep`]). There is no RSAES-PKCS1-v1_5 encryption, and OAEP's +//! plaintext is always a key, not a message. A modulus size is a marker type at the +//! crate root, [`RSA2048`], [`RSA3072`], [`RSA4096`] and [`RSA8192`], which implement +//! [`size::RsaSize`] (the size's lengths and limb types) and [`size::RsaSigningSize`] (key +//! generation, the signing roles and the key-establishment roles); [`RSA1024`] and [`RSA1536`] +//! implement `RsaSize` only, so a private key, `keygen`, every signing-role impl and every +//! key-establishment role, encapsulation and key transport toward a public key included, are +//! absent for them at compile time rather than refused at run time: they verify signatures. +//! +//! The schemes are generic over the size and the hash: [`RSASSA_PKCS1_v1_5`](rsassa_pkcs1_v1_5::RSASSA_PKCS1_v1_5), +//! [`RSASSA_PSS`](rsassa_pss::RSASSA_PSS) with its parameters `P` (the mask and the +//! salt length: [`Conventional`](rsassa_pss::Conventional) unless spelled, what +//! [`PssHash`](rsassa_pss::PssHash) says the hash is conventionally paired with, MGF1 for SHA-2 +//! and SHA-3 and the XOF itself for SHAKE under RFC 8702; [`Mgf1`](rsassa_pss::Mgf1) and +//! [`NoSalt`](rsassa_pss::NoSalt) for the rest), named by scheme and hash +//! (`RSASSA-PSS-SHA256`) at the lesser of the modulus's and the hash's strength. A key is a +//! key for one of them: [`RsaPublicKey`](keys::RsaPublicKey) and +//! [`RsaPrivateKey`](keys::RsaPrivateKey) wrap the key material, +//! [`RsaPublicComponents`](keys::RsaPublicComponents) and +//! [`RsaPrivateComponents`](keys::RsaPrivateComponents), for the algorithm `A` their type +//! names, so `sk.sign(..)` and `pk.verify(..)` resolve from the key and a PSS key cannot sign +//! PKCS#1 v1.5, SP 800-57 Part 1 Rev. 5's one scheme per key pair in the type system, as the +//! ECDSA keys carry their curve and hash. The roles of [`bouncycastle_core::signature_key`] are +//! implemented once over the algorithm traits of [`rsassa`]: +//! [`SigningKey`](bouncycastle_core::signature_key::SigningKey) for the PSS schemes (a fresh +//! salt from the caller's RNG per signer), +//! [`DeterministicSigningKey`](bouncycastle_core::signature_key::DeterministicSigningKey) for +//! RSASSA-PKCS1-v1_5, and [`VerifyingKey`](bouncycastle_core::signature_key::VerifyingKey) for +//! all; one-shot or streaming, the same API shape as this workspace's ECDSA, SM2 and ML-DSA +//! crates. The key types implement +//! [`PrivateKey`](bouncycastle_core::traits::PrivateKey)/[`PublicKey`](bouncycastle_core::traits::PublicKey), +//! the bytes carrying no scheme, so a key file is decoded under the key type it is for. A +//! signing size generates a pair for one algorithm through [`size::SignatureKeyPair`] +//! (`RSA2048::generate_pss_signature_key_pair::(&mut rng)`, FIPS 186-5 Appendix A.1.3, +//! in [`keygen`]), the hash spelled at the call; [`RsaSigningSize::keygen`](size::RsaSigningSize::keygen) +//! gives the components, which `key::()` turns into a key. [`rsassa`] also exposes the +//! `*_from_hash` entry points that take the message hash rather than the message, for a caller +//! that already holds the digest. +//! +//! The size modules [`rsa_1024`] through [`rsa_8192`] are aliases over the markers +//! (`rsa_2048::RSASSA_PSS_SHA256` is `RSASSA_PSS`, `SIG_LEN` is +//! `RSA2048::K_LEN`), for code that works at one size; a key at one size is +//! `RsaPrivateKey`. +//! +//! RSASVE (SP 800-56B Rev. 2 §7.2.1; BC FIPS Java's `FipsRSA.KTS_SVE`, JCA `RSA-KAS-KEM`; +//! OpenSSL's `"RSASVE"` KEM operation) is [`RSASVE`](rsasve::RSASVE) over the same markers. +//! It implements [`bouncycastle_core`]'s +//! [`KEMEncapsulator`](bouncycastle_core::traits::KEMEncapsulator)/[`KEMDecapsulator`](bouncycastle_core::traits::KEMDecapsulator) +//! over its own key types ([`RsaKEMPublicKey`](rsasve::RsaKEMPublicKey) and +//! [`RsaKEMPrivateKey`](rsasve::RsaKEMPrivateKey)), which are kept apart from the signing +//! key types; see [`rsasve`]'s `# Key separation`. Key generation is `RSASVE::::keygen(rng)` +//! or [`size::KemKeyPair`] (`RSA2048::generate_kem_key_pair(&mut rng)`), the same FIPS 186-5 +//! generator the signature keys use. Over `()` the shared secret is RSASVE's raw secret value +//! `Z`, the full modulus length, which is not a derived key; over +//! [`KdfParams`](bouncycastle_core::kdf_params::KdfParams) naming an HKDF description, the +//! same keys run [`RSASVE_HKDF`](rsasve_kdf::RSASVE_HKDF) (`RSASVE-2048-HKDF-SHA256` and +//! so on) and hand out HKDF-Hash(salt, Z, info) at the length the parameters name, the +//! description readable by a key held in a token that runs both steps inside the device. +//! +//! # Usage Examples +//! +//! RSA-2048 with SHA-256 through the `bouncycastle_core` key role traits, spelled with the +//! [`rsa_2048`] aliases, the way code written against those traits (and this workspace's CLI) +//! uses every signature scheme. The key names its scheme, so the calls name nothing: +//! +//! ``` +//! use bouncycastle_core::signature_key::{DeterministicOneShotSigningKey, DeterministicSigningKey, OneShotSigningKey, OneShotVerifyingKey, SigningKey, VerifyingKey}; +//! use bouncycastle_core::traits::{PrivateKey, PublicKey, SignatureSigner, SignatureVerifier}; +//! use bouncycastle_rng::HashDRBG_SHA512; +//! use bouncycastle_rsa::keys::{RsaPrivateKey, RsaPublicKey}; +//! use bouncycastle_rsa::rsa_2048::{RSASSA_PKCS1_v1_5_SHA256, RSASSA_PSS_SHA256}; +//! # // A genuine RSA-2048 keypair (Wycheproof rsa_pkcs1_2048_sig_gen_test.json's first SHA-256 +//! # // group; `tests/rsa_2048_pkcs1_v1_5_tests.rs` has the full, sourced provenance). A fresh +//! # // pair comes from `RSA2048::generate_pkcs1_v1_5_signature_key_pair::(&mut rng)?` +//! # // instead -- a few seconds of Miller-Rabin in a debug build, so this example uses a fixed one. +//! # const P: [u64; 16] = [0x0ea36cfb3a5b18f1, 0x48a6e65332119129, 0x110ad9e7b48a1c93, 0x569156b90113e2e9, 0xe79813a575cfad9c, 0x69d659d143ec6f17, 0xe81e6bab5ddaa783, 0xbff1c5b80a69f788, 0x978f6c35814f50ee, 0xe6a289ad4cfbf78f, 0x34d5681e5809d415, 0xbb028bda42eeb5d2, 0x41c56e4de086b0d5, 0x58b8d1e24f3b55d0, 0xfb5248247d98cb7d, 0xdc431050f782e894]; +//! # const Q: [u64; 16] = [0x669f140cfbc20f25, 0xb97bb03677207d95, 0xfd4e06f3ed7299d4, 0x160f90536abc9492, 0xf5b131f39098f7bc, 0xae8d72c57088d7ab, 0x89b94fbde542aba9, 0x3d3f9880ec47d5e0, 0x1378a6868af3b7a0, 0x5544070beb057c94, 0x16611debc472fac4, 0xe500ffb79f5b8868, 0x308a5e32196603b2, 0xea5fb19eb4eabc38, 0x122273ae3222b598, 0xbd1a81e7977f9898]; +//! # const D_P: [u64; 16] = [0x209f33f09515d7c1, 0xb4a9b37656917205, 0x276933bb07e4efb9, 0x8c14019808e00414, 0x289f96da220711e5, 0xfbbd2923d31532fe, 0xc06b414e61c0e1e7, 0x4c23c4588488961d, 0x4dc48ae34514759c, 0x9c786961ae3e2c35, 0x497e8d9c650688e0, 0x18bf08472612dbe5, 0x8885fb161870ee12, 0xf21d7c1479d99d47, 0x9121d91952ffd1c7, 0xa94b528b28f29159]; +//! # const D_Q: [u64; 16] = [0xf7597ffb68011d8d, 0x7b3cc538c4bab8c9, 0xa8fa480a81a925af, 0x6d6ede7251a383bf, 0x8a63f788ce3a0f85, 0x0b920502eb478bc9, 0x7e37e755edfe70d9, 0x9cf9948422a16555, 0x0d6d9ea1f2ef71fd, 0xf7efa32ea0cb6e00, 0x0629b114ca7f780f, 0xcf51176359654348, 0x540cdcbd4ad35435, 0x31c02ff1a2bc437c, 0xff2503df78bafed5, 0x3af0e72a933aef09]; +//! # const Q_INV: [u64; 16] = [0x552fe4bfce945f7b, 0x67e50c999c67247b, 0xfb54ef17be3b2853, 0x241f5921b5ad3983, 0x02de5eccd143cf31, 0x74e45f6fcc60f216, 0xafa5428a74f12708, 0x88d42294b6a2759b, 0xe923e1097c0c562f, 0xc968b48a91c38b5b, 0x933e85179c0320b0, 0x7993d0445f758d51, 0x9bfc042ee0924b1b, 0x41f956d90fa8a793, 0xee7a87b6483a66ee, 0x2640fbfbcfefb163]; +//! let sk = RsaPrivateKey::::from_crt_components(&P, &Q, &D_P, &D_Q, &Q_INV, 0x10001)?; +//! let pk = RsaPublicKey::::new(sk.n(), sk.e())?; +//! let mut rng = HashDRBG_SHA512::new_from_os(); +//! +//! // One-shot. RSA takes no context: `ctx` is `None` or empty, and anything else is refused. +//! // PKCS#1 v1.5 draws nothing, so it is the deterministic role. +//! let signature = sk.sign_deterministic(b"the message to sign", None)?; +//! pk.verify(b"the message to sign", None, &signature)?; +//! +//! // Streaming: the message arrives in chunks and is hashed as it goes. +//! let mut signer = sk.create_signer_deterministic(None)?; +//! signer.do_update(b"the message "); +//! signer.do_update(b"to sign"); +//! let streamed = signer.do_final()?; +//! assert_eq!(streamed, signature); // PKCS#1 v1.5 is deterministic +//! +//! let mut verifier = pk.create_verifier(None)?; +//! verifier.do_update(b"the message to sign"); +//! verifier.do_verify_final(&streamed)?; +//! +//! // `verify` takes a `&[u8]`: a signature of the wrong length is rejected for its length +//! // (RFC 8017 §8.2.2 step 1), one over a different message as invalid. +//! assert!(pk.verify(b"the message to sign", None, &signature[1..]).is_err()); +//! assert!(pk.verify(b"a different message", None, &signature).is_err()); +//! +//! // The same material as an RSASSA-PSS key is another key: a key is for one scheme, and the +//! // components are what the two share. PSS draws its salt from the RNG handed to the signer, +//! // so two signatures differ. +//! let sk_pss = sk.components().key::(); +//! let pk_pss = pk.components().key::(); +//! let sig_a = sk_pss.sign(&mut rng, b"the message to sign", None)?; +//! let sig_b = sk_pss.sign(&mut rng, b"the message to sign", None)?; +//! assert_ne!(sig_a, sig_b); +//! pk_pss.verify(b"the message to sign", None, &sig_a)?; +//! pk_pss.verify(b"the message to sign", None, &sig_b)?; +//! +//! // A known-answer test replaces the drawn salt with the published one through `set_salt`, +//! // which makes the signature a function of the key and message alone. +//! let mut signer = sk_pss.create_signer(&mut rng, None)?; +//! signer.set_salt([0x42u8; 32]); +//! signer.do_update(b"the message to sign"); +//! let sig_d = signer.do_final()?; +//! let mut signer = sk_pss.create_signer(&mut rng, None)?; +//! signer.set_salt([0x42u8; 32]); +//! signer.do_update(b"the message to sign"); +//! assert_eq!(signer.do_final()?, sig_d); +//! pk_pss.verify(b"the message to sign", None, &sig_d)?; +//! +//! // Keys round-trip through the traits' raw fixed-width encoding (see `keys`'s docs); the +//! // bytes carry no scheme, so they are decoded under the key type they are for. +//! let pk_again = RsaPublicKey::::from_bytes(&pk.encode())?; +//! assert_eq!(pk_again, pk); +//! let sk_again = RsaPrivateKey::::from_bytes(&sk.encode())?; +//! assert_eq!(sk_again, sk); +//! # Ok::<(), bouncycastle_core::errors::SignatureError>(()) +//! ``` +//! +//! RSA-1024 verification, the other major usage pattern: no private key, and so no signing role, +//! exists for this size at all (see `# Scope` above), only `VerifyingKey` on a key typed with +//! the scheme it checks, for signatures produced +//! elsewhere -- here, one of Wycheproof's own genuine `rsa_pkcs1_1024_sig_gen_test.json` +//! signatures (`tests/rsa_1024_tests.rs` has the full, sourced provenance): +//! +//! ``` +//! use bouncycastle_core::signature_key::{OneShotVerifyingKey, VerifyingKey}; +//! use bouncycastle_rsa::keys::RsaPublicKey; +//! use bouncycastle_rsa::rsa_1024::RSASSA_PKCS1_v1_5_SHA256; +//! # const N: [u64; 16] = [0xd00343468eaacfbf, 0xb7c7044cc202dcca, 0x9686f30f478db649, 0x5179b54951fff6aa, 0xbabb14f550d5d0dd, 0x5405db7c5c8f4cf6, 0x9816e2eda41fd7b9, 0xb31b6abd805bace9, 0xb909dd0f4c6014f2, 0x9c8a5810b6d05990, 0x40760d1f23fe9250, 0x90adb011a919575a, 0x45e48572113cab28, 0xcb9ca9ec12000fc8, 0x91b4fcaf62a14595, 0xac9048a7a4f560af]; +//! let sig = bouncycastle_core::hex::decode("41339884a9b3940e8488d666bb158063c6a2a2717cae7f564834a876fcbf7098ecf3acbfabf37d38a8e6127b1e313744f1f896e165efdaea0b2e7673867842b9e94db0868ed9a92bcdcb370a4e20ff275c82595e4400a8b9e9f12482f014846b48216f321266ae6ae6338dbcdc41b711e483e6e3e728772e7f9f5ef95c30196b").unwrap(); +//! let msg = [0u8; 20]; // Wycheproof's own genuine message for this signature. +//! let pk = RsaPublicKey::::new(&N, 0x10001)?; +//! pk.verify(&msg, None, &sig)?; +//! # Ok::<(), bouncycastle_core::errors::SignatureError>(()) +//! ``` +//! +//! RSASVE through the `bouncycastle_core` KEM roles on the key types ([`rsa_2048::RSASVE`] is the +//! algorithm they name). The shared secret is +//! the raw `Z`, which goes through a KDF, as SP 800-56B's KAS1/KAS2 schemes require, before it is +//! used as a key: +//! +//! ``` +//! use bouncycastle_core::key_material::KeyMaterialTrait; +//! use bouncycastle_core::kem_key::{DecapsulatingKey, EncapsulatingKey}; +//! use bouncycastle_core::traits::KDF; +//! use bouncycastle_rsa::rsa_2048::{RSA2048KEMPrivateKey, RSA2048KEMPublicKey, CT_LEN}; +//! use bouncycastle_rng::DefaultRNG; +//! # const P: [u64; 16] = [0x0ea36cfb3a5b18f1, 0x48a6e65332119129, 0x110ad9e7b48a1c93, 0x569156b90113e2e9, 0xe79813a575cfad9c, 0x69d659d143ec6f17, 0xe81e6bab5ddaa783, 0xbff1c5b80a69f788, 0x978f6c35814f50ee, 0xe6a289ad4cfbf78f, 0x34d5681e5809d415, 0xbb028bda42eeb5d2, 0x41c56e4de086b0d5, 0x58b8d1e24f3b55d0, 0xfb5248247d98cb7d, 0xdc431050f782e894]; +//! # const Q: [u64; 16] = [0x669f140cfbc20f25, 0xb97bb03677207d95, 0xfd4e06f3ed7299d4, 0x160f90536abc9492, 0xf5b131f39098f7bc, 0xae8d72c57088d7ab, 0x89b94fbde542aba9, 0x3d3f9880ec47d5e0, 0x1378a6868af3b7a0, 0x5544070beb057c94, 0x16611debc472fac4, 0xe500ffb79f5b8868, 0x308a5e32196603b2, 0xea5fb19eb4eabc38, 0x122273ae3222b598, 0xbd1a81e7977f9898]; +//! # const D_P: [u64; 16] = [0x209f33f09515d7c1, 0xb4a9b37656917205, 0x276933bb07e4efb9, 0x8c14019808e00414, 0x289f96da220711e5, 0xfbbd2923d31532fe, 0xc06b414e61c0e1e7, 0x4c23c4588488961d, 0x4dc48ae34514759c, 0x9c786961ae3e2c35, 0x497e8d9c650688e0, 0x18bf08472612dbe5, 0x8885fb161870ee12, 0xf21d7c1479d99d47, 0x9121d91952ffd1c7, 0xa94b528b28f29159]; +//! # const D_Q: [u64; 16] = [0xf7597ffb68011d8d, 0x7b3cc538c4bab8c9, 0xa8fa480a81a925af, 0x6d6ede7251a383bf, 0x8a63f788ce3a0f85, 0x0b920502eb478bc9, 0x7e37e755edfe70d9, 0x9cf9948422a16555, 0x0d6d9ea1f2ef71fd, 0xf7efa32ea0cb6e00, 0x0629b114ca7f780f, 0xcf51176359654348, 0x540cdcbd4ad35435, 0x31c02ff1a2bc437c, 0xff2503df78bafed5, 0x3af0e72a933aef09]; +//! # const Q_INV: [u64; 16] = [0x552fe4bfce945f7b, 0x67e50c999c67247b, 0xfb54ef17be3b2853, 0x241f5921b5ad3983, 0x02de5eccd143cf31, 0x74e45f6fcc60f216, 0xafa5428a74f12708, 0x88d42294b6a2759b, 0xe923e1097c0c562f, 0xc968b48a91c38b5b, 0x933e85179c0320b0, 0x7993d0445f758d51, 0x9bfc042ee0924b1b, 0x41f956d90fa8a793, 0xee7a87b6483a66ee, 0x2640fbfbcfefb163]; +//! // The same key material as above, as key-establishment keys. A fresh pair comes from +//! // `RSASVE::keygen()?` instead. +//! let sk = RSA2048KEMPrivateKey::from_crt_components(&P, &Q, &D_P, &D_Q, &Q_INV, 65537)?; +//! let pk = RSA2048KEMPublicKey::new(sk.n(), sk.e())?; +//! +//! // The encapsulating party: a fresh secret value Z and its ciphertext C = z^e mod n. +//! let (z, ct) = pk.encaps(&mut DefaultRNG::default(), ())?; +//! assert_eq!(ct.len(), CT_LEN); +//! +//! // The private-key holder recovers the same Z from C. +//! let z_again = sk.decaps(&ct, ())?; +//! assert_eq!(z_again, z); +//! +//! // Z is a shared secret, not a key: derive the key actually used, here with HKDF-SHA-256 +//! // (SP 800-56C Rev. 2's two-step method), binding in whatever context the protocol defines. +//! let key = bouncycastle_sha2::hkdf::HKDF_SHA256::default() +//! .derive_key(&z, b"example protocol v1", 32) +//! .expect("HKDF accepts any non-empty input key"); +//! assert_eq!(key.key_len(), 32); +//! +//! // Or let the keys do it: over `KdfParams` naming the HKDF's description (its salt, absent +//! // here) and the info, the same keys run RSASVE-2048-HKDF-SHA256 and hand out that key. +//! use bouncycastle_core::kdf_params::{KdfParams, KeyLen}; +//! use bouncycastle_hkdf::HkdfDescription; +//! use bouncycastle_sha2::SHA256; +//! let hkdf = HkdfDescription::::new(); +//! let params = KdfParams::new(&hkdf, b"example protocol v1", KeyLen::<32>); +//! let (key_a, ct) = pk.encaps(&mut DefaultRNG::default(), params)?; +//! let key_b = sk.decaps(&ct, params)?; +//! assert_eq!(key_a, key_b); +//! assert_eq!(key_a.security_strength(), bouncycastle_core::security_strength::SecurityStrength::_112bit); +//! +//! // A ciphertext outside (1, n - 1) is an error (SP 800-56B §7.1.2.3); a wrong length is a +//! // type error, since the ciphertext is a `[u8; CT_LEN]`. +//! assert!(sk.decaps(&[0u8; CT_LEN], ()).is_err()); +//! +//! // RSAES-OAEP on the same keys, selected by its parameters: the label hash, MGF1's hash +//! // (the same unless spelled), the label, and the length of the key to transport. As a KEM +//! // the key is drawn here (KTS-OAEP-basic, SP 800-56B §9.2.3)... +//! use bouncycastle_rsa::rsaes_oaep::OaepParams; +//! let oaep = OaepParams::::new(b"example label"); +//! let (key_a, ct) = pk.encaps(&mut DefaultRNG::default(), oaep)?; +//! assert_eq!(sk.decaps(&ct, oaep)?, key_a); +//! +//! // ...and through the key-transport roles the caller supplies it, as CMS and JOSE do. +//! use bouncycastle_core::key_transport_key::{KeyTransportDecryptingKey, KeyTransportEncryptingKey}; +//! let ct = pk.transport(&mut DefaultRNG::default(), oaep, &key_a).expect("a 32-byte key fits"); +//! let mut key_c = bouncycastle_core::key_material::KeyMaterial::<32>::new(); +//! sk.recover_out(&ct, oaep, &mut key_c).expect("the ciphertext is ours"); +//! assert_eq!(key_c.ref_to_bytes(), key_a.ref_to_bytes()); +//! # Ok::<(), bouncycastle_core::errors::KEMError>(()) +//! ``` +//! +//! RSASSA-PSS-SHAKE128/256 (RFC 8702 §3.2.1: [`rsa_2048::RSASSA_PSS_SHAKE128`], +//! [`rsa_3072::RSASSA_PSS_SHAKE128`], [`rsa_4096::RSASSA_PSS_SHAKE256`], per §5's recommended +//! pairing) have exactly the shape of `RSASSA_PSS_SHA256` above, `set_salt` included -- see +//! [`rsa_2048`]'s own docs rather than a second, near-identical example here. +//! +//! # Status +//! +//! [`modexp`] (constant-time modular exponentiation over a runtime-supplied modulus), [`keys`] +//! (the CRT key types), the CRT-based RSASP1/RSAVP1 primitives (crate-private, in `rsa_core`), +//! RSASSA-PKCS1-v1_5 ([`rsassa_pkcs1_v1_5`]), and RSASSA-PSS ([`rsassa_pss`]) are implemented, +//! with SHA-256, SHA-384, and SHA-512 wired up at 2048/3072/4096/8192 (both directions), and +//! RSASSA-PKCS1-v1_5 alone at 1024 (SHA-256, SHA-384) and 1536 (verification only, per `# Scope` +//! above), and validated against genuine vectors: Wycheproof for every size except 8192, which +//! it has no key material for at all (cross-checked against BC Java instead); see +//! `tests/rsa__tests.rs` for the specifics at each size. Every pairing is an instantiation of the generic +//! schemes the key types' `SigningKey` / `DeterministicSigningKey` / `VerifyingKey` roles name +//! (see `# Scope`), exercised through `bouncycastle_core_test_framework`'s shared signature +//! conformance suite at each size. +//! +//! RSASSA-PSS-SHAKE128 and RSASSA-PSS-SHAKE256 (RFC 8702 §3.2.1 -- SHAKE128/SHAKE256 used +//! natively as both the message hash and the mask generation function, in place of a hash+MGF1 +//! split) are the same marker, `RSASSA_PSS`, under the [`Conventional`](rsassa_pss::Conventional) +//! parameters [`PssHash`](rsassa_pss::PssHash) gives a SHAKE, wired up for the pairings RFC 8702 +//! §5 recommends: SHAKE128 with RSA-2048/3072 ([`rsa_2048`], +//! [`rsa_3072`]) and SHAKE256 with RSA-4096 ([`rsa_4096`]), each validated against its own +//! genuine Wycheproof `rsa_pss_*_shake*_test.json` vectors. The spelled parameters, another +//! MGF1 hash or salt length ([`Mgf1`](rsassa_pss::Mgf1)) and no salt +//! ([`NoSalt`](rsassa_pss::NoSalt)), are validated against Wycheproof's +//! `rsa_pss_2048_sha512_mgf1sha256_32_params` and `rsa_pss_2048_sha256_mgf1_0` files. +//! +//! RSASVE ([`rsasve`]) is implemented at 2048/3072/4096/8192, and with its secret value derived +//! through HKDF over any HMAC hash ([`rsasve_kdf`]). It is validated against NIST +//! ACVP-Server's KAS-IFC-SSC (KAS1 at 2048, KAS2 at 3072, both directions) and SP 800-56B RSADP +//! (CRT keys at 2048/3072/4096, out-of-range ciphertexts included) vectors, and against OpenSSL +//! 3.0's `"RSASVE"` KEM operation at every size, 8192 included. See `tests/rsasve_tests.rs` for +//! the sources. +//! +//! # Memory Usage +//! +//! | Key Object | PK size on disk | PK size in memory | SK size on disk | SK size in memory | +//! |-------------------|------------------|--------------------|------------------|--------------------| +//! | RSA-1024 (verify-only) | 136 | 136 | -- | -- | +//! | RSA-1536 (verify-only) | 200 | 200 | -- | -- | +//! | RSA-2048 | 264 | 264 | 648 | 904 | +//! | RSA-3072 | 392 | 392 | 968 | 1352 | +//! | RSA-4096 | 520 | 520 | 1288 | 1800 | +//! | RSA-8192 | 1032 | 1032 | 2568 | 3592 | +//! +//! The RSASVE key types (`RsaKEMPublicKey`/`RsaKEMPrivateKey`) have the same encodings +//! and the same in-memory sizes as the signature key types above: each wraps one. An RSASVE +//! ciphertext and shared secret are each `nLen` bytes, the same as a signature (256/384/512/1024 +//! at 2048/3072/4096/8192). +//! +//! Peak stack usage, as measured by `bench_rsa_mem_usage` under `valgrind --tool=massif +//! --stacks=yes` (release build, x86-64): +//! +//! | Operation | RSA-2048 | RSA-8192 | +//! |----------------------------|----------|----------| +//! | PKCS#1 v1.5 sign (SHA-256) | 16456 | 53720 | +//! | RSASVE encaps | 12888 | 35672 | +//! | RSASVE decaps | 20552 | 59336 | +//! | OAEP encaps (SHA-256) | 12232 | 31816 | +//! | OAEP decaps (SHA-256) | 16536 | 59672 | +//! +//! All values are in bytes. "On disk" is the `PublicKey`/`PrivateKey` raw layout +//! ([`keys::RsaPublicComponents`]'s and [`keys::RsaPrivateComponents`]'s `# Encoding`: `n || e`, +//! and `p || q || dP || dQ || qInv || e` respectively); "in memory" is `core::mem::size_of`. A +//! signature is the same size as the modulus itself (`K::K_LEN`: 128/192/256/384/512/1024 for +//! 1024/1536/2048/3072/4096/8192). These numbers are produced by `mem_usage_benches`' +//! `bench_rsa_mem_usage` binary's `print_key_sizes()`; that binary is also the stack-usage +//! measurement harness (see its own doc comment for the `valgrind`/`massif` invocation) -- only +//! one representative (scheme, hash) pairing is profiled there per modulus size, since stack +//! usage is dominated by the modulus's own limb count, not by which hash or scheme fed into +//! RSASP1/RSAVP1's modular exponentiation. A `SignatureSigner` / `SignatureVerifier` worker +//! borrows its key for its lifetime and holds the hash state beside it. +//! +//! # 🚨 Security Considerations 🚨 +//! +//! - **RSASP1 (private-key signing) is not blinded against its input.** [`modexp`]'s `mod_pow` is +//! constant-time in the *exponent* (the CRT exponents `dP`/`dQ`), which defeats a pure timing +//! attack, but neither it nor `rsa_core::rsasp1` multiplies the message by a random blinding +//! factor before exponentiating and removes it afterward. An attacker able to mount a +//! chosen-message physical side-channel attack (power or cache analysis, not just wall-clock +//! timing) against many signatures under the same key may still be able to recover information +//! about `p`/`q`/`dP`/`dQ`, per Kocher (1996) and Boneh & Brumley (2003) -- see [`modexp`]'s own +//! docs for the exact boundary of what is and is not covered. +//! - **The result of every private-key operation is checked before it is released.** A +//! signature, a decapsulated secret value or a decrypted OAEP message is computed by the CRT +//! from two half-size exponentiations; were one of them wrong, through a fault in the +//! computation or an imported key with a composite factor, the result would be right modulo +//! one prime at most, and such a value must not leave the library. So the private key carries `e`, and the result `y` of +//! `x^d mod n` is returned only if `y^e mod n` is `x` again; otherwise signing fails with +//! `SignatureError::ComputationFault` and decapsulation or decryption with its one failure +//! error, and the result is wiped. The check costs one public exponentiation per operation. +//! It does not detect a fault that leaves the result correct, and it is not blinding. +//! - **Private-key operations wipe the stack they used.** Signing, decapsulation and decryption, +//! and the construction, decoding, encoding, cloning and generation of a private key, run in +//! a frame of their own whose stack is overwritten afterwards, because values derived from +//! the key pass through locals, return slots and spilled registers that no `Secret` names. +//! The wipes are sized by measurement for an optimised build on x86-64: an unoptimised +//! build's larger frames are not covered, and no test in the crate can see a wipe fall +//! short, which is what `dev_scripts/check_rsa_stack.sh` searches the stack for. +//! `keygen::is_probable_prime` wipes likewise; the bare [`modexp`] functions are building +//! blocks and do not. +//! - **A key the caller moves is the caller's to wipe.** Taking a private key out of the +//! `Result` a constructor or key generation returns (`unwrap`, `?`, `Ok(key)`, `Box::new`) is +//! such a move, and leaves the key's components in the caller's own frame; no public +//! constructor builds a key in place. The same holds for the bytes `encode` returns and the +//! key `clone` returns: the copy the caller holds is the caller's to wipe. A caller for whom that matters borrows the key from +//! the `Result` (`as_ref`) and lets the `Result` drop where it was returned, which left +//! nothing behind in the builds measured. +//! - **Imported keys are not validated for primality.** [`keys::RsaPrivateKey::from_crt_components`] +//! and decoding check that `p`/`q` are odd and distinct, that `dP`/`dQ`/`qInv` are in range, +//! that `n = p * q` has exactly the size's bit length (as the public key's constructor checks +//! of its `n`: a modulus whose top bit is clear is refused, at every size), and that the +//! components and `e` belong together (RFC 8017 §3.2's three congruences, in constant time). +//! They do not test `p` and `q` for primality, and a composite `p` or `q` can pass the result +//! check above on some inputs. [`keys::RsaPrivateComponents::validate`] is SP 800-56B Rev. 2 +//! §6.4.1.4.3's validation of a key pair, primality included, for a key from elsewhere; its +//! cost is that of some tens of private-key operations, so it is the caller's to ask for. Keys +//! from this crate's own `keygen` meet FIPS 186-5 Appendix A.1.1's criteria by construction. +//! - **Key generation is not constant-time.** Rejection sampling of prime candidates is +//! inherently data-dependent in how many candidates it draws and where each is rejected, and the +//! small-modulus arithmetic on candidates uses ordinary integer division -- see [`keygen`]'s docs +//! for exactly what is and is not constant-time there. Signing itself is unaffected. +//! - **RSASSA-PSS's salt is only as good as its source.** `SigningKey::create_signer` draws it +//! from the RNG it is handed, once per signer; `set_salt` on the signer takes the salt itself. Unlike ECDSA's per-message secret `k`, a repeated +//! or predictable PSS salt does not hand an attacker the private key by itself (there is no +//! algebraic relation analogous to ECDSA's nonce-reuse equation), but PSS's random-oracle +//! security argument (RFC 8017 §8.1, Appendix A.2.3's references) assumes the salt is drawn +//! fresh and unpredictably each time. Signing with a low-quality or unseeded RNG, or reusing a +//! fixed salt outside a test, weakens that argument even though it will not directly leak `d`. +//! - **`ctx` must be absent or empty.** RSASSA-PKCS1-v1_5 and RSASSA-PSS (RFC 8017 §8) have no +//! context input, so a non-empty `ctx` is refused with `SignatureError::LengthError` by +//! signing and by verifying, one-shot or streaming, rather than dropped. A protocol that +//! needs the binding puts the context in the message itself. +//! - **RSA-1024 and RSA-1536 are legacy sizes, exposed for verification only.** Both fall below +//! the 112-bit security level NIST SP 800-131A requires for new use (RSA-1024 offers roughly +//! 80 bits, RSA-1536 roughly 96); this crate offers no way to sign with either, or to +//! encapsulate or transport a key toward a public key of either size (see `# Scope`), +//! precisely so they can only be used to check signatures against legacy/third-party data, not +//! to produce new ones or to protect a key. +//! - **RSASVE's shared secret is the raw secret value `Z`, not a key.** SP 800-56B Rev. 2 uses +//! RSASVE only inside KAS1/KAS2, which always pass `Z` through a key-derivation method (§5.5, +//! SP 800-56C) together with the parties' identifiers and other context. `Z` is uniform on +//! `(1, n - 1)`, not on all `nLen`-byte strings, and nothing binds it to either party or to the +//! protocol. Use it only as KDF input. +//! - **RSASVE decapsulation does not authenticate the ciphertext.** Any `C` in `(1, n - 1)` +//! recovers *some* `Z`: RSASVE has no redundancy to check, so a corrupted or forged ciphertext +//! yields a different secret, not an error. Assurance that both sides hold the same key has to +//! come from key confirmation (SP 800-56B §5.6) or from the protocol's later use of the derived +//! key, and none of that is provided here. +//! - **RSASVE decapsulation is RSADP on attacker-chosen input, and it is not blinded.** The +//! RSASP1 bullet above applies here with more force: a ciphertext is chosen by whoever sends +//! it, so an attacker who can observe a physical side channel during decapsulation needs no +//! more than the ability to submit ciphertexts. SP 800-56B §7.2.1.3's note (Håstad-Näslund +//! bit security) is the related concern: the recovered `Z` must not leak through timing either. +//! `decaps` itself is constant-time in `Z`, but what the caller does with `Z` is up to the +//! caller. +//! - **Public exponents are limited to 64 bits.** SP 800-56B §6.2.1 allows +//! `65,537 <= e < 2^256`, but the keys hold `e` as a `u64`, so a key with a larger `e` cannot +//! be constructed. (ACVP's RSADP vectors use exponents of up to 56 bits.) +//! - **RSASVE key validation is partial.** The KEM keys check `e >= 65,537` on top of +//! the signature keys' checks, the modulus's exact bit length among them. The KEM keys do not +//! run SP 800-89's remaining plausibility tests, and full RSA public-key validation is not +//! specified by SP 800-56B at all. See [`rsasve`]'s `# Key validation`. +//! - **RSASSA-PSS's mask and salt length are the key's.** The conventional parameters are MGF1 +//! over the message hash and a salt one hash output long (RFC 8017 §8.1's recommendation, §9.1 +//! note 4's "typical" choice); another MGF1 hash, another salt length or no salt is spelled in +//! the key's type (`rsassa_pss::Mgf1`, `rsassa_pss::NoSalt`), so a verifier never guesses them +//! and a signature made under other parameters is invalid under this key, not interoperable. +//! §8.1 allows the mask's hash to differ from the message hash and matches them only against +//! hash substitution, which a key that names its hash prevents; the strength is the size's and +//! the message hash's. + +#![no_std] +#![forbid(unsafe_code)] +#![forbid(missing_docs)] + +mod codec; +mod eme_oaep; +mod emsa_pkcs1_v1_5; +mod emsa_pss; +pub mod keygen; +pub mod keys; +mod mgf1; +pub mod modexp; +pub mod rsa_1024; +pub mod rsa_1536; +pub mod rsa_2048; +pub mod rsa_3072; +pub mod rsa_4096; +pub mod rsa_8192; +mod rsa_core; +pub mod rsaes_oaep; +pub mod rsassa; +pub mod rsassa_pkcs1_v1_5; +pub mod rsassa_pss; +pub mod rsasve; +pub mod rsasve_kdf; +pub mod size; + +/// The private-key arithmetic a signing size routes, for `dev_scripts/rsa_ct_harness` to run +/// under memcheck with the key undefined. Compiled only under +/// `--cfg bouncycastle_rsa_ct_harness`, which `dev_scripts/check_rsa_ct.sh` sets: no build of +/// the library has it. +#[cfg(bouncycastle_rsa_ct_harness)] +pub mod ct_harness { + pub use crate::size::sealed::PrivateKeyEngine; +} + +pub use size::{RSA1024, RSA1536, RSA2048, RSA3072, RSA4096, RSA8192}; diff --git a/crypto/rsa/src/mgf1.rs b/crypto/rsa/src/mgf1.rs new file mode 100644 index 000000000..19fa533c7 --- /dev/null +++ b/crypto/rsa/src/mgf1.rs @@ -0,0 +1,140 @@ +//! MGF1 (RFC 8017 Appendix B.2.1), a mask generation function based on a hash function, in the +//! two shapes this crate calls it in: [`mgf1`] for EMSA-PSS, whose seed is a hash output and +//! whose mask is wanted on its own, and [`mgf1_xor`] for EME-OAEP, whose seeds are of any length +//! and whose masks are XORed into what they mask. + +use bouncycastle_core::traits::{HashAlgParams, HashOneShot}; +use bouncycastle_utils::secret::Secret; + +/// The largest hash output MGF1 is used with here, SHA-512's. +pub(crate) const MAX_HASH_LEN: usize = 64; + +/// MGF1 over `H` (RFC 8017 Appendix B.2.1): `mask` filled with `Hash(seed || C)` for the +/// counter `C` from 0, four big-endian bytes each, the last block truncated. `seed` is a hash +/// output here (`H::OUTPUT_LEN` bytes, EMSA-PSS's `H`). +pub fn mgf1(seed: &[u8], mask: &mut [u8]) { + debug_assert!(seed.len() + 4 <= MAX_HASH_LEN + 4, "mgf1: seed longer than a hash output"); + let h_len = H::OUTPUT_LEN; + let mut input = [0u8; MAX_HASH_LEN + 4]; + input[..seed.len()].copy_from_slice(seed); + let mut block = [0u8; MAX_HASH_LEN]; + let mut offset = 0; + let mut counter: u32 = 0; + while offset < mask.len() { + input[seed.len()..seed.len() + 4].copy_from_slice(&counter.to_be_bytes()); + H::hash_out(&input[..seed.len() + 4], &mut block[..h_len]); + let take = core::cmp::min(h_len, mask.len() - offset); + mask[offset..offset + take].copy_from_slice(&block[..take]); + offset += take; + counter += 1; + } +} + +/// MGF1 over `M` with a seed of any length, XORed into `target` (`target = target xor +/// MGF(seed, target.len())`), which is how EME-OAEP uses both of its masks (RFC 8017 §7.1.1 +/// steps 2.e to 2.h): one of its seeds is `maskedDB`, most of a modulus long, which [`mgf1`]'s +/// fixed input buffer does not hold. The hash block is in a `Secret`, wiped on return, and +/// nothing here branches on the seed or the mask. +pub(crate) fn mgf1_xor(seed: &[u8], target: &mut [u8]) { + let h_len = M::OUTPUT_LEN; + let mut block = Secret::<[u8; MAX_HASH_LEN]>::new(); + // "For counter from 0 to \ceil (maskLen / hLen) - 1": C = I2OSP (counter, 4), + // T = T || Hash(mgfSeed || C). Each chunk of the target takes one block of T. + for (counter, chunk) in target.chunks_mut(h_len).enumerate() { + let mut hash = M::default(); + hash.do_update(seed); + hash.do_update(&(counter as u32).to_be_bytes()); + hash.do_final_out(&mut block[..h_len]); + for (t, m) in chunk.iter_mut().zip(block.iter()) { + *t ^= m; + } + } +} + +#[cfg(test)] +mod tests { + //! `mgf1` is crate-private (only [`crate::emsa_pss`] needs it), so it is exercised here + //! rather than from `tests/` -- the same "high-risk code that cannot be reached through the + //! public API" exception `rsa_core`'s tests use. Every expected value below was computed with + //! a direct Python transliteration of RFC 8017 Appendix B.2.1's own steps (not from recall), + //! using `hashlib.sha256`. + + use super::*; + use bouncycastle_sha2::SHA256; + + const SEED: [u8; 32] = [ + 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, + 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, + 0x1e, 0x1f, + ]; + + const LONG_SEED_MASK: [u8; 40] = [ + 0x21, 0x6a, 0xa5, 0xdf, 0x88, 0xa3, 0xda, 0x51, 0x8c, 0x77, 0x98, 0x7f, 0x93, 0xb1, 0xf8, + 0x71, 0x9f, 0xda, 0xb1, 0x64, 0x12, 0x57, 0x29, 0x86, 0x4b, 0xa8, 0x8b, 0x80, 0xc3, 0xa7, + 0x70, 0x84, 0x2b, 0xe7, 0xb5, 0x93, 0x92, 0x67, 0x71, 0x7c, + ]; + + /// `MASK_LEN = 223`: the exact `DB_LEN` RSA-2048/SHA-256 PSS uses (`K_LEN - H_LEN - 1 = 256 - + /// 32 - 1`), spanning seven full 32-byte hash blocks (`ceil(223/32) = 7`) plus a truncated one. + #[test] + fn mgf1_matches_python_for_pss_2048_sha256_mask_length() { + let mut mask = [0u8; 223]; + mgf1::(&SEED, &mut mask); + let expected_prefix: [u8; 16] = [ + 0x70, 0xf4, 0x00, 0x3d, 0x52, 0xb6, 0xeb, 0x03, 0xda, 0x85, 0x2e, 0x93, 0x25, 0x6b, + 0x59, 0x86, + ]; + assert_eq!(&mask[..16], &expected_prefix); + let expected_suffix: [u8; 8] = [0xff, 0x1f, 0x1e, 0x99, 0x50, 0x22, 0x99, 0x60]; + assert_eq!(&mask[215..223], expected_suffix); + } + + /// `MASK_LEN = 10`, shorter than one hash block: exercises truncation of the very first block. + #[test] + fn mgf1_truncates_within_the_first_block() { + let mut mask = [0u8; 10]; + mgf1::(&SEED, &mut mask); + let expected: [u8; 10] = [0x70, 0xf4, 0x00, 0x3d, 0x52, 0xb6, 0xeb, 0x03, 0xda, 0x85]; + assert_eq!(mask, expected); + // Must agree with the longer mask's own prefix -- MGF1 is a genuine stream, not + // recomputed independently per length. + let mut longer = [0u8; 223]; + mgf1::(&SEED, &mut longer); + assert_eq!(mask, longer[..10]); + } + + /// `MASK_LEN = 70`, spanning three counter blocks (`ceil(70/32) = 3`) with truncation of the + /// last. + #[test] + fn mgf1_spans_multiple_counter_blocks() { + let mut mask = [0u8; 70]; + mgf1::(&SEED, &mut mask); + let mut longer = [0u8; 223]; + mgf1::(&SEED, &mut longer); + assert_eq!(mask, longer[..70]); + } + + /// `mgf1_xor` into zeros is the mask itself, and XORs into what is there. + #[test] + fn mgf1_xor_is_mgf1_xored_into_the_target() { + let mut mask = [0u8; 223]; + mgf1::(&SEED, &mut mask); + let mut target = [0u8; 223]; + mgf1_xor::(&SEED, &mut target); + assert_eq!(target, mask); + let mut target = [0xA5u8; 223]; + mgf1_xor::(&SEED, &mut target); + assert!(target.iter().zip(mask).all(|(t, m)| *t == 0xA5 ^ m)); + } + + /// A seed longer than a hash output, as EME-OAEP's `maskedDB` is. The expected value was + /// computed with a direct Python transliteration of RFC 8017 Appendix B.2.1 using + /// `hashlib.sha256`, over the seed 0x00, 0x01, ..., 0xDE (223 bytes) and a 40-byte mask. + #[test] + fn mgf1_xor_takes_a_long_seed() { + let seed: [u8; 223] = core::array::from_fn(|i| i as u8); + let mut target = [0u8; 40]; + mgf1_xor::(&seed, &mut target); + assert_eq!(target, LONG_SEED_MASK); + } +} diff --git a/crypto/rsa/src/modexp.rs b/crypto/rsa/src/modexp.rs new file mode 100644 index 000000000..58811b589 --- /dev/null +++ b/crypto/rsa/src/modexp.rs @@ -0,0 +1,615 @@ +//! Constant-time modular exponentiation over a runtime-supplied odd modulus, built on +//! [`bouncycastle_ec::nat`] and [`bouncycastle_ec::montgomery`]. +//! +//! Every curve in `bouncycastle-ec` treats its modulus as a per-curve compile-time constant, with +//! the Montgomery constant `n'` computed once, offline, and hard-coded. RSA's modulus is key +//! material supplied at runtime, so this module computes the Montgomery setup itself: +//! +//! * [`mont_n_prime`] derives `n' = -n0^-1 mod 2^64` from the modulus's low limb by Newton's +//! method (six doublings of precision from a one-bit-correct seed), rather than requiring it +//! precomputed. +//! * [`MontgomeryContext`]'s constructors additionally derive `R mod n` and `R^2 mod n` +//! (`R = 2^(64L)`) by repeated doubling-and-reduction, rather than requiring them precomputed. +//! +//! The modulus is public when it is RSA's `n` and secret when it is one of the primes `p`, `q` +//! of the CRT or a candidate prime in key generation, so the context has one constructor for +//! each: [`MontgomeryContext::for_secret_modulus`], constant time in the modulus, and +//! [`MontgomeryContext::for_public_modulus`], whose doublings branch on it -- the same reasoning +//! [`bouncycastle_ec::inverse_vartime`] documents for operating on public curve/scalar values. +//! [`mod_pow`] operates on an exponent that can be secret (the private +//! exponent `d`): it processes every one of the modulus's `64 * L` bits regardless of the +//! exponent's actual value or bit length, using Joye & Yen's Montgomery powering ladder (CHES +//! 2002, "The Montgomery Powering Ladder"), so it performs exactly one multiplication and one +//! squaring per bit, moved into place by a branch-free conditional swap rather than a branch on +//! the bit's value. [`mod_pow_public_exponent`] is for the public exponent `e` alone: it runs +//! over that exponent's own bits and branches on them. +//! +//! # 🚨 Security Considerations 🚨 +//! +//! [`mod_pow`] is constant-time in the *exponent*, which is what RSA signing needs (`d` is +//! secret). It is not blinded against the message/base: an attacker who can also mount a +//! chosen-message physical side-channel attack (power/cache analysis, not just timing) may still +//! learn about `d` from repeated calls with related bases, per Kocher (1996) and Boneh & Brumley +//! (2003). Neither this module nor `crate::rsa_core`'s CRT, which every private-key operation +//! runs, applies message blinding on top of it -- see the crate's +//! own `# Security Considerations` for what that means for this crate's signing operation. + +use bouncycastle_ec::montgomery; +use bouncycastle_ec::nat; +use bouncycastle_utils::ct::Condition; +use bouncycastle_utils::secret::{ZeroizablePrimitive, zeroize_in_place}; + +/// The relations between a width and its companions that every function here generic over +/// `L`, `L2` and `L21` needs: a product is `L2 = 2 * L` limbs and REDC's accumulator +/// `L21 = 2 * L + 1`. Stable Rust cannot compute one const parameter from another, so the +/// caller spells all three, and each public function evaluates this in a `const` block: a +/// triple that does not agree is an error when the function is instantiated, not an index out +/// of bounds when it runs. +pub(crate) const fn check_widths() { + assert!(L2 == 2 * L, "the double width L2 must be 2 * L"); + assert!(L21 == 2 * L + 1, "the accumulator width L21 must be 2 * L + 1"); +} + +/// `n' = -n0^-1 mod 2^64` for an odd `n0`, by Newton's method: `x` is correct to one bit at +/// `x = 1` (since `n0` is odd, `n0 * 1` is odd, i.e. `≡ 1 mod 2`), and each round of +/// `x <- x * (2 - n0 * x)` (all mod `2^64`, via wrapping arithmetic) doubles the number of +/// correct low bits, so six rounds carry it from one correct bit to all sixty-four +/// (`1, 2, 4, 8, 16, 32, 64`). +pub fn mont_n_prime(n0: u64) -> u64 { + debug_assert_eq!(n0 & 1, 1, "mont_n_prime needs an odd modulus"); + let mut inv = 1u64; + for _ in 0..6 { + inv = inv.wrapping_mul(2u64.wrapping_sub(n0.wrapping_mul(inv))); + } + inv.wrapping_neg() +} + +/// `(a * 2) mod n` for `a < n` and odd `n`, in variable time: doubling `a` can carry out of the +/// top limb or land in `[n, 2n)`, either of which means exactly one subtraction of `n` restores +/// the `< n` representative (it cannot need a second: `a < n` implies `2a < 2n`). The branch +/// reveals how `2a` compares with `n`, so `n` must be public. +fn double_mod_n_vartime(a: &[u64; L], n: &[u64; L]) -> [u64; L] { + let (doubled, carry) = nat::add(a, a); + let (diff, borrow) = nat::sub(&doubled, n); + if carry == 1 || borrow == 0 { diff } else { doubled } +} + +/// `2^bits mod n` for odd `n > 1`, by `bits` repeated doublings from `1`. Variable time in `n`, +/// like `double_mod_n_vartime`: for a public modulus only. +fn pow2_mod_vartime(bits: u32, n: &[u64; L]) -> [u64; L] { + let mut acc = [0u64; L]; + acc[0] = 1; + for _ in 0..bits { + acc = double_mod_n_vartime(&acc, n); + } + acc +} + +/// `2^bits mod n` for odd `n > 1`, as `pow2_mod_vartime` computes it, in constant time in `n`: +/// each doubling is [`ct_shift_in_bit_mod`]'s masked subtraction, and the trip count is `bits`, +/// which is public. +fn pow2_mod_ct(bits: u32, n: &[u64; L]) -> [u64; L] { + let mut acc = [0u64; L]; + acc[0] = 1; + for _ in 0..bits { + acc = ct_shift_in_bit_mod(&acc, 0, n); + } + acc +} + +/// Per-limb constant-time select: `mask.select` applied element-wise. +fn ct_select_array(mask: Condition, a: &[u64; L], b: &[u64; L]) -> [u64; L] { + let mut result = [0u64; L]; + for i in 0..L { + result[i] = mask.select(a[i], b[i]); + } + result +} + +/// Per-limb constant-time swap, in place. +fn ct_swap_array(mask: Condition, a: &mut [u64; L], b: &mut [u64; L]) { + for i in 0..L { + let (x, y) = mask.swap(a[i], b[i]); + a[i] = x; + b[i] = y; + } +} + +/// A Montgomery-form value of `< 2n` (the bound [`montgomery::redc`] returns), plus the extra bit +/// beyond its `L` limbs, reduced to the canonical `< n` representative. +/// +/// `extra` and `high` are never both large enough to matter independently: if `extra == 1` then +/// `high + 2^(64L) >= 2^(64L) > n`, so the value is always `>= n` in that case and a subtraction +/// mask of `extra == 1` alone would be correct for it; the `borrow == 0` (`high >= n`) arm handles +/// the remaining `extra == 0` case, so the two conditions ORed together cover exactly the "value +/// `>= n`" set. +fn redc_normalize( + t: &[u64; L2], + modulus: &[u64; L], + n_prime: u64, +) -> [u64; L] { + let (high, extra) = montgomery::redc::(t, modulus, n_prime); + let (diff, borrow) = nat::sub(&high, modulus); + // Mutating this `|` to `^` is an accepted equivalent, not a gap: the two masks are never both + // TRUE at once. `extra == 1` forces `high < n` (equivalently `borrow == 1`, so the second mask + // is FALSE) -- see the doc comment above -- because every caller's `t` comes from + // `montgomery::redc`'s own `< 2n` bound, never from an unconstrained 2L-limb value. + let subtract = Condition::::from_lsb(extra) | Condition::::from_lsb(borrow ^ 1); + ct_select_array(subtract, &diff, &high) +} + +fn mont_mul( + a: &[u64; L], + b: &[u64; L], + modulus: &[u64; L], + n_prime: u64, +) -> [u64; L] { + let t = montgomery::widening_mul::(a, b); + redc_normalize::(&t, modulus, n_prime) +} + +fn mont_square( + a: &[u64; L], + modulus: &[u64; L], + n_prime: u64, +) -> [u64; L] { + let t = montgomery::widening_square::(a); + redc_normalize::(&t, modulus, n_prime) +} + +fn to_montgomery( + a: &[u64; L], + ctx: &MontgomeryContext, +) -> [u64; L] { + let t = montgomery::widening_mul::(a, &ctx.r2_mod_n); + redc_normalize::(&t, &ctx.modulus, ctx.n_prime) +} + +fn from_montgomery( + a_bar: &[u64; L], + ctx: &MontgomeryContext, +) -> [u64; L] { + let mut padded = [0u64; L2]; + padded[..L].copy_from_slice(a_bar); + let result = redc_normalize::(&padded, &ctx.modulus, ctx.n_prime); + zeroize_in_place(&mut padded); + result +} + +/// `a * b mod ctx.modulus()`, for plain (non-Montgomery) `a`, `b`. Only `b` needs converting into +/// Montgomery form: `REDC(a * (b*R)) = a*b*R*R^-1 mod n = a*b mod n`, the same one-sided-conversion +/// trick [`mod_pow`] itself doesn't need (it stays in Montgomery form throughout its ladder). +/// `a` need only fit in `L` limbs, not be `< ctx.modulus()`, by the same `T < n*R` argument +/// `to_montgomery` relies on. +/// +/// `L2` is `2 * L` and `L21` is `2 * L + 1`, checked when the function is instantiated: +/// +/// ```compile_fail,E0080 +/// use bouncycastle_rsa::modexp::{MontgomeryContext, mul_mod}; +/// let ctx = MontgomeryContext::<2>::for_public_modulus(&[7, 0]).unwrap(); +/// let _ = mul_mod::<2, 5, 5>(&[3, 0], &[4, 0], &ctx); +/// ``` +/// +/// ``` +/// use bouncycastle_rsa::modexp::{MontgomeryContext, mul_mod}; +/// let ctx = MontgomeryContext::<2>::for_public_modulus(&[7, 0]).unwrap(); +/// assert_eq!(mul_mod::<2, 4, 5>(&[3, 0], &[4, 0], &ctx), [5, 0]); +/// ``` +pub fn mul_mod( + a: &[u64; L], + b: &[u64; L], + ctx: &MontgomeryContext, +) -> [u64; L] { + const { check_widths::() }; + let mut b_bar = to_montgomery::(b, ctx); + let mut t = montgomery::widening_mul::(a, &b_bar); + let result = redc_normalize::(&t, &ctx.modulus, ctx.n_prime); + zeroize_in_place(&mut b_bar); + zeroize_in_place(&mut t); + result +} + +/// `(a - b) mod modulus` for `a, b < modulus`, in constant time with respect to `modulus`: RSA's +/// CRT recombination (RFC 8017 §5.2.1 step 2.b.3) needs `(s1 - s2) mod p`, and `p` is private key +/// material, so -- unlike `double_mod_n_vartime`'s public-modulus reasoning -- this must not +/// branch on it. +pub fn sub_mod(a: &[u64; N], b: &[u64; N], modulus: &[u64; N]) -> [u64; N] { + let (diff, borrow) = nat::sub(a, b); + let (corrected, _) = nat::add(&diff, modulus); + let mask = Condition::::from_lsb(borrow); + ct_select_array(mask, &corrected, &diff) +} + +/// `(acc * 2 + bit) mod modulus` for `acc < modulus`, in constant time in all three: the +/// modulus can be secret (see [`reduce_wide`] and `pow2_mod_ct`). The modulus need not be odd: +/// [`mul_u64_mod`] reduces modulo `p - 1`. +fn ct_shift_in_bit_mod(acc: &[u64; N], bit: u64, modulus: &[u64; N]) -> [u64; N] { + let mut doubled = [0u64; N]; + let mut carry = bit; + for i in 0..N { + let next_carry = acc[i] >> 63; + // Mutating this `|` to `^` is an accepted equivalent, not a gap: `acc[i] << 1` always has + // bit 0 clear (a left shift's incoming bit), and `carry` is 0 or 1, so OR-ing it into that + // always-clear bit and XOR-ing it produce identical results. + doubled[i] = (acc[i] << 1) | carry; + carry = next_carry; + } + // Same accepted OR/XOR equivalence as `redc_normalize`, by the identical argument: `doubled`'s + // true value is `2*acc + bit < 2*modulus` (`acc < modulus`), so `carry == 1` (the bit that + // overflowed the top limb) forces the stored `doubled < 2*modulus - 2^(64N) < modulus`, i.e. + // `borrow == 1` (the other mask FALSE) whenever `carry == 1`. + let (diff, borrow) = nat::sub(&doubled, modulus); + let subtract = Condition::::from_lsb(carry) | Condition::::from_lsb(borrow ^ 1); + ct_select_array(subtract, &diff, &doubled) +} + +/// `value mod modulus` for a `WIDE`-limb `value` and a `NARROW`-limb nonzero `modulus`, in constant +/// time with respect to `modulus`. Unlike `pow2_mod_vartime`, which assumes a *public* +/// modulus (true of RSA's own `n`), this brings a value down to a CRT prime's width and the primes +/// are private key material: branching on their value here would leak them the same way branching +/// on the exponent would leak `d`. Used two ways in RSA's CRT recombination (RFC 8017 §5.2.1 step +/// 2.b): with `WIDE > NARROW`, to reduce the `n`-width message `m` down to `m mod p` before +/// exponentiating (step 2.b.1); and with `WIDE == NARROW`, to reduce `s2` (a residue mod `q`) down +/// to `s2 mod p` before the CRT subtraction (step 2.b.3). Bit-serial schoolbook long division: +/// every one of `value`'s `64 * WIDE` bits contributes one constant-time doubling-and-conditional- +/// subtract step. +pub fn reduce_wide( + value: &[u64; WIDE], + modulus: &[u64; NARROW], +) -> [u64; NARROW] { + let mut acc = [0u64; NARROW]; + for limb_index in (0..WIDE).rev() { + for bit_index in (0..64u32).rev() { + let bit = (value[limb_index] >> bit_index) & 1; + acc = ct_shift_in_bit_mod(&acc, bit, modulus); + } + } + acc +} + +/// `x * k mod modulus` for a small multiplier `k` and a nonzero `modulus` that need not be odd, +/// in constant time in `x` and `modulus`: the `N + 1`-limb product is reduced bit-serially, as +/// [`reduce_wide`] reduces. This is how a private key's constructor checks RFC 8017 §3.2's +/// `e * dP == 1 (mod (p - 1))`, whose modulus is even and so has no Montgomery context. +pub(crate) fn mul_u64_mod(x: &[u64; N], k: u64, modulus: &[u64; N]) -> [u64; N] { + let mut low = [0u64; N]; + let mut carry = 0u128; + for i in 0..N { + let t = u128::from(x[i]) * u128::from(k) + carry; + low[i] = t as u64; + carry = t >> 64; + } + let mut top = carry as u64; + let mut acc = [0u64; N]; + for bit_index in (0..64u32).rev() { + acc = ct_shift_in_bit_mod(&acc, (top >> bit_index) & 1, modulus); + } + for limb_index in (0..N).rev() { + for bit_index in (0..64u32).rev() { + acc = ct_shift_in_bit_mod(&acc, (low[limb_index] >> bit_index) & 1, modulus); + } + } + zeroize_in_place(&mut low); + zeroize_in_place(&mut top); + acc +} + +/// Precomputed Montgomery constants for a runtime-supplied odd modulus `n`, `L` limbs wide. +/// +/// Unlike every curve modulus in `bouncycastle-ec`, `n` here is not known until the key is +/// loaded, so these constants (see the module docs) are derived at construction time rather than +/// hard-coded. +#[derive(Clone, Copy)] +pub struct MontgomeryContext { + modulus: [u64; L], + n_prime: u64, + /// Montgomery form of `1`, i.e. `R mod n`. + r_mod_n: [u64; L], + /// `R^2 mod n`, used to bring a value into Montgomery form. + r2_mod_n: [u64; L], +} + +/// A context over a private modulus -- `p` or `q` in the CRT, a candidate prime in key +/// generation -- holds that modulus and constants derived from it, so it is built inside a +/// [`bouncycastle_utils::secret::Secret`] and scrubbed when dropped. One over the public `n` +/// gains nothing from this. +impl ZeroizablePrimitive for MontgomeryContext { + const ZEROED: Self = Self { modulus: [0; L], n_prime: 0, r_mod_n: [0; L], r2_mod_n: [0; L] }; +} + +// There is no plain `new`: a call names what its modulus is, so that a secret one handed to the +// variable-time constructor is wrong on the line that does it. +impl MontgomeryContext { + /// Builds the Montgomery context for a modulus that is secret: `p` or `q` of the CRT, or a + /// candidate prime. `modulus` must be odd and greater than 1, which the caller has + /// established: this constructor does not test it, since the test would be a branch on the + /// secret. Over an even modulus a debug build stops at an assertion, and a release build + /// returns a context that gives wrong answers, without a panic. + /// + /// Constant time in `modulus`: no branch, memory access or loop count depends on it. + /// `dev_scripts/check_rsa_ct.sh` runs this, and the CRT that uses it, under memcheck with + /// the secrets undefined. + pub fn for_secret_modulus(modulus: &[u64; L]) -> Self { + let n_prime = mont_n_prime(modulus[0]); + let r_mod_n = pow2_mod_ct(64 * L as u32, modulus); + let r2_mod_n = pow2_mod_ct(128 * L as u32, modulus); + Self { modulus: *modulus, n_prime, r_mod_n, r2_mod_n } + } + + /// Builds the Montgomery context for a modulus that is public: RSA's `n`. Returns `None` + /// if `modulus` is even (zero included); Montgomery reduction requires an odd modulus. + /// `modulus` must be greater than 1. The same context as [`Self::for_secret_modulus`] + /// builds. + /// + /// Variable time in `modulus`: its doublings branch on how the running value compares with + /// it. Never for `p`, `q` or anything else that is secret. + pub fn for_public_modulus(modulus: &[u64; L]) -> Option { + if modulus[0] & 1 == 0 { + return None; + } + let n_prime = mont_n_prime(modulus[0]); + let r_mod_n = pow2_mod_vartime(64 * L as u32, modulus); + let r2_mod_n = pow2_mod_vartime(128 * L as u32, modulus); + Some(Self { modulus: *modulus, n_prime, r_mod_n, r2_mod_n }) + } +} + +/// `base^exponent mod ctx.modulus()`, constant-time in `exponent`: every one of the modulus's +/// `64 * L` bits is processed, via Joye & Yen's Montgomery powering ladder (see the module docs). +/// +/// `base` must be `< ctx.modulus()`; callers reduce first if that is not already guaranteed (RSA +/// callers always pass an already-reduced value: a message digest padded to the modulus width, or +/// a signature, both taken modulo `n` by construction). +/// +/// `L2` is `2 * L` and `L21` is `2 * L + 1`, checked when the function is instantiated: +/// +/// ```compile_fail,E0080 +/// use bouncycastle_rsa::modexp::{MontgomeryContext, mod_pow}; +/// let ctx = MontgomeryContext::<2>::for_public_modulus(&[7, 0]).unwrap(); +/// let _ = mod_pow::<2, 4, 4>(&[3, 0], &[5, 0], &ctx); +/// ``` +/// +/// ``` +/// use bouncycastle_rsa::modexp::{MontgomeryContext, mod_pow}; +/// let ctx = MontgomeryContext::<2>::for_public_modulus(&[7, 0]).unwrap(); +/// assert_eq!(mod_pow::<2, 4, 5>(&[3, 0], &[5, 0], &ctx), [5, 0]); // 3^5 = 243 = 5 mod 7 +/// ``` +pub fn mod_pow( + base: &[u64; L], + exponent: &[u64; L], + ctx: &MontgomeryContext, +) -> [u64; L] { + const { check_widths::() }; + debug_assert_eq!(nat::sub(base, &ctx.modulus).1, 1, "mod_pow needs base < modulus"); + + let mut r0 = ctx.r_mod_n; + let mut r1 = to_montgomery::(base, ctx); + // The step's two products, declared here so one scrub after the ladder covers them. + let mut new_r0 = [0u64; L]; + let mut new_r1 = [0u64; L]; + + for limb_index in (0..L).rev() { + for bit_index in (0..64u32).rev() { + let mask = Condition::::is_bit_set(exponent[limb_index], bit_index); + ct_swap_array(mask, &mut r0, &mut r1); + new_r1 = mont_mul::(&r0, &r1, &ctx.modulus, ctx.n_prime); + new_r0 = mont_square::(&r0, &ctx.modulus, ctx.n_prime); + r0 = new_r0; + r1 = new_r1; + ct_swap_array(mask, &mut r0, &mut r1); + } + } + + let result = from_montgomery::(&r0, ctx); + // The ladder's state is a function of the exponent's bits, so it is scrubbed before + // returning (QUALITY_AND_STYLE.md's rule on secret-holding locals). The products inside + // `mont_mul` and `mont_square` are the callee intermediates that rule does not reach. + zeroize_in_place(&mut r0); + zeroize_in_place(&mut r1); + zeroize_in_place(&mut new_r0); + zeroize_in_place(&mut new_r1); + result +} + +/// `base^exponent mod ctx.modulus()` for a public exponent, RSA's `e`: left-to-right square and +/// multiply over the exponent's own bits, from its highest set bit down, so the cost is that of +/// the exponent and not of the modulus's width as [`mod_pow`]'s is. `base` need only fit in `L` +/// limbs. +/// +/// Variable time in `exponent`, whose bits decide how many squarings are made and where the +/// multiplications fall: never for a private exponent. Constant time in `base`, which can be +/// secret (RSASVE's secret value, a recovered message): the sequence of operations is a +/// function of the exponent alone, and each is the same Montgomery product `mod_pow` uses. +/// +/// `L2` is `2 * L` and `L21` is `2 * L + 1`, checked when the function is instantiated: +/// +/// ```compile_fail,E0080 +/// use bouncycastle_rsa::modexp::{MontgomeryContext, mod_pow_public_exponent}; +/// let ctx = MontgomeryContext::<2>::for_public_modulus(&[7, 0]).unwrap(); +/// let _ = mod_pow_public_exponent::<2, 3, 5>(&[3, 0], 5, &ctx); +/// ``` +/// +/// ``` +/// use bouncycastle_rsa::modexp::{MontgomeryContext, mod_pow_public_exponent}; +/// let ctx = MontgomeryContext::<2>::for_public_modulus(&[7, 0]).unwrap(); +/// assert_eq!(mod_pow_public_exponent::<2, 4, 5>(&[3, 0], 5, &ctx), [5, 0]); +/// ``` +pub fn mod_pow_public_exponent( + base: &[u64; L], + exponent: u64, + ctx: &MontgomeryContext, +) -> [u64; L] { + const { check_widths::() }; + let mut base_bar = to_montgomery::(base, ctx); + // Montgomery form of 1, so that an exponent of zero gives 1. + let mut acc = ctx.r_mod_n; + for bit_index in (0..u64::BITS - exponent.leading_zeros()).rev() { + acc = mont_square::(&acc, &ctx.modulus, ctx.n_prime); + if (exponent >> bit_index) & 1 == 1 { + acc = mont_mul::(&acc, &base_bar, &ctx.modulus, ctx.n_prime); + } + } + let result = from_montgomery::(&acc, ctx); + // Powers of the base, which can be secret: scrubbed as `mod_pow` scrubs its ladder. The + // values `acc` held before its last assignment are not reached. + zeroize_in_place(&mut base_bar); + zeroize_in_place(&mut acc); + result +} + +// A context's constants are private, so that the two constructors build the same context -- +// and that each is right -- is not something `tests/` can see: the QUALITY_AND_STYLE.md +// exception for private state with known answers. The answers are Python's (`-pow(n, -1, +// 2**64) % 2**64`, `2**(64*L) % n`, `2**(128*L) % n`). +#[cfg(test)] +mod tests { + use super::*; + + // `check_widths` runs in `const` blocks, where a failure is a build error that only the + // `compile_fail` doctests on the public functions can show. Called at run time it is an + // ordinary function, so its two relations are pinned here as well. + #[test] + fn check_widths_takes_the_consistent_triples() { + check_widths::<1, 2, 3>(); + check_widths::<16, 32, 33>(); + check_widths::<128, 256, 257>(); + } + + #[test] + #[should_panic(expected = "the double width L2 must be 2 * L")] + fn check_widths_refuses_a_short_double_width() { + check_widths::<2, 3, 5>(); + } + + #[test] + #[should_panic(expected = "the double width L2 must be 2 * L")] + fn check_widths_refuses_a_long_double_width() { + check_widths::<2, 5, 5>(); + } + + #[test] + #[should_panic(expected = "the accumulator width L21 must be 2 * L + 1")] + fn check_widths_refuses_a_short_accumulator() { + check_widths::<2, 4, 4>(); + } + + #[test] + #[should_panic(expected = "the accumulator width L21 must be 2 * L + 1")] + fn check_widths_refuses_a_long_accumulator() { + check_widths::<2, 4, 6>(); + } + + /// A modulus, then its `n'`, `R mod n` and `R^2 mod n`. + type Case = ([u64; L], u64, [u64; L], [u64; L]); + + fn assert_both_constructors_give(cases: &[Case]) { + for (n, n_prime, r_mod_n, r2_mod_n) in cases { + for ctx in [ + MontgomeryContext::for_secret_modulus(n), + MontgomeryContext::for_public_modulus(n).unwrap(), + ] { + assert_eq!(ctx.modulus, *n); + assert_eq!(ctx.n_prime, *n_prime, "n' for {n:x?}"); + assert_eq!(ctx.r_mod_n, *r_mod_n, "R mod n for {n:x?}"); + assert_eq!(ctx.r2_mod_n, *r2_mod_n, "R^2 mod n for {n:x?}"); + } + } + } + + #[test] + fn both_constructors_give_the_known_constants() { + assert_both_constructors_give::<2>(&[ + // 2^128 - 1: every limb all ones. + ([0xffffffffffffffff, 0xffffffffffffffff], 0x0000000000000001, [1, 0], [1, 0]), + // 2^127 + 1: just above 2^(k-1), the low limb all but zero. + ( + [0x0000000000000001, 0x8000000000000000], + 0xffffffffffffffff, + [0xffffffffffffffff, 0x7fffffffffffffff], + [4, 0], + ), + // The top limb all ones, the low limb 1. + ( + [0x0000000000000001, 0xffffffffffffffff], + 0xffffffffffffffff, + [0xffffffffffffffff, 0x0000000000000000], + [0x0000000000000001, 0xfffffffffffffffe], + ), + // The top limb all ones over an arbitrary low limb. + ( + [0x123456789abcdef1, 0xffffffffffffffff], + 0x8848c2974d33adef, + [0xedcba9876543210f, 0x0000000000000000], + [0xca4ab582281edee1, 0xdce2b9eafe7ceefa], + ), + // 2^127 - 1: the top bit clear. + ([0xffffffffffffffff, 0x7fffffffffffffff], 0x0000000000000001, [2, 0], [4, 0]), + // 3: far short of the width. + ([3, 0], 0x5555555555555555, [1, 0], [1, 0]), + // An arbitrary full-length value. + ( + [0x9e3779b97f4a7c15, 0xd1b54a32d192ed03], + 0x0e217c1e66c88cc3, + [0x61c8864680b583eb, 0x2e4ab5cd2e6d12fc], + [0xefccadf490c04b25, 0xb0ba6db3c8cd9e51], + ), + ]); + assert_both_constructors_give::<4>(&[ + // 2^255 + 1: just above 2^(k-1), the low limbs zero but for bit 0. + ( + [1, 0, 0, 0x8000000000000000], + 0xffffffffffffffff, + [0xffffffffffffffff, 0xffffffffffffffff, 0xffffffffffffffff, 0x7fffffffffffffff], + [4, 0, 0, 0], + ), + // The top limb all ones, the low limbs zero but for bit 0. + ( + [1, 0, 0, 0xffffffffffffffff], + 0xffffffffffffffff, + [0xffffffffffffffff, 0xffffffffffffffff, 0xffffffffffffffff, 0], + [0x0000000000000001, 0xffffffffffffffff, 0xfffffffffffffffe, 0xfffffffffffffffd], + ), + // 2^256 - 189. + ( + [0xffffffffffffff43, 0xffffffffffffffff, 0xffffffffffffffff, 0xffffffffffffffff], + 0xa53fa94fea53fa95, + [0xbd, 0, 0, 0], + [0x8b89, 0, 0, 0], + ), + ]); + } + + /// The two constructors agree limb for limb at a CRT prime's width, RSA-2048's 16 limbs, + /// over 64 moduli stepped from a fixed seed (SplitMix64's increment and mixer, as a source + /// of varied limbs, not of randomness), each forced odd and, on alternate rounds, given a + /// top limb of all ones or of only its top bit. + #[test] + fn both_constructors_agree_at_a_prime_width() { + let mut state = 0x243f6a8885a308d3u64; + let mut next = || { + state = state.wrapping_add(0x9e3779b97f4a7c15); + let mut z = state; + z = (z ^ (z >> 30)).wrapping_mul(0xbf58476d1ce4e5b9); + z = (z ^ (z >> 27)).wrapping_mul(0x94d049bb133111eb); + z ^ (z >> 31) + }; + for round in 0..64 { + let mut n = [0u64; 16]; + for limb in n.iter_mut() { + *limb = next(); + } + n[0] |= 1; + match round % 4 { + 1 => n[15] = u64::MAX, + 2 => n[15] = 1 << 63, + _ => {} + } + let secret = MontgomeryContext::for_secret_modulus(&n); + let public = MontgomeryContext::for_public_modulus(&n).unwrap(); + assert_eq!(secret.modulus, public.modulus); + assert_eq!(secret.n_prime, public.n_prime); + assert_eq!(secret.r_mod_n, public.r_mod_n, "R mod n for {n:x?}"); + assert_eq!(secret.r2_mod_n, public.r2_mod_n, "R^2 mod n for {n:x?}"); + } + } +} diff --git a/crypto/rsa/src/rsa_1024.rs b/crypto/rsa/src/rsa_1024.rs new file mode 100644 index 000000000..8d76162c9 --- /dev/null +++ b/crypto/rsa/src/rsa_1024.rs @@ -0,0 +1,20 @@ +//! RSA-1024: the generic types at this size, as aliases over the marker [`RSA1024`]: +//! the public key and the PKCS#1 v1.5 verifiers (this size is verification only; see the crate's `# Scope`). +//! Every (scheme, hash) pairing is an algorithm marker the key role traits are implemented over. + +use crate::rsassa_pkcs1_v1_5::RSASSA_PKCS1_v1_5; +pub use crate::size::RSA1024; +use crate::size::RsaSize; +use bouncycastle_sha2::{SHA256, SHA384}; + +/// Encoded length of an RSA-1024 public key: `n || e`. +pub const PK_LEN: usize = RSA1024::PK_LEN; +/// Length of an RSA-1024 signature: the modulus's. +pub const SIG_LEN: usize = RSA1024::K_LEN; + +/// RSASSA-PKCS1-v1_5 with SHA-256 at RSA-1024. +#[allow(non_camel_case_types)] +pub type RSASSA_PKCS1_v1_5_SHA256 = RSASSA_PKCS1_v1_5; +/// RSASSA-PKCS1-v1_5 with SHA-384 at RSA-1024. +#[allow(non_camel_case_types)] +pub type RSASSA_PKCS1_v1_5_SHA384 = RSASSA_PKCS1_v1_5; diff --git a/crypto/rsa/src/rsa_1536.rs b/crypto/rsa/src/rsa_1536.rs new file mode 100644 index 000000000..1a09572b8 --- /dev/null +++ b/crypto/rsa/src/rsa_1536.rs @@ -0,0 +1,23 @@ +//! RSA-1536: the generic types at this size, as aliases over the marker [`RSA1536`]: +//! the public key and the PKCS#1 v1.5 verifiers (this size is verification only; see the crate's `# Scope`). +//! Every (scheme, hash) pairing is an algorithm marker the key role traits are implemented over. + +use crate::rsassa_pkcs1_v1_5::RSASSA_PKCS1_v1_5; +pub use crate::size::RSA1536; +use crate::size::RsaSize; +use bouncycastle_sha2::{SHA256, SHA384, SHA512}; + +/// Encoded length of an RSA-1536 public key: `n || e`. +pub const PK_LEN: usize = RSA1536::PK_LEN; +/// Length of an RSA-1536 signature: the modulus's. +pub const SIG_LEN: usize = RSA1536::K_LEN; + +/// RSASSA-PKCS1-v1_5 with SHA-256 at RSA-1536. +#[allow(non_camel_case_types)] +pub type RSASSA_PKCS1_v1_5_SHA256 = RSASSA_PKCS1_v1_5; +/// RSASSA-PKCS1-v1_5 with SHA-384 at RSA-1536. +#[allow(non_camel_case_types)] +pub type RSASSA_PKCS1_v1_5_SHA384 = RSASSA_PKCS1_v1_5; +/// RSASSA-PKCS1-v1_5 with SHA-512 at RSA-1536. +#[allow(non_camel_case_types)] +pub type RSASSA_PKCS1_v1_5_SHA512 = RSASSA_PKCS1_v1_5; diff --git a/crypto/rsa/src/rsa_2048.rs b/crypto/rsa/src/rsa_2048.rs new file mode 100644 index 000000000..b8891201a --- /dev/null +++ b/crypto/rsa/src/rsa_2048.rs @@ -0,0 +1,58 @@ +//! RSA-2048: the generic types at this size, as aliases over the marker [`RSA2048`]: +//! every (scheme, hash) pairing offered at this size, the lengths, and RSASVE; a key is +//! `RsaPrivateKey` and so on, and comes from the marker's generators. +//! Every (scheme, hash) pairing is an algorithm marker the key role traits are implemented over. +//! PSS's salt length is the hash's own output length throughout, RFC 8017 §9.1 note 4's +//! "typical" choice and Wycheproof's own `rsa_pss_*_mgf1__test.json`. + +use crate::rsassa_pkcs1_v1_5::RSASSA_PKCS1_v1_5; +use crate::rsassa_pss::RSASSA_PSS; +use crate::rsasve::{RsaKEMPrivateKey, RsaKEMPublicKey}; +pub use crate::size::RSA2048; +use crate::size::RsaSize; +use bouncycastle_sha2::{SHA256, SHA384, SHA512}; +use bouncycastle_sha3::SHAKE128; + +/// Encoded length of an RSA-2048 public key: `n || e`. +pub const PK_LEN: usize = RSA2048::PK_LEN; +/// Length of an RSA-2048 signature: the modulus's. +pub const SIG_LEN: usize = RSA2048::K_LEN; +/// Encoded length of an RSA-2048 private key: `p || q || dP || dQ || qInv || e`. +pub const SK_LEN: usize = RSA2048::SK_LEN; + +/// RSASSA-PKCS1-v1_5 with SHA-256 at RSA-2048. +#[allow(non_camel_case_types)] +pub type RSASSA_PKCS1_v1_5_SHA256 = RSASSA_PKCS1_v1_5; +/// RSASSA-PKCS1-v1_5 with SHA-384 at RSA-2048. +#[allow(non_camel_case_types)] +pub type RSASSA_PKCS1_v1_5_SHA384 = RSASSA_PKCS1_v1_5; +/// RSASSA-PKCS1-v1_5 with SHA-512 at RSA-2048. +#[allow(non_camel_case_types)] +pub type RSASSA_PKCS1_v1_5_SHA512 = RSASSA_PKCS1_v1_5; +/// RSASSA-PSS with SHA-256 (and MGF1 over it) at RSA-2048. +#[allow(non_camel_case_types)] +pub type RSASSA_PSS_SHA256 = RSASSA_PSS; +/// RSASSA-PSS with SHA-384 (and MGF1 over it) at RSA-2048. +#[allow(non_camel_case_types)] +pub type RSASSA_PSS_SHA384 = RSASSA_PSS; +/// RSASSA-PSS with SHA-512 (and MGF1 over it) at RSA-2048. +#[allow(non_camel_case_types)] +pub type RSASSA_PSS_SHA512 = RSASSA_PSS; +/// RSASSA-PSS with SHAKE128 as hash and mask (RFC 8702 §3.2.1, §5's pairing for this size) at RSA-2048. +#[allow(non_camel_case_types)] +pub type RSASSA_PSS_SHAKE128 = RSASSA_PSS; + +/// An RSA-2048 key-establishment private key. +pub type RSA2048KEMPrivateKey = RsaKEMPrivateKey; +/// An RSA-2048 key-establishment public key. +pub type RSA2048KEMPublicKey = RsaKEMPublicKey; +/// Length of an RSASVE-2048 ciphertext: `nLen`. +pub const CT_LEN: usize = RSA2048::K_LEN; +/// Length of an RSASVE-2048 shared secret, the secret value `Z`: `nLen`. +pub const SS_LEN: usize = RSA2048::K_LEN; +/// RSASVE at RSA-2048; `RSASVE::keygen` gives the KEM pair. +pub type RSASVE = crate::rsasve::RSASVE; +/// RSAES-OAEP at RSA-2048 with the label hash `H` and MGF1 over `M`; the key-establishment +/// keys above run it under [`OaepParams`](crate::rsaes_oaep::OaepParams). +#[allow(non_camel_case_types)] +pub type RSAES_OAEP = crate::rsaes_oaep::RSAES_OAEP; diff --git a/crypto/rsa/src/rsa_3072.rs b/crypto/rsa/src/rsa_3072.rs new file mode 100644 index 000000000..5c7a2ee9b --- /dev/null +++ b/crypto/rsa/src/rsa_3072.rs @@ -0,0 +1,58 @@ +//! RSA-3072: the generic types at this size, as aliases over the marker [`RSA3072`]: +//! every (scheme, hash) pairing offered at this size, the lengths, and RSASVE; a key is +//! `RsaPrivateKey` and so on, and comes from the marker's generators. +//! Every (scheme, hash) pairing is an algorithm marker the key role traits are implemented over. +//! PSS's salt length is the hash's own output length throughout, RFC 8017 §9.1 note 4's +//! "typical" choice and Wycheproof's own `rsa_pss_*_mgf1__test.json`. + +use crate::rsassa_pkcs1_v1_5::RSASSA_PKCS1_v1_5; +use crate::rsassa_pss::RSASSA_PSS; +use crate::rsasve::{RsaKEMPrivateKey, RsaKEMPublicKey}; +pub use crate::size::RSA3072; +use crate::size::RsaSize; +use bouncycastle_sha2::{SHA256, SHA384, SHA512}; +use bouncycastle_sha3::SHAKE128; + +/// Encoded length of an RSA-3072 public key: `n || e`. +pub const PK_LEN: usize = RSA3072::PK_LEN; +/// Length of an RSA-3072 signature: the modulus's. +pub const SIG_LEN: usize = RSA3072::K_LEN; +/// Encoded length of an RSA-3072 private key: `p || q || dP || dQ || qInv || e`. +pub const SK_LEN: usize = RSA3072::SK_LEN; + +/// RSASSA-PKCS1-v1_5 with SHA-256 at RSA-3072. +#[allow(non_camel_case_types)] +pub type RSASSA_PKCS1_v1_5_SHA256 = RSASSA_PKCS1_v1_5; +/// RSASSA-PKCS1-v1_5 with SHA-384 at RSA-3072. +#[allow(non_camel_case_types)] +pub type RSASSA_PKCS1_v1_5_SHA384 = RSASSA_PKCS1_v1_5; +/// RSASSA-PKCS1-v1_5 with SHA-512 at RSA-3072. +#[allow(non_camel_case_types)] +pub type RSASSA_PKCS1_v1_5_SHA512 = RSASSA_PKCS1_v1_5; +/// RSASSA-PSS with SHA-256 (and MGF1 over it) at RSA-3072. +#[allow(non_camel_case_types)] +pub type RSASSA_PSS_SHA256 = RSASSA_PSS; +/// RSASSA-PSS with SHA-384 (and MGF1 over it) at RSA-3072. +#[allow(non_camel_case_types)] +pub type RSASSA_PSS_SHA384 = RSASSA_PSS; +/// RSASSA-PSS with SHA-512 (and MGF1 over it) at RSA-3072. +#[allow(non_camel_case_types)] +pub type RSASSA_PSS_SHA512 = RSASSA_PSS; +/// RSASSA-PSS with SHAKE128 as hash and mask (RFC 8702 §3.2.1, §5's pairing for this size) at RSA-3072. +#[allow(non_camel_case_types)] +pub type RSASSA_PSS_SHAKE128 = RSASSA_PSS; + +/// An RSA-3072 key-establishment private key. +pub type RSA3072KEMPrivateKey = RsaKEMPrivateKey; +/// An RSA-3072 key-establishment public key. +pub type RSA3072KEMPublicKey = RsaKEMPublicKey; +/// Length of an RSASVE-3072 ciphertext: `nLen`. +pub const CT_LEN: usize = RSA3072::K_LEN; +/// Length of an RSASVE-3072 shared secret, the secret value `Z`: `nLen`. +pub const SS_LEN: usize = RSA3072::K_LEN; +/// RSASVE at RSA-3072; `RSASVE::keygen` gives the KEM pair. +pub type RSASVE = crate::rsasve::RSASVE; +/// RSAES-OAEP at RSA-3072 with the label hash `H` and MGF1 over `M`; the key-establishment +/// keys above run it under [`OaepParams`](crate::rsaes_oaep::OaepParams). +#[allow(non_camel_case_types)] +pub type RSAES_OAEP = crate::rsaes_oaep::RSAES_OAEP; diff --git a/crypto/rsa/src/rsa_4096.rs b/crypto/rsa/src/rsa_4096.rs new file mode 100644 index 000000000..68dd086e5 --- /dev/null +++ b/crypto/rsa/src/rsa_4096.rs @@ -0,0 +1,58 @@ +//! RSA-4096: the generic types at this size, as aliases over the marker [`RSA4096`]: +//! every (scheme, hash) pairing offered at this size, the lengths, and RSASVE; a key is +//! `RsaPrivateKey` and so on, and comes from the marker's generators. +//! Every (scheme, hash) pairing is an algorithm marker the key role traits are implemented over. +//! PSS's salt length is the hash's own output length throughout, RFC 8017 §9.1 note 4's +//! "typical" choice and Wycheproof's own `rsa_pss_*_mgf1__test.json`. + +use crate::rsassa_pkcs1_v1_5::RSASSA_PKCS1_v1_5; +use crate::rsassa_pss::RSASSA_PSS; +use crate::rsasve::{RsaKEMPrivateKey, RsaKEMPublicKey}; +pub use crate::size::RSA4096; +use crate::size::RsaSize; +use bouncycastle_sha2::{SHA256, SHA384, SHA512}; +use bouncycastle_sha3::SHAKE256; + +/// Encoded length of an RSA-4096 public key: `n || e`. +pub const PK_LEN: usize = RSA4096::PK_LEN; +/// Length of an RSA-4096 signature: the modulus's. +pub const SIG_LEN: usize = RSA4096::K_LEN; +/// Encoded length of an RSA-4096 private key: `p || q || dP || dQ || qInv || e`. +pub const SK_LEN: usize = RSA4096::SK_LEN; + +/// RSASSA-PKCS1-v1_5 with SHA-256 at RSA-4096. +#[allow(non_camel_case_types)] +pub type RSASSA_PKCS1_v1_5_SHA256 = RSASSA_PKCS1_v1_5; +/// RSASSA-PKCS1-v1_5 with SHA-384 at RSA-4096. +#[allow(non_camel_case_types)] +pub type RSASSA_PKCS1_v1_5_SHA384 = RSASSA_PKCS1_v1_5; +/// RSASSA-PKCS1-v1_5 with SHA-512 at RSA-4096. +#[allow(non_camel_case_types)] +pub type RSASSA_PKCS1_v1_5_SHA512 = RSASSA_PKCS1_v1_5; +/// RSASSA-PSS with SHA-256 (and MGF1 over it) at RSA-4096. +#[allow(non_camel_case_types)] +pub type RSASSA_PSS_SHA256 = RSASSA_PSS; +/// RSASSA-PSS with SHA-384 (and MGF1 over it) at RSA-4096. +#[allow(non_camel_case_types)] +pub type RSASSA_PSS_SHA384 = RSASSA_PSS; +/// RSASSA-PSS with SHA-512 (and MGF1 over it) at RSA-4096. +#[allow(non_camel_case_types)] +pub type RSASSA_PSS_SHA512 = RSASSA_PSS; +/// RSASSA-PSS with SHAKE256 as hash and mask (RFC 8702 §3.2.1, §5's pairing for this size) at RSA-4096. +#[allow(non_camel_case_types)] +pub type RSASSA_PSS_SHAKE256 = RSASSA_PSS; + +/// An RSA-4096 key-establishment private key. +pub type RSA4096KEMPrivateKey = RsaKEMPrivateKey; +/// An RSA-4096 key-establishment public key. +pub type RSA4096KEMPublicKey = RsaKEMPublicKey; +/// Length of an RSASVE-4096 ciphertext: `nLen`. +pub const CT_LEN: usize = RSA4096::K_LEN; +/// Length of an RSASVE-4096 shared secret, the secret value `Z`: `nLen`. +pub const SS_LEN: usize = RSA4096::K_LEN; +/// RSASVE at RSA-4096; `RSASVE::keygen` gives the KEM pair. +pub type RSASVE = crate::rsasve::RSASVE; +/// RSAES-OAEP at RSA-4096 with the label hash `H` and MGF1 over `M`; the key-establishment +/// keys above run it under [`OaepParams`](crate::rsaes_oaep::OaepParams). +#[allow(non_camel_case_types)] +pub type RSAES_OAEP = crate::rsaes_oaep::RSAES_OAEP; diff --git a/crypto/rsa/src/rsa_8192.rs b/crypto/rsa/src/rsa_8192.rs new file mode 100644 index 000000000..5b6242dcb --- /dev/null +++ b/crypto/rsa/src/rsa_8192.rs @@ -0,0 +1,54 @@ +//! RSA-8192: the generic types at this size, as aliases over the marker [`RSA8192`]: +//! every (scheme, hash) pairing offered at this size, the lengths, and RSASVE; a key is +//! `RsaPrivateKey` and so on, and comes from the marker's generators. +//! Every (scheme, hash) pairing is an algorithm marker the key role traits are implemented over. +//! PSS's salt length is the hash's own output length throughout, RFC 8017 §9.1 note 4's +//! "typical" choice and Wycheproof's own `rsa_pss_*_mgf1__test.json`. + +use crate::rsassa_pkcs1_v1_5::RSASSA_PKCS1_v1_5; +use crate::rsassa_pss::RSASSA_PSS; +use crate::rsasve::{RsaKEMPrivateKey, RsaKEMPublicKey}; +pub use crate::size::RSA8192; +use crate::size::RsaSize; +use bouncycastle_sha2::{SHA256, SHA384, SHA512}; + +/// Encoded length of an RSA-8192 public key: `n || e`. +pub const PK_LEN: usize = RSA8192::PK_LEN; +/// Length of an RSA-8192 signature: the modulus's. +pub const SIG_LEN: usize = RSA8192::K_LEN; +/// Encoded length of an RSA-8192 private key: `p || q || dP || dQ || qInv || e`. +pub const SK_LEN: usize = RSA8192::SK_LEN; + +/// RSASSA-PKCS1-v1_5 with SHA-256 at RSA-8192. +#[allow(non_camel_case_types)] +pub type RSASSA_PKCS1_v1_5_SHA256 = RSASSA_PKCS1_v1_5; +/// RSASSA-PKCS1-v1_5 with SHA-384 at RSA-8192. +#[allow(non_camel_case_types)] +pub type RSASSA_PKCS1_v1_5_SHA384 = RSASSA_PKCS1_v1_5; +/// RSASSA-PKCS1-v1_5 with SHA-512 at RSA-8192. +#[allow(non_camel_case_types)] +pub type RSASSA_PKCS1_v1_5_SHA512 = RSASSA_PKCS1_v1_5; +/// RSASSA-PSS with SHA-256 (and MGF1 over it) at RSA-8192. +#[allow(non_camel_case_types)] +pub type RSASSA_PSS_SHA256 = RSASSA_PSS; +/// RSASSA-PSS with SHA-384 (and MGF1 over it) at RSA-8192. +#[allow(non_camel_case_types)] +pub type RSASSA_PSS_SHA384 = RSASSA_PSS; +/// RSASSA-PSS with SHA-512 (and MGF1 over it) at RSA-8192. +#[allow(non_camel_case_types)] +pub type RSASSA_PSS_SHA512 = RSASSA_PSS; + +/// An RSA-8192 key-establishment private key. +pub type RSA8192KEMPrivateKey = RsaKEMPrivateKey; +/// An RSA-8192 key-establishment public key. +pub type RSA8192KEMPublicKey = RsaKEMPublicKey; +/// Length of an RSASVE-8192 ciphertext: `nLen`. +pub const CT_LEN: usize = RSA8192::K_LEN; +/// Length of an RSASVE-8192 shared secret, the secret value `Z`: `nLen`. +pub const SS_LEN: usize = RSA8192::K_LEN; +/// RSASVE at RSA-8192; `RSASVE::keygen` gives the KEM pair. +pub type RSASVE = crate::rsasve::RSASVE; +/// RSAES-OAEP at RSA-8192 with the label hash `H` and MGF1 over `M`; the key-establishment +/// keys above run it under [`OaepParams`](crate::rsaes_oaep::OaepParams). +#[allow(non_camel_case_types)] +pub type RSAES_OAEP = crate::rsaes_oaep::RSAES_OAEP; diff --git a/crypto/rsa/src/rsa_core.rs b/crypto/rsa/src/rsa_core.rs new file mode 100644 index 000000000..d92f741c0 --- /dev/null +++ b/crypto/rsa/src/rsa_core.rs @@ -0,0 +1,756 @@ +//! RSASP1 and RSAVP1 (RFC 8017 §5.2.1, §5.2.2): the raw signature and verification primitives, +//! and the checked CRT exponentiation RSASP1 and RSADP (§5.1.2) share. +//! [`rsasp1`] and [`rsavp1`] are private to the crate and reached through a padding scheme +//! only. Code generic over a size reaches the exponentiations beneath them at one width +//! through the size: the public one is [`RsaSize::public_exp`], and the private one is +//! `crt_exp` of `size::sealed::PrivateKeyEngine`, a supertrait of [`RsaSigningSize`] that +//! code outside the crate cannot name. They are the engine and not a way to +//! sign. RFC 8017's introduction to §5 says why: "\[primitives\] are not intended to provide +//! security apart from a scheme" -- "textbook RSA" (signing a bare integer with no padding) is +//! malleable and vulnerable to existential forgery. +//! +//! Both primitives operate on the two-prime case only (RFC 8017's `u = 2`, no additional +//! `(r_i, d_i, t_i)` triplets): [`crate::keys::RsaPrivateComponents`] has no representation for +//! multi-prime RSA, so there is nothing here to extend to `u > 2`. + +use crate::keys::{RsaPrivateComponents, RsaPublicComponents}; +use crate::modexp::{ + MontgomeryContext, mod_pow, mod_pow_public_exponent, mul_mod, mul_u64_mod, reduce_wide, sub_mod, +}; +use crate::size::{RsaSigningSize, RsaSize}; +use bouncycastle_core::errors::SignatureError; +use bouncycastle_ec::montgomery; +use bouncycastle_ec::nat; +use bouncycastle_utils::ct::Condition; +use bouncycastle_utils::secret::{Secret, ZeroizablePrimitive, zeroize_in_place}; + +/// RSAVP1 (RFC 8017 §5.2.2): `m = s^e mod n`, recovering the message representative from a +/// signature representative under the public key. +/// +/// Step 1's range check ("If the signature representative s is not between 0 and n - 1, output +/// 'signature representative out of range'") is `Err(`[`SignatureError::DecodingError`]`)` here. +pub(crate) fn rsavp1( + pk: &RsaPublicComponents, + s: &K::Limbs, +) -> Result { + // RFC 8017 §5.2.2 step 1: the representative must be in [0, n - 1]. + if !K::is_less(s, pk.n()) { + return Err(SignatureError::DecodingError("signature representative out of range")); + } + Ok(K::public_exp(pk.n(), pk.e(), s)) +} + +/// `x^e mod n` for a public exponent, the shared core of RSAVP1 and RSAEP: `x` must already be +/// below `n`. The size marker's `public_exp` forwards here with the size's widths. Variable +/// time in `n` and `e`, which are public, and constant time in `x`, which RSAEP's is not. +pub(crate) fn public_exp( + n: &[u64; L], + e: u64, + x: &[u64; L], +) -> [u64; L] { + let ctx = MontgomeryContext::::for_public_modulus(n) + .expect("the modulus is odd: a key's is, by its constructor"); + mod_pow_public_exponent::(x, e, &ctx) +} + +/// RSASP1 (RFC 8017 §5.2.1): `s = m^d mod n` by the CRT, released only if `s^e mod n` is `m` +/// again. +/// +/// Step 1's range check is `Err(`[`SignatureError::DecodingError`]`)`. A result that fails its +/// check is `Err(`[`SignatureError::ComputationFault`]`)`, with nothing of it returned: the +/// computation went wrong, or a factor of the key's modulus is not prime. +pub(crate) fn rsasp1( + sk: &RsaPrivateComponents, + m: &K::Limbs, +) -> Result { + // RFC 8017 §5.2.1 step 1: the representative must be in [0, n - 1]. + if !K::is_less(m, sk.n()) { + return Err(SignatureError::DecodingError("message representative out of range")); + } + let mut s = K::Limbs::ZEROED; + if !K::crt_exp(sk, m, &mut s).to_bool() { + return Err(SignatureError::ComputationFault); + } + Ok(s) +} + +/// RFC 8017 §3.2's three conditions on a private key in the CRT form, which make the quintuple +/// and `e` one key, in this order: `e * dP == 1 (mod (p - 1))`, `e * dQ == 1 (mod (q - 1))` +/// and `q * qInv == 1 (mod p)`. They are SP 800-56B Rev. 2 §6.4.1.4.3 step 7's d, e and f, and +/// with them its a, b and c hold: a `dP` of 1 or of `p - 1` satisfies no such congruence for an +/// `e` below `p - 1`, nor does a `qInv` of 1 for a `q` that is not 1 modulo `p`. +/// +/// `p` and `q` are odd, which the caller has checked. Constant time in the five components: +/// each residue comes from a bit-serial reduction and is compared over every limb, and none +/// of the three verdicts is branched on here. +pub(crate) fn crt_congruences( + p: &[u64; HALF], + q: &[u64; HALF], + d_p: &[u64; HALF], + d_q: &[u64; HALF], + q_inv: &[u64; HALF], + e: u64, +) -> [Condition; 3] { + const { assert!(HALF2 == 2 * HALF, "the double width HALF2 must be 2 * HALF") }; + let mut q_q_inv = montgomery::widening_mul::(q, q_inv); + let mut q_q_inv_mod_p = reduce_wide::(&q_q_inv, p); + let q_inv_ok = is_one(&q_q_inv_mod_p); + zeroize_in_place(&mut q_q_inv); + zeroize_in_place(&mut q_q_inv_mod_p); + [inverts_e_mod_prime_minus_1(d_p, e, p), inverts_e_mod_prime_minus_1(d_q, e, q), q_inv_ok] +} + +/// Whether `e * d == 1 (mod (prime - 1))`, for an odd `prime`. +fn inverts_e_mod_prime_minus_1( + d: &[u64; HALF], + e: u64, + prime: &[u64; HALF], +) -> Condition { + // `prime` is odd, so clearing its lowest bit subtracts 1. + let mut prime_minus_1 = *prime; + prime_minus_1[0] &= !1; + let mut residue = mul_u64_mod(d, e, &prime_minus_1); + let ok = is_one(&residue); + zeroize_in_place(&mut prime_minus_1); + zeroize_in_place(&mut residue); + ok +} + +/// Whether `x == 1`, over every limb. +fn is_one(x: &[u64; N]) -> Condition { + let mut diff = x[0] ^ 1; + for limb in &x[1..] { + diff |= limb; + } + Condition::::is_zero(diff) +} + +/// Overwrites the stack that the previous call made from the caller's frame used, by taking a +/// frame of its own over the same memory and wiping it. Never inlined: the frame is the point. +/// The caller runs its computation in a never-inlined function, so that everything the +/// computation and its callees spill or stage lies below the caller's frame, and calls this +/// next. +/// +/// The frame is `COUNT` values of `T`, for the part of the computation's stack that scales +/// with the modulus (`T` is a limb array of the size in hand), and `FIXED` words for the part +/// that does not. Each caller gives the measured figures beside its constants. +/// +/// The shape of `wipe_stack_below` in `bouncycastle-ed` (`ed25519/scalar.rs`) and +/// `bouncycastle-sha3` (`keccak.rs`), which are private to those crates and of one fixed size. +/// Like theirs it is sized for an optimised build: an unoptimised build's frames are larger +/// and are not covered. +#[inline(never)] +pub(crate) fn wipe_stack_below() { + let mut scaled = Secret::<[T; COUNT]>::new(); + let mut fixed = Secret::<[u64; FIXED]>::new(); + core::hint::black_box((&mut *scaled, &mut *fixed)); +} + +/// [`wipe_stack_below`] when it goes out of scope, for a function whose result is itself the +/// secret and is returned by value. Such a function ends with the call that does the work, so +/// that the result is written to where the function's own caller wants it and not staged in +/// this frame, and declares this first, so that the wipe runs after that call has returned: +/// +/// ```text +/// let _wipe = WipeStackBelowOnReturn::::new(); +/// Self::the_work_in_own_frame(..) +/// ``` +pub(crate) struct WipeStackBelowOnReturn< + T: ZeroizablePrimitive, + const COUNT: usize, + const FIXED: usize, +>(core::marker::PhantomData); + +impl + WipeStackBelowOnReturn +{ + pub(crate) fn new() -> Self { + Self(core::marker::PhantomData) + } +} + +impl Drop + for WipeStackBelowOnReturn +{ + fn drop(&mut self) { + wipe_stack_below::(); + } +} + +/// What [`wipe_stack_below`] overwrites after the checked CRT: this many `[u64; L]` values and +/// this many words. Measured in x86-64 release builds (rustc 1.88 and 1.97), the computation +/// and everything it calls use 8248 bytes at RSA-2048, 10552 at RSA-3072, 13752 at RSA-4096 +/// and 27592 at RSA-8192; these cover 9600, 13440, 17280 and 32640, the difference being +/// room for a compiler that lays the frames out less tightly. +const CRT_STACK_PER_LIMB: usize = 30; +const CRT_STACK_FIXED: usize = 240; + +/// The CRT exponentiation of RSASP1 and RSADP, [`crt_exp`], with its result checked before any +/// of it leaves: `y = x^d mod n` goes into `out` only if `y^e mod n` is `x` again, which it is +/// whenever both half-exponentiations were computed correctly and the key's primes are prime +/// (that its components belong together is its constructor's check). Otherwise `out` is zero and the return is +/// FALSE. A CRT result that is right modulo one prime and wrong modulo the other must not be +/// seen, by a verifier or anyone else. +/// +/// `x < n`. Constant time in the key and in `y`: the comparison is over every limb, and `out` +/// is written through a mask either way. The size marker's `crt_exp` forwards here. +/// +/// The contexts over `p` and `q`, the two half-size results, `h` and `q * h` pass through +/// locals, return slots and spilled registers of this computation and its callees, where the +/// scrubbing of the named values does not reach. So it runs in a frame of its own and the +/// stack it used is overwritten afterwards. +#[allow(clippy::too_many_arguments)] +pub(crate) fn crt_exp_checked< + const L: usize, + const L2: usize, + const L21: usize, + const HALF: usize, + const HALF2: usize, + const HALF21: usize, +>( + p: &[u64; HALF], + q: &[u64; HALF], + d_p: &[u64; HALF], + d_q: &[u64; HALF], + q_inv: &[u64; HALF], + n: &[u64; L], + e: u64, + x: &[u64; L], + out: &mut [u64; L], +) -> Condition { + let ok = crt_exp_checked_in_own_frame::( + p, q, d_p, d_q, q_inv, n, e, x, out, + ); + wipe_stack_below::<[u64; L], CRT_STACK_PER_LIMB, CRT_STACK_FIXED>(); + ok +} + +/// The computation of [`crt_exp_checked`]. Never inlined, so that what it and its callees +/// leave lies below its caller's frame, where [`wipe_stack_below`] reaches it. +#[allow(clippy::too_many_arguments)] +#[inline(never)] +fn crt_exp_checked_in_own_frame< + const L: usize, + const L2: usize, + const L21: usize, + const HALF: usize, + const HALF2: usize, + const HALF21: usize, +>( + p: &[u64; HALF], + q: &[u64; HALF], + d_p: &[u64; HALF], + d_q: &[u64; HALF], + q_inv: &[u64; HALF], + n: &[u64; L], + e: u64, + x: &[u64; L], + out: &mut [u64; L], +) -> Condition { + let mut y = crt_exp::(p, q, d_p, d_q, q_inv, x); + // y < n whatever the components hold (y = s_2 + q * h with s_2 < q and h < p), and the + // public exponentiation is constant time in its base. + let mut back = public_exp::(n, e, &y); + let mut diff = 0u64; + for i in 0..L { + diff |= back[i] ^ x[i]; + } + let ok = Condition::::is_zero(diff); + for i in 0..L { + out[i] = ok.select(y[i], 0); + } + zeroize_in_place(&mut y); + zeroize_in_place(&mut back); + ok +} + +/// RFC 8017 §5.2.1 step 2.b, the CRT form of `m^d mod n`, over the five components (RSADP's +/// step 2.b in §5.1.2 is the same computation, its sub-steps numbered i to iv), without the +/// result check [`crt_exp_checked`] wraps it in. Constant time in the key: the two +/// contexts are built by `MontgomeryContext::for_secret_modulus`, every exponentiation is +/// `mod_pow`'s ladder, every reduction `reduce_wide`'s bit-serial loop. +pub(crate) fn crt_exp< + const L: usize, + const L2: usize, + const L21: usize, + const HALF: usize, + const HALF2: usize, + const HALF21: usize, +>( + p: &[u64; HALF], + q: &[u64; HALF], + d_p: &[u64; HALF], + d_q: &[u64; HALF], + q_inv: &[u64; HALF], + m: &[u64; L], +) -> [u64; L] { + let mut ctx_p = Secret::>::new(); + // Odd, as `for_secret_modulus` needs: `RsaPrivateComponents::from_crt_components` checked. + *ctx_p = MontgomeryContext::::for_secret_modulus(p); + let mut ctx_q = Secret::>::new(); + *ctx_q = MontgomeryContext::::for_secret_modulus(q); + // Step 2.b.1: s_1 = m^dP mod p, s_2 = m^dQ mod q, each on m reduced to the prime's width. + let mut m_mod_p = reduce_wide::(m, p); + let mut m_mod_q = reduce_wide::(m, q); + let mut s1 = mod_pow::(&m_mod_p, d_p, &ctx_p); + let mut s2 = mod_pow::(&m_mod_q, d_q, &ctx_q); + // Step 2.b.3: h = (s_1 - s_2) * qInv mod p, with s_2 reduced mod p first (q can be the + // larger prime). + let mut s2_mod_p = reduce_wide::(&s2, p); + let mut diff = sub_mod::(&s1, &s2_mod_p, p); + let mut h = mul_mod::(&diff, q_inv, &ctx_p); + // Step 2.b.4: s = s_2 + q * h. + let mut q_h = montgomery::widening_mul::(q, &h); + let mut s2_wide = [0u64; L]; + s2_wide[..HALF].copy_from_slice(&s2); + let (s, carry) = nat::add(&s2_wide, &q_h); + debug_assert_eq!(carry, 0, "CRT recombination must stay within n's width"); + zeroize_in_place(&mut m_mod_p); + zeroize_in_place(&mut m_mod_q); + zeroize_in_place(&mut s1); + zeroize_in_place(&mut s2); + zeroize_in_place(&mut s2_mod_p); + zeroize_in_place(&mut diff); + zeroize_in_place(&mut h); + zeroize_in_place(&mut q_h); + zeroize_in_place(&mut s2_wide); + s +} + +#[cfg(test)] +mod tests { + //! `rsasp1`/`rsavp1` are deliberately crate-private (see the module docs), so they cannot be + //! reached from `tests/` the way every other primitive in this crate is exercised -- this is + //! the "high-risk code that ... cannot be reached through the public API" exception + //! `CLAUDE.md`'s testing notes describe. The key is a genuine RSA-2048 key pair, the first + //! SHA-256 group of Wycheproof's `rsa_pkcs1_2048_sig_gen_test.json` (`e = 65537`; see + //! `tests/rsa_2048_pkcs1_v1_5_tests.rs` for its provenance), and every expected signature + //! was computed in Python and cross-checked two ways before being pasted here: CRT + //! recombination against plain `pow(m, d, n)`, and `pow(pow(m, d, n), e, n) == m`. + + use super::*; + + use crate::size::RSA2048; + + fn keypair() -> RsaPrivateComponents { + let p: [u64; 16] = [ + 0x0ea36cfb3a5b18f1, 0x48a6e65332119129, 0x110ad9e7b48a1c93, 0x569156b90113e2e9, + 0xe79813a575cfad9c, 0x69d659d143ec6f17, 0xe81e6bab5ddaa783, 0xbff1c5b80a69f788, + 0x978f6c35814f50ee, 0xe6a289ad4cfbf78f, 0x34d5681e5809d415, 0xbb028bda42eeb5d2, + 0x41c56e4de086b0d5, 0x58b8d1e24f3b55d0, 0xfb5248247d98cb7d, 0xdc431050f782e894, + ]; + let q: [u64; 16] = [ + 0x669f140cfbc20f25, 0xb97bb03677207d95, 0xfd4e06f3ed7299d4, 0x160f90536abc9492, + 0xf5b131f39098f7bc, 0xae8d72c57088d7ab, 0x89b94fbde542aba9, 0x3d3f9880ec47d5e0, + 0x1378a6868af3b7a0, 0x5544070beb057c94, 0x16611debc472fac4, 0xe500ffb79f5b8868, + 0x308a5e32196603b2, 0xea5fb19eb4eabc38, 0x122273ae3222b598, 0xbd1a81e7977f9898, + ]; + let d_p: [u64; 16] = [ + 0x209f33f09515d7c1, 0xb4a9b37656917205, 0x276933bb07e4efb9, 0x8c14019808e00414, + 0x289f96da220711e5, 0xfbbd2923d31532fe, 0xc06b414e61c0e1e7, 0x4c23c4588488961d, + 0x4dc48ae34514759c, 0x9c786961ae3e2c35, 0x497e8d9c650688e0, 0x18bf08472612dbe5, + 0x8885fb161870ee12, 0xf21d7c1479d99d47, 0x9121d91952ffd1c7, 0xa94b528b28f29159, + ]; + let d_q: [u64; 16] = [ + 0xf7597ffb68011d8d, 0x7b3cc538c4bab8c9, 0xa8fa480a81a925af, 0x6d6ede7251a383bf, + 0x8a63f788ce3a0f85, 0x0b920502eb478bc9, 0x7e37e755edfe70d9, 0x9cf9948422a16555, + 0x0d6d9ea1f2ef71fd, 0xf7efa32ea0cb6e00, 0x0629b114ca7f780f, 0xcf51176359654348, + 0x540cdcbd4ad35435, 0x31c02ff1a2bc437c, 0xff2503df78bafed5, 0x3af0e72a933aef09, + ]; + let q_inv: [u64; 16] = [ + 0x552fe4bfce945f7b, 0x67e50c999c67247b, 0xfb54ef17be3b2853, 0x241f5921b5ad3983, + 0x02de5eccd143cf31, 0x74e45f6fcc60f216, 0xafa5428a74f12708, 0x88d42294b6a2759b, + 0xe923e1097c0c562f, 0xc968b48a91c38b5b, 0x933e85179c0320b0, 0x7993d0445f758d51, + 0x9bfc042ee0924b1b, 0x41f956d90fa8a793, 0xee7a87b6483a66ee, 0x2640fbfbcfefb163, + ]; + RsaPrivateComponents::from_crt_components(&p, &q, &d_p, &d_q, &q_inv, 0x00010001) + .expect("genuine CRT components must be accepted") + } + + fn public_key(sk: &RsaPrivateComponents) -> RsaPublicComponents { + RsaPublicComponents::new(sk.n(), 0x00010001).expect("e = 65537 is valid") + } + + #[test] + fn rsasp1_matches_python_crt_and_rsavp1_recovers_m() { + let sk = keypair(); + let pk = public_key(&sk); + + let m: [u64; 32] = [ + 0x000000e8d4a50fff, 0x0000000000000000, 0x0000000000000000, 0x7ff3af8ff7be0800, + 0x67ad7342574d2811, 0x4976e38546b81ac1, 0x2b70b32f6c55125e, 0x00cb3167f0fdb915, + 0x370a38a0a48c0523, 0x6a9a91b20989ab70, 0x612d6fd7e2bb4495, 0x0000000000015112, + 0x0000000000000000, 0x0000000000000000, 0x0000000000000000, 0x0000000000000000, + 0x0000000000000000, 0x0000000000000000, 0x0000000000000000, 0x0000000000000000, + 0x0000000000000000, 0x0000000000000000, 0x0000000000000000, 0x0000000000000000, + 0x0000000000000000, 0x0000000000000000, 0x0000000000000000, 0x0000000000000000, + 0x0000000000000000, 0x0000000000000000, 0x0000000000000000, 0x0000000000000000, + ]; + let expected_s: [u64; 32] = [ + 0xd5bc2d48a83b31e5, 0xd48a52b64b6b96b5, 0xdc4ca2421de42187, 0x4c6118a19591ea09, + 0xe849ca6daac6241f, 0x2678c5b1e6e79065, 0xee29c430e55bc557, 0xf302e3591357ce98, + 0x686f541f63912448, 0x439b31f48f6dc764, 0xf3e71f9194357f28, 0x42de8ac88d93e447, + 0x6827ee7425c4211b, 0x7827dcf7d9dd02e5, 0xcdbd9c101bd7827e, 0xac2df3ab2f1b6d57, + 0x22530d053b2c62c2, 0x97d455fb10d0016f, 0xda0173ac606bf822, 0xde58560afb5b0a77, + 0x0b5863a4b0a2a080, 0x310470fcb7994b88, 0x7edc02bc4dba6d65, 0x62357119beba7486, + 0x6c6680551d7b3fda, 0x085593ca5407542f, 0xd28b00187aea208d, 0x8043e9a53c324baf, + 0x7e10dc6aefa091e0, 0xe23d3889a371d248, 0x01c491dd0a01f0c4, 0x4e47e60636bb4dac, + ]; + + let s = rsasp1::(&sk, &m).expect("m is in range"); + assert_eq!(s, expected_s); + + let recovered = rsavp1::(&pk, &s).expect("s is in range"); + assert_eq!(recovered, m); + } + + #[test] + fn rsasp1_second_vector_near_n_minus_1() { + let sk = keypair(); + let pk = public_key(&sk); + + // m2 = n - 12345, exercising a message representative close to the top of the range. + let m2: [u64; 32] = [ + 0xf7820283f742899c, 0x6f453d1f5b4c2e9c, 0x9a02e5a530e77306, 0x5d12569a62807d3b, + 0xc22c4e5ac0f7c1a4, 0xf9f85e7975005d9b, 0x1b4d9cae79d460d8, 0x69816f48698bcbba, + 0x126422f590975a19, 0xfd7afc3e09ada0f1, 0xed5411eb878daf05, 0x4c03145b5d3495d4, + 0x12be82de4d1ece6b, 0x21d0fceca08d945a, 0x7d9658594266f5c0, 0x4c22da610428e09c, + 0x90ed81299615d981, 0x7a1fa26a8dce26f4, 0x3eff8f17e1a02939, 0x254a2fe9765313a0, + 0x3d3e42e46e48c98e, 0xcd20f79c15e8247f, 0x2ed8a7711a1253fa, 0xb5ab393189db9251, + 0x9e89d6eac8845097, 0x1700f65903b46942, 0x1878d80325b6ef5a, 0x37f9746d3f7cafd3, + 0x094fa1fee82224e6, 0x4a8a5b462ebef717, 0x6e45567151355051, 0xa2b451a07d0aa5f9, + ]; + let expected_s2: [u64; 32] = [ + 0x21aaf584e305ddf7, 0x21f3dccf3e5072ee, 0xf5e0eb3cd82ad5d7, 0x1754c77f5c4bd685, + 0x8c396d2e90dd96b8, 0x4535e22014c3503d, 0x0159ab66fe04959d, 0xecfe054486820710, + 0x7a27dbbfe19204e9, 0x02c060ac0fdc597f, 0xd2def08324675a05, 0x28d6ecd14d476bed, + 0xf81f1e10e1198c2d, 0x8d343c8f7f43413c, 0x578f55bc4294e74d, 0x5755f9ad526bce2d, + 0xc9ca96c13523a148, 0x513f3dadc0bb6784, 0xab72f632a4f73988, 0x59005fd0f7af24ef, + 0x4f197c87199b0283, 0x66b27811e159eb5f, 0xfa688afc1b45df99, 0xc07a9c95704d1dde, + 0x52b56f684cd42de3, 0x8c9d4bbaad4fafb8, 0x6954ceced63aa41b, 0x08b40e0ff164edff, + 0x6e93ed6bdb3aa4d0, 0xd95b97bc72531c4e, 0x3bdde22a09aea05c, 0x062ce3e60377e92e, + ]; + + let s2 = rsasp1::(&sk, &m2).expect("m2 is in range"); + assert_eq!(s2, expected_s2); + assert_eq!(rsavp1::(&pk, &s2).expect("s2 is in range"), m2); + } + + #[test] + fn rsasp1_rejects_out_of_range_message() { + let sk = keypair(); + let out_of_range = *sk.n(); + assert!(matches!( + rsasp1::(&sk, &out_of_range), + Err(SignatureError::DecodingError(_)) + )); + } + + #[test] + fn rsavp1_rejects_out_of_range_signature() { + let sk = keypair(); + let pk = public_key(&sk); + let out_of_range = *pk.n(); + assert!(matches!( + rsavp1::(&pk, &out_of_range), + Err(SignatureError::DecodingError(_)) + )); + } + + mod damaged_keys { + //! The result of a private-key operation is checked before it is released (the crate's + //! `# Security Considerations`). A key's constructor refuses components that do not belong + //! together, so a result wrong modulo one prime alone, as a fault in one + //! half-exponentiation leaves it, cannot be provoked from `tests/`: these build a key with + //! one damaged component past the constructor (`RsaPrivateComponents::unvalidated`, which + //! exists in test builds only) and stand for the fault. Each private-key operation then + //! returns its error and leaves the caller's buffer zeroized, under RSASSA-PKCS1-v1_5, + //! RSASSA-PSS, RSASVE (raw and through HKDF) and RSAES-OAEP (as a KEM and as key + //! transport); the sound key does all of them. + + use crate::keys::{RsaPrivateComponents, RsaPublicComponents}; + use crate::rsa_2048::{ + RSA2048KEMPrivateKey, RSA2048KEMPublicKey, RSASSA_PKCS1_v1_5_SHA256, RSASSA_PSS_SHA256, + }; + use crate::rsaes_oaep::OaepParams; + use crate::rsassa; + use crate::rsasve::RsaKEMPrivateKey; + use crate::size::sealed::PrivateKeyEngine; + use crate::size::{RSA2048, RsaSize}; + use bouncycastle_core::errors::{KEMError, KeyTransportError, SignatureError}; + use bouncycastle_core::kdf_params::{KdfParams, KeyLen}; + use bouncycastle_core::kem_key::{DecapsulatingKey, EncapsulatingKey}; + use bouncycastle_core::key_material::{KeyMaterial, KeyMaterialTrait, KeyType}; + use bouncycastle_core::key_transport_key::{ + KeyTransportDecryptingKey, KeyTransportEncryptingKey, + }; + use bouncycastle_core::signature_key::{ + DeterministicOneShotSigningKey, DeterministicSigningKey, OneShotSigningKey, + OneShotVerifyingKey, SigningKey, + }; + use bouncycastle_core::traits::SignatureSigner; + use bouncycastle_hkdf::HkdfDescription; + use bouncycastle_rng::DefaultRNG; + use bouncycastle_sha2::SHA256; + + // A genuine RSA-2048 key: the first SHA-256 group of Wycheproof's + // `rsa_pkcs1_2048_sig_gen_test.json` (`tests/rsa_2048_pkcs1_v1_5_tests.rs` has the provenance), + // with e = 65537. + const P: [u64; 16] = [ + 0x0ea36cfb3a5b18f1, 0x48a6e65332119129, 0x110ad9e7b48a1c93, 0x569156b90113e2e9, + 0xe79813a575cfad9c, 0x69d659d143ec6f17, 0xe81e6bab5ddaa783, 0xbff1c5b80a69f788, + 0x978f6c35814f50ee, 0xe6a289ad4cfbf78f, 0x34d5681e5809d415, 0xbb028bda42eeb5d2, + 0x41c56e4de086b0d5, 0x58b8d1e24f3b55d0, 0xfb5248247d98cb7d, 0xdc431050f782e894, + ]; + const Q: [u64; 16] = [ + 0x669f140cfbc20f25, 0xb97bb03677207d95, 0xfd4e06f3ed7299d4, 0x160f90536abc9492, + 0xf5b131f39098f7bc, 0xae8d72c57088d7ab, 0x89b94fbde542aba9, 0x3d3f9880ec47d5e0, + 0x1378a6868af3b7a0, 0x5544070beb057c94, 0x16611debc472fac4, 0xe500ffb79f5b8868, + 0x308a5e32196603b2, 0xea5fb19eb4eabc38, 0x122273ae3222b598, 0xbd1a81e7977f9898, + ]; + const D_P: [u64; 16] = [ + 0x209f33f09515d7c1, 0xb4a9b37656917205, 0x276933bb07e4efb9, 0x8c14019808e00414, + 0x289f96da220711e5, 0xfbbd2923d31532fe, 0xc06b414e61c0e1e7, 0x4c23c4588488961d, + 0x4dc48ae34514759c, 0x9c786961ae3e2c35, 0x497e8d9c650688e0, 0x18bf08472612dbe5, + 0x8885fb161870ee12, 0xf21d7c1479d99d47, 0x9121d91952ffd1c7, 0xa94b528b28f29159, + ]; + const D_Q: [u64; 16] = [ + 0xf7597ffb68011d8d, 0x7b3cc538c4bab8c9, 0xa8fa480a81a925af, 0x6d6ede7251a383bf, + 0x8a63f788ce3a0f85, 0x0b920502eb478bc9, 0x7e37e755edfe70d9, 0x9cf9948422a16555, + 0x0d6d9ea1f2ef71fd, 0xf7efa32ea0cb6e00, 0x0629b114ca7f780f, 0xcf51176359654348, + 0x540cdcbd4ad35435, 0x31c02ff1a2bc437c, 0xff2503df78bafed5, 0x3af0e72a933aef09, + ]; + const Q_INV: [u64; 16] = [ + 0x552fe4bfce945f7b, 0x67e50c999c67247b, 0xfb54ef17be3b2853, 0x241f5921b5ad3983, + 0x02de5eccd143cf31, 0x74e45f6fcc60f216, 0xafa5428a74f12708, 0x88d42294b6a2759b, + 0xe923e1097c0c562f, 0xc968b48a91c38b5b, 0x933e85179c0320b0, 0x7993d0445f758d51, + 0x9bfc042ee0924b1b, 0x41f956d90fa8a793, 0xee7a87b6483a66ee, 0x2640fbfbcfefb163, + ]; + + const E: u64 = 65537; + const MSG: &[u8] = b"a message"; + + /// The sound key and four damaged ones, each named: one bit flipped in `dP`, in `dQ` and in + /// `qInv`, and the sound components under an exponent that is not theirs. + fn keys() + -> (RsaPrivateComponents, [(&'static str, RsaPrivateComponents); 4]) + { + let key = |d_p: &[u64; 16], d_q: &[u64; 16], q_inv: &[u64; 16], e: u64| { + RsaPrivateComponents::::unvalidated(&P, &Q, d_p, d_q, q_inv, e) + }; + let flipped = |x: &[u64; 16], limb: usize, bit: u32| { + let mut x = *x; + x[limb] ^= 1 << bit; + x + }; + let damaged = [ + ("dP", key(&flipped(&D_P, 0, 1), &D_Q, &Q_INV, E)), + ("dQ", key(&D_P, &flipped(&D_Q, 7, 40), &Q_INV, E)), + ("qInv", key(&D_P, &D_Q, &flipped(&Q_INV, 15, 3), E)), + ("e", key(&D_P, &D_Q, &Q_INV, 65539)), + ]; + (key(&D_P, &D_Q, &Q_INV, E), damaged) + } + + /// The key-establishment key over the same components. + fn kem_key(components: &RsaPrivateComponents) -> RSA2048KEMPrivateKey { + RsaKEMPrivateKey(components.clone()) + } + + /// The size's checked exponentiation itself: a sound key gives the value that `e` takes back + /// to the input, and a damaged one gives FALSE and an output of zero. + #[test] + fn the_checked_exponentiation_releases_only_a_result_that_e_inverts() { + let (sound, damaged) = keys(); + let mut x = [0u64; 32]; + x[0] = 0x0123_4567_89ab_cdef; + x[17] = 0xfeed_face_cafe_f00d; + + let mut y = [0xFFFF_FFFF_FFFF_FFFFu64; 32]; + assert!(RSA2048::crt_exp(&sound, &x, &mut y).to_bool()); + assert_eq!(RSA2048::public_exp(sound.n(), E, &y), x); + + for (what, sk) in &damaged { + let mut y = [0xFFFF_FFFF_FFFF_FFFFu64; 32]; + assert!(!RSA2048::crt_exp(sk, &x, &mut y).to_bool(), "{what}"); + assert_eq!(y, [0u64; 32], "{what}"); + } + } + + #[test] + fn a_damaged_key_does_not_sign_pkcs1_v1_5() { + let (sound, damaged) = keys(); + let pk = RsaPublicComponents::::new(sound.n(), E).unwrap(); + let sig = + sound.key::().sign_deterministic(MSG, None).unwrap(); + pk.key::().verify(MSG, None, &sig).unwrap(); + + for (what, sk) in damaged { + let sk = sk.into_key::(); + assert_eq!( + sk.sign_deterministic(MSG, None), + Err(SignatureError::ComputationFault), + "{what}" + ); + let mut out = [0xFFu8; 256]; + assert_eq!( + sk.sign_deterministic_out(MSG, None, &mut out), + Err(SignatureError::ComputationFault), + "{what}" + ); + assert_eq!(out, [0u8; 256], "{what}"); + // Streaming, and from the hash. + let mut signer = sk.create_signer_deterministic(None).unwrap(); + signer.do_update(MSG); + let mut out = [0xFFu8; 256]; + assert_eq!( + signer.do_final_out(&mut out), + Err(SignatureError::ComputationFault), + "{what}" + ); + assert_eq!(out, [0u8; 256], "{what}"); + assert_eq!( + rsassa::sign_from_hash_deterministic(&sk, &[0x11; 32]), + Err(SignatureError::ComputationFault), + "{what}" + ); + } + } + + #[test] + fn a_damaged_key_does_not_sign_pss() { + let (sound, damaged) = keys(); + let mut rng = DefaultRNG::default(); + let pk = RsaPublicComponents::::new(sound.n(), E).unwrap(); + let sig = sound.key::().sign(&mut rng, MSG, None).unwrap(); + pk.key::().verify(MSG, None, &sig).unwrap(); + + for (what, sk) in damaged { + let sk = sk.into_key::(); + assert_eq!( + sk.sign(&mut rng, MSG, None), + Err(SignatureError::ComputationFault), + "{what}" + ); + let mut out = [0xFFu8; 256]; + assert_eq!( + sk.sign_out(&mut rng, MSG, None, &mut out), + Err(SignatureError::ComputationFault), + "{what}" + ); + assert_eq!(out, [0u8; 256], "{what}"); + // Streaming with the salt given, from the hash with a salt drawn, and with one given. + let mut signer = sk.create_signer(&mut rng, None).unwrap(); + signer.set_salt([0x42u8; 32]); + signer.do_update(MSG); + let mut out = [0xFFu8; 256]; + assert_eq!( + signer.do_final_out(&mut out), + Err(SignatureError::ComputationFault), + "{what}" + ); + assert_eq!(out, [0u8; 256], "{what}"); + assert_eq!( + rsassa::sign_from_hash(&sk, &[0x11; 32], &mut rng), + Err(SignatureError::ComputationFault), + "{what}" + ); + assert_eq!( + rsassa::sign_from_hash_with_salt(&sk, &[0x11; 32], &[0x42; 32]), + Err(SignatureError::ComputationFault), + "{what}" + ); + } + } + + /// RSASVE and RSASVE with HKDF: the secret value of a ciphertext made for the sound key is + /// not handed out by a damaged one. + #[test] + fn a_damaged_key_does_not_decapsulate_rsasve() { + let (sound, damaged) = keys(); + let mut rng = DefaultRNG::default(); + let pk = RSA2048KEMPublicKey::new(sound.n(), E).unwrap(); + let sound = kem_key(&sound); + let hkdf = HkdfDescription::::new(); + let params = KdfParams::new(&hkdf, b"info", KeyLen::<32>); + + let (z, ct) = pk.encaps(&mut rng, ()).unwrap(); + assert_eq!(sound.decaps(&ct, ()).unwrap(), z); + let (key, ct_kdf) = pk.encaps(&mut rng, params).unwrap(); + assert_eq!(sound.decaps(&ct_kdf, params).unwrap(), key); + + for (what, sk) in damaged { + let sk = kem_key(&sk); + assert!(matches!(sk.decaps(&ct, ()), Err(KEMError::DecapsulationFailed)), "{what}"); + let mut ss = KeyMaterial::<256>::from_bytes(&[0xEE; 256]).unwrap(); + assert_eq!( + sk.decaps_out(&ct, (), &mut ss), + Err(KEMError::DecapsulationFailed), + "{what}" + ); + assert_eq!(ss.key_type(), KeyType::Zeroized, "{what}"); + assert_eq!(ss.key_len(), 0, "{what}"); + + let mut ss = KeyMaterial::<32>::from_bytes(&[0xEE; 32]).unwrap(); + assert_eq!( + sk.decaps_out(&ct_kdf, params, &mut ss), + Err(KEMError::DecapsulationFailed), + "{what}" + ); + assert_eq!(ss.key_type(), KeyType::Zeroized, "{what}"); + } + } + + /// RSAES-OAEP: a failed result check is the one decryption error, as a wrong label is, with + /// the key buffer zeroized, for the KEM and for key transport. + #[test] + fn a_damaged_key_does_not_decrypt_oaep() { + let (sound, damaged) = keys(); + let mut rng = DefaultRNG::default(); + let pk = RSA2048KEMPublicKey::new(sound.n(), E).unwrap(); + let sound = kem_key(&sound); + let params = OaepParams::::new(b"label"); + + let (ss, ct) = pk.encaps(&mut rng, params).unwrap(); + assert_eq!(sound.decaps(&ct, params).unwrap(), ss); + let sent = KeyMaterial::<48>::from_bytes_as_type(&[0x42; 48], KeyType::MACKey).unwrap(); + let ct_sent = pk.transport(&mut rng, params, &sent).unwrap(); + let mut recovered = KeyMaterial::<64>::new(); + assert_eq!(sound.recover_out(&ct_sent, params, &mut recovered), Ok(48)); + assert_eq!(recovered.ref_to_bytes(), [0x42; 48]); + + // What any other decryption failure looks like: the sound key under the wrong label. + let wrong = OaepParams::::new(b"another label"); + let mut out = KeyMaterial::<64>::from_bytes(&[0xEE; 64]).unwrap(); + assert_eq!( + sound.recover_out(&ct_sent, wrong, &mut out), + Err(KeyTransportError::DecryptionFailed) + ); + assert_eq!(out.key_type(), KeyType::Zeroized); + + for (what, sk) in damaged { + let sk = kem_key(&sk); + assert!( + matches!(sk.decaps(&ct, params), Err(KEMError::DecapsulationFailed)), + "{what}" + ); + let mut ss = KeyMaterial::<32>::from_bytes(&[0xEE; 32]).unwrap(); + assert_eq!( + sk.decaps_out(&ct, params, &mut ss), + Err(KEMError::DecapsulationFailed), + "{what}" + ); + assert_eq!(ss.key_type(), KeyType::Zeroized, "{what}"); + + let mut out = KeyMaterial::<64>::from_bytes(&[0xEE; 64]).unwrap(); + assert_eq!( + sk.recover_out(&ct_sent, params, &mut out), + Err(KeyTransportError::DecryptionFailed), + "{what}" + ); + assert_eq!(out.key_type(), KeyType::Zeroized, "{what}"); + assert_eq!(out.key_len(), 0, "{what}"); + } + } + } +} diff --git a/crypto/rsa/src/rsaes_oaep.rs b/crypto/rsa/src/rsaes_oaep.rs new file mode 100644 index 000000000..5da37d67d --- /dev/null +++ b/crypto/rsa/src/rsaes_oaep.rs @@ -0,0 +1,551 @@ +//! RSAES-OAEP (RFC 8017 §7.1; SP 800-56B Rev. 2 §7.2.2, RSA-OAEP) on the key-establishment +//! keys [`RsaKEMPublicKey`] and [`RsaKEMPrivateKey`], as key transport: the plaintext is always +//! a key. +//! +//! Two roles over one implementation, both selected by [`OaepParams`]: +//! +//! * **A KEM**, KTS-OAEP-basic of SP 800-56B Rev. 2 §9.2.3 with the key drawn here: the +//! [`EncapsulatingKey`] / [`DecapsulatingKey`] roles, whose shared secret is the transported +//! key, `LEN` bytes from the caller's RNG. +//! * **Transport of a key the caller holds** (a CMS or JOSE content-encryption key): the +//! [`KeyTransportEncryptingKey`] / [`KeyTransportDecryptingKey`] roles. +//! +//! The parameters name the label hash `H` and the MGF1 hash `M`, which SP 800-56B Rev. 2 +//! §7.2.2.1 item 2 allows to differ, and carry the label `L` (the "additional input" `A` of +//! §7.2.2.3), which both sides must supply and which may be empty. +//! +//! # 🚨 Security Considerations 🚨 +//! +//! * **The ciphertext does not say who made it.** Anyone with the public key can transport a +//! key to its owner; a protocol that needs to know the sender must authenticate it. +//! * **Every decryption failure is one error** ([`KEMError::DecapsulationFailed`], +//! [`KeyTransportError::DecryptionFailed`]), computed without branching on the padding, as +//! RFC 8017 §7.1.2's note asks; a private-key result that fails its check (the crate's +//! `# Security Considerations`) is that error as well, by the same path. A caller must keep +//! it that way: do not report, log or time anything that tells a peer why a ciphertext was +//! refused. +//! * **The label is not secret and is not sent.** It binds a ciphertext to its use; a +//! ciphertext made under one label does not decrypt under another. +//! * **The hashes are RFC 8017's** ([`OaepHash`]). **SHA-1** is among them, for peers that use it. +//! OAEP does not rest on collision resistance, so the algorithm's strength is the modulus's, +//! capped by what the shorter hash output can carry; prefer SHA-256 or longer where the +//! choice is open. + +use crate::eme_oaep::{self, HashBuf}; +use crate::keygen::fill_bytes; +use crate::rsa_core::wipe_stack_below; +use crate::rsasve::{RsaKEMPrivateKey, RsaKEMPublicKey, in_open_range}; +use crate::size::{RsaSigningSize, RsaSize}; +use bouncycastle_core::errors::{KEMError, KeyMaterialError, KeyTransportError, RNGError}; +use bouncycastle_core::kem_key::{DecapsulatingKey, EncapsulatingKey, KEMAlgorithm}; +use bouncycastle_core::key_material::{KeyMaterial, KeyMaterialTrait, KeyType}; +use bouncycastle_core::key_transport_key::{ + KeyTransportAlgorithm, KeyTransportDecryptingKey, KeyTransportEncryptingKey, +}; +use bouncycastle_core::security_strength::SecurityStrength; +use bouncycastle_core::traits::{ + Algorithm, HashAlgParams, HashOneShot, KEMDecapsulator, KEMEncapsulator, RNG, +}; +use bouncycastle_digest::sha1::SHA1; +use bouncycastle_sha2::{SHA224, SHA256, SHA384, SHA512, SHA512_224, SHA512_256}; +use bouncycastle_utils::const_str::ConstStr; +use bouncycastle_utils::secret::Secret; +use core::marker::PhantomData; + +mod sealed { + pub trait Sealed {} +} + +/// A hash RSAES-OAEP may use for its label and under MGF1: the `OAEP-PSSDigestAlgorithms` of +/// RFC 8017 Appendix A.2.1, SHA-1, SHA-224, SHA-256, SHA-384, SHA-512, SHA-512/224 and +/// SHA-512/256. Sealed: the buffers and the strength below are sized for these. +pub trait OaepHash: HashOneShot + HashAlgParams + sealed::Sealed {} + +impl sealed::Sealed for SHA1 {} +impl OaepHash for SHA1 {} +impl sealed::Sealed for SHA224 {} +impl OaepHash for SHA224 {} +impl sealed::Sealed for SHA256 {} +impl OaepHash for SHA256 {} +impl sealed::Sealed for SHA384 {} +impl OaepHash for SHA384 {} +impl sealed::Sealed for SHA512 {} +impl OaepHash for SHA512 {} +impl sealed::Sealed for SHA512_224 {} +impl OaepHash for SHA512_224 {} +impl sealed::Sealed for SHA512_256 {} +impl OaepHash for SHA512_256 {} + +/// RSAES-OAEP at the modulus size `K` with the label hash `H` and MGF1 over `M`: the algorithm +/// the key-establishment keys run under [`OaepParams`], named +/// `RSAES-OAEP-2048-SHA256-MGF1-SHA256` and so on. +/// +/// The encapsulating and key-transporting roles exist at a signing size, RSA-2048 and up, as +/// their private counterparts do. Nothing is encapsulated or transported toward RSA-1024 or +/// RSA-1536: +/// +/// ```compile_fail,E0277 +/// use bouncycastle_core::kem_key::EncapsulatingKey; +/// use bouncycastle_rsa::RSA1024; +/// use bouncycastle_rsa::rsaes_oaep::OaepParams; +/// use bouncycastle_rsa::rsasve::RsaKEMPublicKey; +/// use bouncycastle_sha2::SHA256; +/// +/// type Params = OaepParams<'static, SHA256, SHA256, 32>; +/// fn encapsulates, const N: usize>() {} +/// encapsulates::, 128>(); +/// ``` +/// +/// ```compile_fail,E0277 +/// use bouncycastle_core::key_transport_key::KeyTransportEncryptingKey; +/// use bouncycastle_rsa::RSA1024; +/// use bouncycastle_rsa::rsaes_oaep::OaepParams; +/// use bouncycastle_rsa::rsasve::RsaKEMPublicKey; +/// use bouncycastle_sha2::SHA256; +/// +/// type Params = OaepParams<'static, SHA256>; +/// fn transports, const N: usize>() {} +/// transports::, 128>(); +/// ``` +/// +/// ``` +/// use bouncycastle_core::kem_key::EncapsulatingKey; +/// use bouncycastle_core::key_transport_key::KeyTransportEncryptingKey; +/// use bouncycastle_rsa::RSA2048; +/// use bouncycastle_rsa::rsaes_oaep::OaepParams; +/// use bouncycastle_rsa::rsasve::RsaKEMPublicKey; +/// use bouncycastle_sha2::SHA256; +/// +/// type Kem = OaepParams<'static, SHA256, SHA256, 32>; +/// type Transport = OaepParams<'static, SHA256>; +/// fn encapsulates, const N: usize>() {} +/// fn transports, const N: usize>() {} +/// encapsulates::, 256>(); +/// transports::, 256>(); +/// ``` +#[allow(non_camel_case_types)] +pub struct RSAES_OAEP { + _params: PhantomData<(K, H, M)>, +} + +/// What a hash output of `h_len` bytes can carry as a preimage strength, which for the hashes +/// of [`OaepHash`] is the output's length: OAEP's hashes are used as random oracles, not for +/// collision resistance. +const fn hash_output_strength(h_len: usize) -> SecurityStrength { + match h_len { + 32.. => SecurityStrength::_256bit, + 24..32 => SecurityStrength::_192bit, + 16..24 => SecurityStrength::_128bit, + _ => SecurityStrength::None, + } +} + +/// The lesser of two strengths, in a const. +const fn min_strength(a: SecurityStrength, b: SecurityStrength) -> SecurityStrength { + if (a as u8) < (b as u8) { a } else { b } +} + +impl RSAES_OAEP { + const NAME: ConstStr<64> = + ConstStr::concat(&["RSAES-OAEP-", K::BITS_NAME, "-", H::ALG_NAME, "-MGF1-", M::ALG_NAME]); + + /// The modulus's strength, capped by what each hash's output length can carry. + const STRENGTH: SecurityStrength = min_strength( + K::STRENGTH, + min_strength(hash_output_strength(H::OUTPUT_LEN), hash_output_strength(M::OUTPUT_LEN)), + ); + + /// `k - 2hLen - 2`, the longest message (RFC 8017 §7.1.1 step 1.b). Evaluating it checks + /// §7.1.2 step 1.c, `k >= 2hLen + 2`, at compile time. + const MAX_MESSAGE_LEN: usize = { + assert!(K::K_LEN >= 2 * H::OUTPUT_LEN + 2, "the modulus is too short for this hash"); + K::K_LEN - 2 * H::OUTPUT_LEN - 2 + }; +} + +impl Algorithm for RSAES_OAEP { + const ALG_NAME: &'static str = Self::NAME.as_str(); + const MAX_SECURITY_STRENGTH: SecurityStrength = Self::STRENGTH; +} + +impl KEMAlgorithm for RSAES_OAEP {} + +impl KeyTransportAlgorithm for RSAES_OAEP {} + +/// The parameters of RSAES-OAEP: the label hash `H`, the MGF1 hash `M` (the same hash unless +/// spelled), the label, and for the KEM roles the length `LEN` of the key to transport. +/// +/// The KEM roles check `LEN` against the modulus when they are compiled; RSA-2048 with +/// SHA-256 carries at most 190 bytes, so 190 builds (`tests/rsaes_oaep_tests.rs`) and 191 does +/// not: +/// +/// ```compile_fail,E0080 +/// use bouncycastle_core::kem_key::EncapsulatingKey; +/// use bouncycastle_rng::HashDRBG_SHA512; +/// use bouncycastle_rsa::rsa_2048::RSASVE; +/// use bouncycastle_rsa::rsaes_oaep::OaepParams; +/// use bouncycastle_sha2::SHA256; +/// +/// let mut rng = HashDRBG_SHA512::new_from_os(); +/// let (pk, _sk) = RSASVE::keygen(&mut rng).unwrap(); +/// let _ = pk.encaps(&mut rng, OaepParams::::new(b"")); +/// ``` +pub struct OaepParams<'l, H, M = H, const LEN: usize = 32> { + label: &'l [u8], + _hashes: PhantomData<(H, M)>, +} + +// Not derived: the derive would ask `H: Clone` and `M: Clone` of a marker that holds neither. +impl Clone for OaepParams<'_, H, M, LEN> { + fn clone(&self) -> Self { + *self + } +} + +impl Copy for OaepParams<'_, H, M, LEN> {} + +impl<'l, H, M, const LEN: usize> OaepParams<'l, H, M, LEN> { + /// The parameters with the label `label`, which may be empty (RFC 8017 §7.1.1: "the + /// default value for L, if L is not provided, is the empty string"). + pub fn new(label: &'l [u8]) -> Self { + Self { label, _hashes: PhantomData } + } +} + +/// RSAES-OAEP-ENCRYPT (RFC 8017 §7.1.1) of `msg` under `pk` and `label` into `ct`, which is +/// zeroized first and left so on an error. The caller has checked `mLen <= k - 2hLen - 2` and +/// the RNG's strength. +fn encrypt( + pk: &RsaKEMPublicKey, + label: &[u8], + msg: &[u8], + rng: &mut dyn RNG, + ct: &mut [u8; N], +) -> Result<(), RNGError> +where + K: RsaSigningSize + RsaSize, + H: OaepHash, + M: OaepHash, +{ + ct.fill(0); + let h_len = H::OUTPUT_LEN; + // Step 2.a: lHash = Hash(L). + let mut l_hash = HashBuf::new(); + eme_oaep::label_hash::(label, &mut l_hash); + // Step 2.d: a random octet string seed of length hLen. + let mut seed = HashBuf::new(); + fill_bytes(rng, &mut seed[..h_len])?; + // Steps 2.b to 2.i: EM = 0x00 || maskedSeed || maskedDB. + let mut em = Secret::<[u8; N]>::new(); + eme_oaep::encode::(&l_hash[..h_len], &seed[..h_len], msg, &mut *em); + // Step 3: m = OS2IP(EM); c = RSAEP((n, e), m); C = I2OSP(c, k). EM's leading octet is 0x00 + // and a key-establishment key's modulus has its top bit set, so m < n. + let mut m = Secret::::new(); + *m = K::limbs_from_be_bytes(&em); + let c = K::public_exp(pk.n(), pk.e(), &m); + *ct = K::be_bytes_from_limbs(&c); + Ok(()) +} + +/// RSAES-OAEP-DECRYPT (RFC 8017 §7.1.2) of `ct` under `sk` and `label` into `out`, which is +/// zeroized first and left so on failure: the message length, or `None` for a decryption error +/// of any kind. `exact_len` is as [`eme_oaep::decode_out`]'s. +fn decrypt( + sk: &RsaKEMPrivateKey, + label: &[u8], + ct: &[u8; N], + exact_len: Option, + out: &mut [u8], +) -> Option +where + K: RsaSigningSize + RsaSize, + H: OaepHash, + M: OaepHash, +{ + let len = decrypt_in_own_frame::(sk, label, ct, exact_len, out); + // The encoded message and the seed pass through return slots and through the frames of + // the mask generation; the whole operation's stack is overwritten, the CRT's own wipe + // being inside it. + wipe_stack_below::(); + len +} + +/// What [`wipe_stack_below`] overwrites after RSAES-OAEP-DECRYPT: this many `K::Limbs` values +/// and this many words. Measured in x86-64 release builds (rustc 1.88 and 1.97) with SHA-256, +/// the operation uses 9544 bytes at RSA-2048, 12632 at RSA-3072, 16344 at RSA-4096 and 32232 +/// at RSA-8192; these cover 11008, 15360, 19712 and 37120, the difference being room for a +/// compiler that lays the frames out less tightly. +const DECRYPT_STACK_PER_LIMB: usize = 34; +const DECRYPT_STACK_FIXED: usize = 288; + +/// The work of [`decrypt`]. Never inlined, so that what it leaves lies below its caller's +/// frame, where [`wipe_stack_below`] reaches it. +#[inline(never)] +fn decrypt_in_own_frame( + sk: &RsaKEMPrivateKey, + label: &[u8], + ct: &[u8; N], + exact_len: Option, + out: &mut [u8], +) -> Option +where + K: RsaSigningSize + RsaSize, + H: OaepHash, + M: OaepHash, +{ + out.fill(0); + // Step 2.a: c = OS2IP(C). RFC 8017 step 2.b refuses c >= n ("ciphertext representative + // out of range"); SP 800-56B Rev. 2 §7.2.2.4 step 2.c is narrower, "If the ciphertext + // integer c is not such that 1 < c < (n - 1), output an indication of erroneous input", + // and is what is applied. The ciphertext and the modulus are public, so this branch tells + // an observer nothing it could not compute; the error is the one every failure gives. + let c = K::limbs_from_be_bytes(ct); + if !in_open_range::(&c, sk.n()) { + return None; + } + // Step 2.b: m = RSADP(K, c), constant time in the key, and `m` zero if it failed its check + // (m^e mod n is not c); step 2.c: EM = I2OSP(m, k). + let mut m = Secret::::new(); + let checked = K::crt_exp(&sk.0, &c, &mut m); + let mut em = Secret::<[u8; N]>::new(); + *em = K::be_bytes_from_limbs(&m); + // A failed check must end as the one decryption error, and no sooner or later than a bad + // encoding does, so it is not branched on: it sets EM's first octet, which step 3.g + // refuses when it is not zero ("if Y is nonzero"), and the decoding runs as for any EM. + em[0] |= checked.select(0x00, 0xFF) as u8; + // Step 3. + let mut l_hash = HashBuf::new(); + let h_len = eme_oaep::label_hash::(label, &mut l_hash); + eme_oaep::decode_out::(&l_hash[..h_len], &mut *em, exact_len, out) +} + +/// The transported key into the caller's buffer, typed `CryptographicRandom` at the lesser of +/// `strength` and what its length carries; zeroized first and left so on error. An empty or +/// all-zero key is a value, not an error: the buffer types it `Zeroized`, with no strength. +fn key_into( + bytes: &[u8], + strength: SecurityStrength, + key: &mut KeyMaterial, +) -> Result<(), KeyMaterialError> { + key.zeroize(); + match key.set_bytes_as_type(bytes, KeyType::CryptographicRandom) { + Ok(()) => {} + Err(KeyMaterialError::ActingOnZeroizedKey) => return Ok(()), + Err(e) => { + key.zeroize(); + return Err(e); + } + } + if key.security_strength() > strength { + // Lowering a strength is always permitted. + if let Err(e) = key.set_security_strength(strength) { + key.zeroize(); + return Err(e); + } + } + Ok(()) +} + +/// The worker [`EncapsulatingKey::create_encapsulator`] hands out under [`OaepParams`]: the +/// public key, borrowed, and the parameters. +pub struct RsaOaepEncapsulator<'k, 'l, K: RsaSize, H, M, const LEN: usize> { + pk: &'k RsaKEMPublicKey, + params: OaepParams<'l, H, M, LEN>, +} + +impl Algorithm + for RsaOaepEncapsulator<'_, '_, K, H, M, LEN> +{ + const ALG_NAME: &'static str = RSAES_OAEP::::ALG_NAME; + const MAX_SECURITY_STRENGTH: SecurityStrength = RSAES_OAEP::::MAX_SECURITY_STRENGTH; +} + +impl KEMEncapsulator + for RsaOaepEncapsulator<'_, '_, K, H, M, LEN> +where + K: RsaSigningSize + RsaSize, + H: OaepHash, + M: OaepHash, +{ + /// KTS-OAEP-basic, party U (SP 800-56B Rev. 2 §9.2.3), with the keying material drawn + /// here: `LEN` bytes from `rng` into `ss`, and `C = RSA-OAEP.ENCRYPT(PubKeyV, K, A)` into + /// `ct`. Both buffers are zeroized first and left so on error. + /// + /// # Errors + /// [`KEMError::RNGError`] if `rng` is weaker than the algorithm or fails to deliver. + fn encaps_out( + &self, + rng: &mut dyn RNG, + ct: &mut [u8; N], + ss: &mut KeyMaterial, + ) -> Result { + ct.fill(0); + ss.zeroize(); + if rng.security_strength() < RSAES_OAEP::::STRENGTH { + return Err(KEMError::RNGError(RNGError::SecurityStrengthInsufficientForAlgorithm)); + } + let mut key = Secret::<[u8; LEN]>::new(); + fill_bytes(rng, &mut *key)?; + encrypt::(self.pk, self.params.label, &*key, rng, ct)?; + if let Err(e) = key_into(&*key, RSAES_OAEP::::STRENGTH, ss) { + ct.fill(0); + return Err(e.into()); + } + Ok(N) + } +} + +/// The worker [`DecapsulatingKey::create_decapsulator`] hands out under [`OaepParams`]: the +/// private key, borrowed, and the parameters. +pub struct RsaOaepDecapsulator<'k, 'l, K: RsaSize, H, M, const LEN: usize> { + sk: &'k RsaKEMPrivateKey, + params: OaepParams<'l, H, M, LEN>, +} + +impl Algorithm + for RsaOaepDecapsulator<'_, '_, K, H, M, LEN> +{ + const ALG_NAME: &'static str = RSAES_OAEP::::ALG_NAME; + const MAX_SECURITY_STRENGTH: SecurityStrength = RSAES_OAEP::::MAX_SECURITY_STRENGTH; +} + +impl KEMDecapsulator + for RsaOaepDecapsulator<'_, '_, K, H, M, LEN> +where + K: RsaSigningSize + RsaSize, + H: OaepHash, + M: OaepHash, +{ + /// KTS-OAEP-basic, party V (SP 800-56B Rev. 2 §9.2.3): + /// `K = RSA-OAEP.DECRYPT(PrivKeyV, C, A)` into `ss`, zeroized first and left so on error. + /// A recovered key that is not exactly `LEN` bytes is a decryption error like any other. + /// + /// # Errors + /// [`KEMError::DecapsulationFailed`] for a decryption error of any kind. + fn decaps_out(&self, ct: &[u8; N], ss: &mut KeyMaterial) -> Result { + ss.zeroize(); + let mut key = Secret::<[u8; LEN]>::new(); + decrypt::(self.sk, self.params.label, ct, Some(LEN), &mut *key) + .ok_or(KEMError::DecapsulationFailed)?; + key_into(&*key, RSAES_OAEP::::STRENGTH, ss)?; + Ok(LEN) + } +} + +impl<'l, K, H, M, const N: usize, const LEN: usize> + EncapsulatingKey, N, LEN> for RsaKEMPublicKey +where + K: RsaSigningSize + RsaSize, + H: OaepHash, + M: OaepHash, +{ + type Algorithm = RSAES_OAEP; + type Encapsulator<'k> + = RsaOaepEncapsulator<'k, 'l, K, H, M, LEN> + where + Self: 'k; + + /// Cannot fail: the key length is checked against the modulus at compile time. + fn create_encapsulator<'k>( + &'k self, + params: OaepParams<'l, H, M, LEN>, + ) -> Result, KEMError> { + const { + assert!(LEN > 0, "a key has at least one byte"); + assert!(LEN <= RSAES_OAEP::::MAX_MESSAGE_LEN, "LEN > k - 2hLen - 2"); + } + Ok(RsaOaepEncapsulator { pk: self, params }) + } +} + +impl<'l, K, H, M, const N: usize, const LEN: usize> + DecapsulatingKey, N, LEN> for RsaKEMPrivateKey +where + K: RsaSigningSize + RsaSize, + H: OaepHash, + M: OaepHash, +{ + type Algorithm = RSAES_OAEP; + type Decapsulator<'k> + = RsaOaepDecapsulator<'k, 'l, K, H, M, LEN> + where + Self: 'k; + + /// As [`EncapsulatingKey::create_encapsulator`]: cannot fail. + fn create_decapsulator<'k>( + &'k self, + params: OaepParams<'l, H, M, LEN>, + ) -> Result, KEMError> { + const { + assert!(LEN > 0, "a key has at least one byte"); + assert!(LEN <= RSAES_OAEP::::MAX_MESSAGE_LEN, "LEN > k - 2hLen - 2"); + } + Ok(RsaOaepDecapsulator { sk: self, params }) + } +} + +/// Transport of a key the caller holds: `C = RSA-OAEP.ENCRYPT(PubKeyV, K, A)` (SP 800-56B Rev. 2 +/// §9.2.3, party U). The parameters' `LEN` is not used: the key's own length is. +impl<'l, K, H, M, const N: usize, const LEN: usize> + KeyTransportEncryptingKey, N> for RsaKEMPublicKey +where + K: RsaSigningSize + RsaSize, + H: OaepHash, + M: OaepHash, +{ + type Algorithm = RSAES_OAEP; + + /// `k - 2hLen - 2` (RFC 8017 §7.1.1 step 1.b). + fn max_key_len(&self, _params: OaepParams<'l, H, M, LEN>) -> usize { + RSAES_OAEP::::MAX_MESSAGE_LEN + } + + fn transport_out( + &self, + rng: &mut dyn RNG, + params: OaepParams<'l, H, M, LEN>, + key: &dyn KeyMaterialTrait, + ct: &mut [u8; N], + ) -> Result { + ct.fill(0); + if key.key_type() == KeyType::Zeroized { + return Err(KeyMaterialError::ActingOnZeroizedKey.into()); + } + // RFC 8017 §7.1.1 step 1.b: "If mLen > k - 2hLen - 2, output "message too long" and + // stop." + if key.key_len() > RSAES_OAEP::::MAX_MESSAGE_LEN { + return Err(KeyTransportError::KeyTooLong); + } + if rng.security_strength() < RSAES_OAEP::::STRENGTH { + return Err(RNGError::SecurityStrengthInsufficientForAlgorithm.into()); + } + encrypt::(self, params.label, key.ref_to_bytes(), rng, ct)?; + Ok(N) + } +} + +/// Recovery of a transported key: `K = RSA-OAEP.DECRYPT(PrivKeyV, C, A)` (SP 800-56B Rev. 2 +/// §9.2.3, party V). The parameters' `LEN` is not used: the key is as long as it was sent. +impl<'l, K, H, M, const N: usize, const LEN: usize> + KeyTransportDecryptingKey, N> for RsaKEMPrivateKey +where + K: RsaSigningSize + RsaSize, + H: OaepHash, + M: OaepHash, +{ + type Algorithm = RSAES_OAEP; + + fn recover_out( + &self, + ct: &[u8; N], + params: OaepParams<'l, H, M, LEN>, + key: &mut KeyMaterial, + ) -> Result { + key.zeroize(); + let mut bytes = Secret::<[u8; KEY_LEN]>::new(); + let len = decrypt::(self, params.label, ct, None, &mut *bytes) + .ok_or(KeyTransportError::DecryptionFailed)?; + key_into(&bytes[..len], RSAES_OAEP::::STRENGTH, key)?; + Ok(len) + } +} diff --git a/crypto/rsa/src/rsassa.rs b/crypto/rsa/src/rsassa.rs new file mode 100644 index 000000000..b0bde2145 --- /dev/null +++ b/crypto/rsa/src/rsassa.rs @@ -0,0 +1,468 @@ +//! The signature roles over any RSA signature algorithm: [`RsaSignatureAlgorithm`] is what a +//! scheme-and-hash marker ([`RSASSA_PKCS1_v1_5`](crate::rsassa_pkcs1_v1_5::RSASSA_PKCS1_v1_5), +//! [`RSASSA_PSS`](crate::rsassa_pss::RSASSA_PSS)) implements, the size, +//! the hash and the scheme's EMSA verification, with its signing side on +//! [`RsaDeterministicSignatureAlgorithm`] (PKCS#1 v1.5, which draws nothing) or +//! [`RsaRandomizedSignatureAlgorithm`] (PSS, with its salt); the three workers and the role +//! impls on [`RsaPrivateKey`] and [`RsaPublicKey`] are written once over them, RSASP1 / +//! RSAVP1 around the scheme's encoding (RFC 8017 §8.1.1, §8.1.2, §8.2.1, §8.2.2 and RFC 8702 +//! §3.2.1 as one orchestration). The `*_from_hash` functions take the message hash rather than +//! the message, for a caller that already holds the digest. Sealed: the markers are the +//! library's, so a role impl exists for every pairing and no other. + +use crate::emsa_pkcs1_v1_5::HASH_LEN_ERROR; +use crate::keygen::fill_bytes; +use crate::keys::{RsaPrivateKey, RsaPublicKey}; +use crate::mgf1::MAX_HASH_LEN; +use crate::rsa_core::{rsasp1, rsavp1}; +use crate::size::{RsaSigningSize, RsaSize}; +use bouncycastle_core::errors::SignatureError; +use bouncycastle_core::security_strength::SecurityStrength; +use bouncycastle_core::signature_key::{ + DeterministicOneShotSigningKey, DeterministicSigningKey, OneShotSigningKey, + OneShotVerifyingKey, SignatureAlgorithm, SigningKey, VerifyingKey, sign_out_with_signer, + verify_with_verifier, +}; +use bouncycastle_core::traits::{ + AlgorithmInfo, FinishToken, Hash, HashAlgParams, HashOneShot, RNG, SignatureSigner, + SignatureVerifier, +}; + +/// An RSA signature algorithm: the modulus size, the message hash, and the scheme's EMSA +/// verification. A key over it, [`RsaPrivateKey`] / [`RsaPublicKey`], is a key for it and +/// for nothing else. +/// +/// The encodings' `K_LEN` is the size's modulus length and no other, checked when the method is +/// instantiated: +/// +/// ```compile_fail,E0080 +/// use bouncycastle_rsa::RSA2048; +/// use bouncycastle_rsa::rsassa::RsaSignatureAlgorithm; +/// use bouncycastle_rsa::rsassa_pss::RSASSA_PSS; +/// use bouncycastle_sha2::SHA256; +/// let _ = RSASSA_PSS::::emsa_verify::<128>(&[0u8; 32], &[0u8; 128]); +/// ``` +/// +/// ``` +/// use bouncycastle_rsa::RSA2048; +/// use bouncycastle_rsa::rsassa::RsaSignatureAlgorithm; +/// use bouncycastle_rsa::rsassa_pss::RSASSA_PSS; +/// use bouncycastle_sha2::SHA256; +/// assert!(!RSASSA_PSS::::emsa_verify::<256>(&[0u8; 32], &[0u8; 256])); +/// ``` +pub trait RsaSignatureAlgorithm: SignatureAlgorithm + sealed::Sealed { + /// The modulus size. + type Size: RsaSize; + /// The message hash (for PSS-SHAKE, the XOF read at its hash length). + type Hash: HashOneShot + HashAlgParams; + + /// The scheme's verification of the recovered `EM` against the message hash: EMSA-PKCS1-v1_5's + /// decoding or EMSA-PSS-VERIFY. False for an `m_hash` that is not one output of the hash. + fn emsa_verify(m_hash: &[u8], em: &[u8; K_LEN]) -> bool; +} + +/// An RSA signature algorithm whose encoding takes nothing but the hash: RSASSA-PKCS1-v1_5. Its +/// keys sign through [`DeterministicSigningKey`]. +pub trait RsaDeterministicSignatureAlgorithm: RsaSignatureAlgorithm { + /// EMSA-PKCS1-v1_5-ENCODE of the message hash. + /// + /// # Errors + /// [`SignatureError::LengthError`] if `m_hash` is not one output of the hash. + fn emsa_encode(m_hash: &[u8]) -> Result<[u8; K_LEN], SignatureError>; +} + +/// An RSA signature algorithm whose encoding takes a salt: RSASSA-PSS under salted parameters. +/// Its keys sign through [`SigningKey`], the salt drawn from the RNG when the signer is made. +pub trait RsaRandomizedSignatureAlgorithm: RsaSignatureAlgorithm { + /// The salt length in bytes, at most 64 (`MAX_HASH_LEN`, the signer's buffer). + const SALT_LEN: usize; + + /// EMSA-PSS-ENCODE of the message hash with `salt`, `SALT_LEN` bytes. + /// + /// # Errors + /// [`SignatureError::LengthError`] if `m_hash` is not one output of the hash or `salt` is + /// not `SALT_LEN` bytes; [`SignatureError::EncodingError`] if the modulus is too short for + /// the hash and the salt (RFC 8017 §9.1.1 step 3), which no pairing that signs is. + fn emsa_encode( + m_hash: &[u8], + salt: &[u8], + ) -> Result<[u8; K_LEN], SignatureError>; +} + +/// RSA signatures take no context: RSASSA-PSS-SIGN and RSASSA-PKCS1-V1_5-SIGN (RFC 8017 §8.1.1, +/// §8.2.1) and their verifications are over a key and a message, and nothing else. So `None` and +/// the empty context are accepted and a non-empty one is refused where it is given, when a +/// worker is made, rather than dropped. +fn refuse_context(ctx: Option<&[u8]>) -> Result<(), SignatureError> { + match ctx { + Some(ctx) if !ctx.is_empty() => Err(SignatureError::LengthError("RSA takes no context")), + _ => Ok(()), + } +} + +/// The signer [`SigningKey::create_signer`] hands out for a randomized algorithm: the key, +/// borrowed, the hash state, and the salt drawn when it was made. +pub struct RsaSigner<'k, A: RsaRandomizedSignatureAlgorithm> { + sk: &'k RsaPrivateKey, + hash: A::Hash, + salt: [u8; MAX_HASH_LEN], +} + +impl RsaSigner<'_, A> { + /// Replaces the drawn salt with `salt`, the algorithm's salt length (a compile-time check), + /// for a known-answer test: the signature is then a function of the key and the message + /// alone. + pub fn set_salt(&mut self, salt: [u8; N]) { + const { assert!(N == A::SALT_LEN, "the salt is the algorithm's salt length") }; + self.salt[..N].copy_from_slice(&salt); + } +} + +/// The signer [`DeterministicSigningKey::create_signer_deterministic`] hands out: the key, +/// borrowed, and the hash state. +pub struct RsaDeterministicSigner<'k, A: RsaDeterministicSignatureAlgorithm> { + sk: &'k RsaPrivateKey, + hash: A::Hash, +} + +/// The verifier [`VerifyingKey::create_verifier`] hands out: the key, borrowed, and the hash +/// state. +pub struct RsaVerifier<'k, A: RsaSignatureAlgorithm> { + pk: &'k RsaPublicKey, + hash: A::Hash, +} + +impl SigningKey for RsaPrivateKey +where + A: RsaRandomizedSignatureAlgorithm, + // Only a signing size signs: the verify-only sizes, RSA-1024/1536, do not implement + // RsaSigningSize, so this impl does not exist for them -- the crate's `# Scope` at compile + // time. + A::Size: RsaSigningSize + RsaSize, +{ + type Signer<'k> + = RsaSigner<'k, A> + where + Self: 'k; + + /// Draws EMSA-PSS-ENCODE step 4's salt from `rng` when the signer is made, as ECDSA draws + /// `k`. `ctx` must be `None` or empty, RSA having no context. + /// + /// # Errors + /// [`SignatureError::LengthError`] for a non-empty `ctx`, before anything is drawn; + /// [`SignatureError::RNGError`] if the RNG fails to deliver, a draw shorter than the salt + /// included. + fn create_signer<'k>( + &'k self, + rng: &mut dyn RNG, + ctx: Option<&[u8]>, + ) -> Result, SignatureError> { + const { assert!(A::SALT_LEN <= MAX_HASH_LEN, "the salt fits the signer's buffer") }; + refuse_context(ctx)?; + let mut salt = [0u8; MAX_HASH_LEN]; + fill_bytes(rng, &mut salt[..A::SALT_LEN]).map_err(SignatureError::RNGError)?; + Ok(RsaSigner { sk: self, hash: A::Hash::default(), salt }) + } +} + +impl OneShotSigningKey for RsaPrivateKey +where + A: RsaRandomizedSignatureAlgorithm, + A::Size: RsaSigningSize + RsaSize, +{ + fn sign_out( + &self, + rng: &mut dyn RNG, + msg: &[u8], + ctx: Option<&[u8]>, + output: &mut [u8; K_LEN], + ) -> Result { + let signer = SigningKey::::create_signer(self, rng, ctx); + sign_out_with_signer(signer, msg, output) + } +} + +impl DeterministicSigningKey for RsaPrivateKey +where + A: RsaDeterministicSignatureAlgorithm, + A::Size: RsaSigningSize + RsaSize, +{ + type Signer<'k> + = RsaDeterministicSigner<'k, A> + where + Self: 'k; + + /// `ctx` must be `None` or empty, RSA having no context. + /// + /// # Errors + /// [`SignatureError::LengthError`] for a non-empty `ctx`. + fn create_signer_deterministic<'k>( + &'k self, + ctx: Option<&[u8]>, + ) -> Result, SignatureError> { + refuse_context(ctx)?; + Ok(RsaDeterministicSigner { sk: self, hash: A::Hash::default() }) + } +} + +impl DeterministicOneShotSigningKey for RsaPrivateKey +where + A: RsaDeterministicSignatureAlgorithm, + A::Size: RsaSigningSize + RsaSize, +{ + fn sign_deterministic_out( + &self, + msg: &[u8], + ctx: Option<&[u8]>, + output: &mut [u8; K_LEN], + ) -> Result { + let signer = DeterministicSigningKey::::create_signer_deterministic(self, ctx); + sign_out_with_signer(signer, msg, output) + } +} + +impl VerifyingKey for RsaPublicKey +where + A: RsaSignatureAlgorithm, + A::Size: RsaSize, +{ + type Verifier<'k> + = RsaVerifier<'k, A> + where + Self: 'k; + + /// `ctx` must be `None` or empty, RSA having no context. + /// + /// # Errors + /// [`SignatureError::LengthError`] for a non-empty `ctx`. + fn create_verifier<'k>( + &'k self, + ctx: Option<&[u8]>, + ) -> Result, SignatureError> { + refuse_context(ctx)?; + Ok(RsaVerifier { pk: self, hash: A::Hash::default() }) + } +} + +impl OneShotVerifyingKey for RsaPublicKey +where + A: RsaSignatureAlgorithm, + A::Size: RsaSize, +{ + fn verify(&self, msg: &[u8], ctx: Option<&[u8]>, sig: &[u8]) -> Result<(), SignatureError> { + let verifier = VerifyingKey::::create_verifier(self, ctx)?; + verify_with_verifier(verifier, msg, sig) + } +} + +impl AlgorithmInfo for RsaSigner<'_, A> { + fn alg_name(&self) -> &'static str { + A::ALG_NAME + } + + fn max_security_strength(&self) -> SecurityStrength { + A::MAX_SECURITY_STRENGTH + } +} + +impl SignatureSigner for RsaSigner<'_, A> +where + A: RsaRandomizedSignatureAlgorithm, + A::Size: RsaSigningSize + RsaSize, +{ + fn do_update(&mut self, msg_chunk: &[u8]) { + self.hash.do_update(msg_chunk); + } + + fn finish_signature_into( + &mut self, + token: &FinishToken, + output: &mut [u8; K_LEN], + ) -> Result { + output.fill(0); + let h_len = A::Hash::OUTPUT_LEN; + let mut m_hash = [0u8; MAX_HASH_LEN]; + self.hash.finish_into(token, &mut m_hash[..h_len]); + *output = sign_from_hash_with_salt::( + self.sk, + &m_hash[..h_len], + &self.salt[..A::SALT_LEN], + )?; + Ok(K_LEN) + } +} + +impl AlgorithmInfo for RsaDeterministicSigner<'_, A> { + fn alg_name(&self) -> &'static str { + A::ALG_NAME + } + + fn max_security_strength(&self) -> SecurityStrength { + A::MAX_SECURITY_STRENGTH + } +} + +impl SignatureSigner for RsaDeterministicSigner<'_, A> +where + A: RsaDeterministicSignatureAlgorithm, + A::Size: RsaSigningSize + RsaSize, +{ + fn do_update(&mut self, msg_chunk: &[u8]) { + self.hash.do_update(msg_chunk); + } + + fn finish_signature_into( + &mut self, + token: &FinishToken, + output: &mut [u8; K_LEN], + ) -> Result { + output.fill(0); + let h_len = A::Hash::OUTPUT_LEN; + let mut m_hash = [0u8; MAX_HASH_LEN]; + self.hash.finish_into(token, &mut m_hash[..h_len]); + *output = sign_from_hash_deterministic::(self.sk, &m_hash[..h_len])?; + Ok(K_LEN) + } +} + +impl AlgorithmInfo for RsaVerifier<'_, A> { + fn alg_name(&self) -> &'static str { + A::ALG_NAME + } + + fn max_security_strength(&self) -> SecurityStrength { + A::MAX_SECURITY_STRENGTH + } +} + +impl SignatureVerifier for RsaVerifier<'_, A> +where + A: RsaSignatureAlgorithm, + A::Size: RsaSize, +{ + fn do_update(&mut self, msg_chunk: &[u8]) { + self.hash.do_update(msg_chunk); + } + + fn finish_signature_verify( + &mut self, + token: &FinishToken, + sig: &[u8], + ) -> Result<(), SignatureError> { + // RFC 8017 §8.1.2 / §8.2.2 step 1: a signature of the wrong length is rejected for its + // length. + let sig: &[u8; K_LEN] = sig.try_into().map_err(|_| { + SignatureError::LengthError("RSA signature must be exactly the modulus length") + })?; + let h_len = A::Hash::OUTPUT_LEN; + let mut m_hash = [0u8; MAX_HASH_LEN]; + self.hash.finish_into(token, &mut m_hash[..h_len]); + // Step 2.b: RSAVP1's "signature representative out of range" is "invalid signature" here; + // one answer for every way a signature can fail. + verify_from_hash::(self.pk, &m_hash[..h_len], sig) + .map_err(|_| SignatureError::SignatureVerificationFailed) + } +} + +/// A randomized algorithm's signature of the message hash `m_hash` under `salt` (RFC 8017 +/// §8.1.1 with the salt the caller's): the scheme's encoding, then RSASP1. +/// +/// # Errors +/// [`SignatureError::LengthError`] if `m_hash` is not `A::Hash::OUTPUT_LEN` bytes or `salt` is +/// not `A::SALT_LEN` bytes; [`SignatureError::ComputationFault`] if the result fails RSASP1's +/// check; [`SignatureError::DecodingError`] if the encoded message is not below `n` (RSASP1 +/// step 1), which a correct encoding never is. +pub fn sign_from_hash_with_salt( + sk: &RsaPrivateKey, + m_hash: &[u8], + salt: &[u8], +) -> Result<[u8; K_LEN], SignatureError> +where + A: RsaRandomizedSignatureAlgorithm, + A::Size: RsaSigningSize + RsaSize, +{ + let em = A::emsa_encode::(m_hash, salt)?; + let m = A::Size::limbs_from_be_bytes(&em); + let s = rsasp1::(sk.components(), &m)?; + Ok(A::Size::be_bytes_from_limbs(&s)) +} + +/// A randomized algorithm's signature of the message hash `m_hash`, the salt drawn from `rng`: +/// RFC 8017 §8.1.1. +/// +/// # Errors +/// [`SignatureError::LengthError`] if `m_hash` is not `A::Hash::OUTPUT_LEN` bytes, before +/// anything is drawn; [`SignatureError::RNGError`] if the RNG fails to deliver; else as +/// [`sign_from_hash_with_salt`]. +pub fn sign_from_hash( + sk: &RsaPrivateKey, + m_hash: &[u8], + rng: &mut dyn RNG, +) -> Result<[u8; K_LEN], SignatureError> +where + A: RsaRandomizedSignatureAlgorithm, + A::Size: RsaSigningSize + RsaSize, +{ + const { assert!(A::SALT_LEN <= MAX_HASH_LEN, "the salt fits the buffer") }; + if m_hash.len() != A::Hash::OUTPUT_LEN { + return Err(HASH_LEN_ERROR); + } + let mut salt = [0u8; MAX_HASH_LEN]; + fill_bytes(rng, &mut salt[..A::SALT_LEN]).map_err(SignatureError::RNGError)?; + sign_from_hash_with_salt::(sk, m_hash, &salt[..A::SALT_LEN]) +} + +/// A deterministic algorithm's signature of the message hash `m_hash`: RFC 8017 §8.2.1, the +/// scheme's encoding, then RSASP1. +/// +/// # Errors +/// As [`sign_from_hash_with_salt`], there being no salt. +pub fn sign_from_hash_deterministic( + sk: &RsaPrivateKey, + m_hash: &[u8], +) -> Result<[u8; K_LEN], SignatureError> +where + A: RsaDeterministicSignatureAlgorithm, + A::Size: RsaSigningSize + RsaSize, +{ + let em = A::emsa_encode::(m_hash)?; + let m = A::Size::limbs_from_be_bytes(&em); + let s = rsasp1::(sk.components(), &m)?; + Ok(A::Size::be_bytes_from_limbs(&s)) +} + +/// Verification of `signature` against the message hash `m_hash` (RFC 8017 §8.1.2 / §8.2.2): +/// RSAVP1, then the scheme's verification of the recovered encoding. +/// +/// # Errors +/// [`SignatureError::LengthError`] if `m_hash` is not `A::Hash::OUTPUT_LEN` bytes, +/// [`SignatureError::DecodingError`] if the signature representative is not below `n` +/// (RSAVP1 step 1), [`SignatureError::SignatureVerificationFailed`] if the encoding does not +/// verify. +pub fn verify_from_hash( + pk: &RsaPublicKey, + m_hash: &[u8], + signature: &[u8; K_LEN], +) -> Result<(), SignatureError> +where + A: RsaSignatureAlgorithm, + A::Size: RsaSize, +{ + if m_hash.len() != A::Hash::OUTPUT_LEN { + return Err(HASH_LEN_ERROR); + } + let s = A::Size::limbs_from_be_bytes(signature); + let m = rsavp1::(pk.components(), &s)?; + let em = A::Size::be_bytes_from_limbs(&m); + if A::emsa_verify::(m_hash, &em) { + Ok(()) + } else { + Err(SignatureError::SignatureVerificationFailed) + } +} + +mod sealed { + pub trait Sealed {} + impl Sealed for crate::rsassa_pkcs1_v1_5::RSASSA_PKCS1_v1_5 {} + impl Sealed for crate::rsassa_pss::RSASSA_PSS {} +} diff --git a/crypto/rsa/src/rsassa_pkcs1_v1_5.rs b/crypto/rsa/src/rsassa_pkcs1_v1_5.rs new file mode 100644 index 000000000..d15684970 --- /dev/null +++ b/crypto/rsa/src/rsassa_pkcs1_v1_5.rs @@ -0,0 +1,86 @@ +//! RSASSA-PKCS1-v1_5 (RFC 8017 §8.2) over the modulus size `K` ([`RsaSize`]) and the hash `H`: +//! [`RSASSA_PKCS1_v1_5`] is the algorithm marker a key names, named +//! `RSASSA-PKCS1-v1_5-` at the lesser of the size's and the hash's strength, and its +//! [`RsaDeterministicSignatureAlgorithm`] impl is `emsa_pkcs1_v1_5`'s deterministic encoding; +//! the keys, the workers and the `*_from_hash` entry points are [`crate::rsassa`]'s, once over +//! every algorithm. + +use crate::emsa_pkcs1_v1_5::{emsa_pkcs1_v1_5_encode_from_hash, emsa_pkcs1_v1_5_verify_from_hash}; +use crate::rsassa::{RsaDeterministicSignatureAlgorithm, RsaSignatureAlgorithm}; +use crate::size::{RsaSize, min_strength}; +use bouncycastle_core::errors::SignatureError; +use bouncycastle_core::security_strength::SecurityStrength; +use bouncycastle_core::signature_key::SignatureAlgorithm; +use bouncycastle_core::traits::{ + Algorithm, AlgorithmOID, CollisionResistantHash, HashAlgParams, HashOneShot, +}; +use bouncycastle_utils::const_str::ConstStr; +use core::marker::PhantomData; + +/// RSASSA-PKCS1-v1_5 (RFC 8017 §8.2) over the hash `H` at the modulus size `K`: the algorithm +/// marker the key role traits are implemented over, named `RSASSA-PKCS1-v1_5-` +/// (`RSASSA-PKCS1-v1_5-SHA256`), at the lesser of the size's and the hash's strength. +/// [`RsaPrivateKey`](crate::keys::RsaPrivateKey) signs through [`DeterministicSigningKey`](bouncycastle_core::signature_key::DeterministicSigningKey) at a signing size: PKCS#1 v1.5 +/// draws nothing, so the same key and message always give the same signature. +/// [`RsaPublicKey`](crate::keys::RsaPublicKey) verifies through [`VerifyingKey`](bouncycastle_core::signature_key::VerifyingKey) at any size. The key names +/// the marker, so a call names nothing: `sk.sign_deterministic(msg, None)`. +/// `ctx` must be `None` or empty, since RSA has no context: a non-empty one is a +/// [`SignatureError::LengthError`] from signing and from verification. +/// +/// Signing requires a [`CollisionResistantHash`]; verification does not. A key over SHA-1 +/// verifies and does not sign: +/// +/// ```compile_fail,E0277 +/// use bouncycastle_core::signature_key::DeterministicOneShotSigningKey; +/// use bouncycastle_rsa::RSA2048; +/// use bouncycastle_rsa::keys::RsaPrivateComponents; +/// use bouncycastle_rsa::rsassa_pkcs1_v1_5::RSASSA_PKCS1_v1_5; +/// use bouncycastle_digest::sha1::SHA1; +/// +/// let z = [0u64; 16]; +/// let sk = RsaPrivateComponents::::from_crt_components(&z, &z, &z, &z, &z, 65537).unwrap(); +/// let sk = sk.key::>(); +/// let _ = DeterministicOneShotSigningKey::, 256>::sign_deterministic( +/// &sk, b"message", None, +/// ); +/// ``` +/// +/// A caller who must make such a signature names the hash as +/// [`WithoutCollisionResistance`](bouncycastle_core::hazmat::WithoutCollisionResistance). +#[allow(non_camel_case_types)] +pub struct RSASSA_PKCS1_v1_5 { + _params: PhantomData<(K, H)>, +} + +impl RSASSA_PKCS1_v1_5 { + const NAME: ConstStr<40> = ConstStr::concat(&["RSASSA-PKCS1-v1_5-", H::ALG_NAME]); +} + +impl Algorithm for RSASSA_PKCS1_v1_5 { + const ALG_NAME: &'static str = Self::NAME.as_str(); + const MAX_SECURITY_STRENGTH: SecurityStrength = + min_strength(K::STRENGTH, H::MAX_SECURITY_STRENGTH); +} + +impl SignatureAlgorithm for RSASSA_PKCS1_v1_5 {} + +impl RsaSignatureAlgorithm + for RSASSA_PKCS1_v1_5 +{ + type Size = K; + type Hash = H; + + fn emsa_verify(m_hash: &[u8], em: &[u8; K_LEN]) -> bool { + const { assert!(K_LEN == K::K_LEN, "K_LEN is the size's modulus length") }; + emsa_pkcs1_v1_5_verify_from_hash::(m_hash, em) + } +} + +impl + RsaDeterministicSignatureAlgorithm for RSASSA_PKCS1_v1_5 +{ + fn emsa_encode(m_hash: &[u8]) -> Result<[u8; K_LEN], SignatureError> { + const { assert!(K_LEN == K::K_LEN, "K_LEN is the size's modulus length") }; + emsa_pkcs1_v1_5_encode_from_hash::(m_hash) + } +} diff --git a/crypto/rsa/src/rsassa_pss.rs b/crypto/rsa/src/rsassa_pss.rs new file mode 100644 index 000000000..cafd8b0f6 --- /dev/null +++ b/crypto/rsa/src/rsassa_pss.rs @@ -0,0 +1,266 @@ +//! RSASSA-PSS (RFC 8017 §8.1) over the modulus size `K` ([`RsaSize`]), the hash `H` and the +//! parameters `P` that EMSA-PSS is parameterized by beyond the hash (§9.1: the mask generation +//! function and the salt length): [`RSASSA_PSS`] is the algorithm marker a key names. +//! `P` is [`Conventional`] unless spelled, what [`PssHash`] says the hash is conventionally +//! paired with: MGF1 over `H` and a salt one hash output long for SHA-2 and SHA-3, the §8.1 +//! recommendation and §9.1 note 4's "typical" choice, and for SHAKE128/256 the XOF itself as +//! the mask (RFC 8702 §3.2.1), so `RSASSA_PSS` is RSASSA-PSS-SHAKE128; +//! [`Mgf1`] spells another MGF1 hash or salt length, which §8.1 allows ("the provable security of +//! RSASSA-PSS does not rely on the hash function in the mask generation function being the same +//! as the hash function applied to the message"; matching them prevents hash substitution, which +//! a key that names its hash prevents anyway); and [`NoSalt`] is the zero salt of §9.1 note 4, +//! which makes the scheme deterministic and its keys sign through `DeterministicSigningKey`. A +//! key is for one `(H, P)`, so a verifier never guesses the mask or the salt length. The keys, +//! the workers and the `*_from_hash` entry points are [`crate::rsassa`]'s, once over every +//! algorithm; the encoding is `emsa_pss`'s, once over `H` and `P`. + +use crate::emsa_pss::{emsa_pss_encode_from_hash, emsa_pss_verify_from_hash}; +use crate::mgf1::{MAX_HASH_LEN, mgf1}; +use crate::rsassa::{ + RsaDeterministicSignatureAlgorithm, RsaRandomizedSignatureAlgorithm, RsaSignatureAlgorithm, +}; +use crate::size::{RsaSize, min_strength}; +use bouncycastle_core::errors::SignatureError; +use bouncycastle_core::security_strength::SecurityStrength; +use bouncycastle_core::signature_key::SignatureAlgorithm; +use bouncycastle_core::traits::{ + Algorithm, CollisionResistantHash, HashAlgParams, HashOneShot, XOF, +}; +use bouncycastle_sha2::{SHA256InitValue, SHA256Internal, SHA512InitValue, SHA512Internal}; +use bouncycastle_sha3::{SHA3Internal, SHA3Params, SHAKEInternal, SHAKEParams}; +use bouncycastle_utils::const_str::ConstStr; +use core::marker::PhantomData; + +/// A hash and how RSASSA-PSS conventionally uses it, which [`Conventional`] reads: SHA-2 and +/// SHA-3 through MGF1 over the same hash with a salt one output long (RFC 8017 §8.1, §9.1 +/// note 4), SHAKE128 and SHAKE256 natively as the mask with a salt of the output length +/// RFC 8702 §3.2.1 fixes (32 and 64 bytes). Implemented for this workspace's SHA-2, SHA-3 and +/// SHAKE types; another hash takes spelled parameters, [`Mgf1`]. +pub trait PssHash: HashOneShot + HashAlgParams { + /// `sLen` under the conventional parameters. + const SALT_LEN: usize; + /// The conventional `MGF(seed, maskLen)`: `mask` filled from `seed`. + fn mask(seed: &[u8], mask: &mut [u8]); +} + +impl PssHash for SHA256Internal

+where + Self: HashOneShot + HashAlgParams, +{ + const SALT_LEN: usize = Self::OUTPUT_LEN; + + fn mask(seed: &[u8], mask: &mut [u8]) { + mgf1::(seed, mask); + } +} + +impl PssHash for SHA512Internal

+where + Self: HashOneShot + HashAlgParams, +{ + const SALT_LEN: usize = Self::OUTPUT_LEN; + + fn mask(seed: &[u8], mask: &mut [u8]) { + mgf1::(seed, mask); + } +} + +impl PssHash for SHA3Internal

+where + Self: HashOneShot + HashAlgParams, +{ + const SALT_LEN: usize = Self::OUTPUT_LEN; + + fn mask(seed: &[u8], mask: &mut [u8]) { + mgf1::(seed, mask); + } +} + +impl PssHash for SHAKEInternal

+where + Self: XOF + HashOneShot + HashAlgParams, +{ + const SALT_LEN: usize = Self::OUTPUT_LEN; + + fn mask(seed: &[u8], mask: &mut [u8]) { + Self::default().xof_out(seed, mask); + } +} + +/// What EMSA-PSS is parameterized by beyond its hash `H` (RFC 8017 §9.1): the mask generation +/// function and the salt length. Implemented by [`Conventional`], [`Mgf1`] and [`NoSalt`]; a +/// caller may implement it for a mask of its own. +pub trait PssParams { + /// `sLen`, the salt length in bytes; at most 64 (`MAX_HASH_LEN`, the signer's buffer). + const SALT_LEN: usize; + /// What the algorithm name says after `RSASSA-PSS-`: nothing for the conventional + /// pairing, `-MGF1--` for a spelled one. + const NAME_SUFFIX: ConstStr<32>; + /// `MGF(seed, maskLen)`: `mask` filled from `seed`. + fn mask(seed: &[u8], mask: &mut [u8]); +} + +/// The parameters whose salt is drawn: a key over them signs through `SigningKey`. +pub trait SaltedPss {} + +/// The parameters with no salt: a key over them signs through `DeterministicSigningKey`. +pub trait UnsaltedPss {} + +/// The hash's conventional parameters ([`PssHash`]): MGF1 over the message hash and a salt one +/// hash output long for SHA-2 and SHA-3, the XOF as the mask for SHAKE. The default. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] +pub struct Conventional; + +impl PssParams for Conventional { + const SALT_LEN: usize = H::SALT_LEN; + const NAME_SUFFIX: ConstStr<32> = ConstStr::concat(&[]); + + fn mask(seed: &[u8], mask: &mut [u8]) { + H::mask(seed, mask); + } +} + +impl SaltedPss for Conventional {} + +/// MGF1 over `M`, which need not be the message hash, and a salt of `SALT_LEN` bytes, at least +/// one: the parameters a key made elsewhere may carry (the ASN.1 parameters of RFC 8017 +/// Appendix A.2.3 name the mask's hash and the salt length separately). Named +/// `-MGF1--`. +pub struct Mgf1 { + _hash: PhantomData, +} + +impl PssParams + for Mgf1 +{ + const SALT_LEN: usize = { + assert!(SALT_LEN > 0 && SALT_LEN <= MAX_HASH_LEN, "a drawn salt is 1 to 64 bytes"); + SALT_LEN + }; + const NAME_SUFFIX: ConstStr<32> = + ConstStr::concat(&["-MGF1-", M::ALG_NAME, "-", ConstStr::<8>::decimal(SALT_LEN).as_str()]); + + fn mask(seed: &[u8], mask: &mut [u8]) { + mgf1::(seed, mask); + } +} + +impl SaltedPss for Mgf1 {} + +/// MGF1 over `M` and no salt, RFC 8017 §9.1 note 4's other typical length: the encoding is a +/// function of the key and the message alone, so the keys sign through +/// `DeterministicSigningKey`. Named `-MGF1--0`. +pub struct NoSalt { + _hash: PhantomData, +} + +impl PssParams for NoSalt { + const SALT_LEN: usize = 0; + const NAME_SUFFIX: ConstStr<32> = ConstStr::concat(&["-MGF1-", M::ALG_NAME, "-0"]); + + fn mask(seed: &[u8], mask: &mut [u8]) { + mgf1::(seed, mask); + } +} + +impl UnsaltedPss for NoSalt {} + +/// RSASSA-PSS over the size `K`, the hash `H` and the parameters `P` (see the module docs): the +/// algorithm marker a key names, `RSASSA-PSS-` for the conventional parameters +/// (`RSASSA-PSS-SHA256`, `RSASSA-PSS-SHAKE128`) and `RSASSA-PSS--MGF1--` +/// for spelled ones, at the lesser of the size's and the hash's strength (§8.1: the mask's hash +/// does not enter the proof). A key over it signs through `SigningKey`, +/// `sk.sign(&mut rng, msg, None)`, or for [`NoSalt`] through `DeterministicSigningKey`, +/// `sk.sign_deterministic(msg, None)`; `ctx` must be `None` or empty, since RSA has no +/// context: a non-empty one is a [`SignatureError::LengthError`] from signing and from +/// verification. +/// +/// Signing requires a [`CollisionResistantHash`] as `H` (the mask's hash is not bound by it); +/// verification does not. A key over SHA-1 verifies and does not sign, salted or not: +/// +/// ```compile_fail,E0277 +/// use bouncycastle_core::signature_key::OneShotSigningKey; +/// use bouncycastle_rng::DefaultRNG; +/// use bouncycastle_rsa::RSA2048; +/// use bouncycastle_rsa::keys::RsaPrivateComponents; +/// use bouncycastle_rsa::rsassa_pss::{Mgf1, RSASSA_PSS}; +/// use bouncycastle_digest::sha1::SHA1; +/// +/// type Alg = RSASSA_PSS>; +/// let z = [0u64; 16]; +/// let sk = RsaPrivateComponents::::from_crt_components(&z, &z, &z, &z, &z, 65537).unwrap(); +/// let sk = sk.key::(); +/// let _ = OneShotSigningKey::::sign(&sk, &mut DefaultRNG::default(), b"message", None); +/// ``` +/// +/// ```compile_fail,E0277 +/// use bouncycastle_core::signature_key::DeterministicOneShotSigningKey; +/// use bouncycastle_rsa::RSA2048; +/// use bouncycastle_rsa::keys::RsaPrivateComponents; +/// use bouncycastle_rsa::rsassa_pss::{NoSalt, RSASSA_PSS}; +/// use bouncycastle_digest::sha1::SHA1; +/// +/// type Alg = RSASSA_PSS>; +/// let z = [0u64; 16]; +/// let sk = RsaPrivateComponents::::from_crt_components(&z, &z, &z, &z, &z, 65537).unwrap(); +/// let sk = sk.key::(); +/// let _ = DeterministicOneShotSigningKey::::sign_deterministic(&sk, b"message", None); +/// ``` +#[allow(non_camel_case_types)] +pub struct RSASSA_PSS { + _params: PhantomData<(K, H, P)>, +} + +impl> RSASSA_PSS { + const NAME: ConstStr<80> = + ConstStr::concat(&["RSASSA-PSS-", H::ALG_NAME, P::NAME_SUFFIX.as_str()]); +} + +impl> Algorithm for RSASSA_PSS { + const ALG_NAME: &'static str = Self::NAME.as_str(); + const MAX_SECURITY_STRENGTH: SecurityStrength = + min_strength(K::STRENGTH, H::MAX_SECURITY_STRENGTH); +} + +impl> SignatureAlgorithm for RSASSA_PSS {} + +impl> RsaSignatureAlgorithm + for RSASSA_PSS +{ + type Size = K; + type Hash = H; + + fn emsa_verify(m_hash: &[u8], em: &[u8; K_LEN]) -> bool { + const { assert!(K_LEN == K::K_LEN, "K_LEN is the size's modulus length") }; + emsa_pss_verify_from_hash::(m_hash, em) + } +} + +impl< + K: RsaSize, + H: HashOneShot + HashAlgParams + CollisionResistantHash, + P: PssParams + SaltedPss, +> RsaRandomizedSignatureAlgorithm for RSASSA_PSS +{ + const SALT_LEN: usize = P::SALT_LEN; + + fn emsa_encode( + m_hash: &[u8], + salt: &[u8], + ) -> Result<[u8; K_LEN], SignatureError> { + const { assert!(K_LEN == K::K_LEN, "K_LEN is the size's modulus length") }; + emsa_pss_encode_from_hash::(m_hash, salt) + } +} + +impl< + K: RsaSize, + H: HashOneShot + HashAlgParams + CollisionResistantHash, + P: PssParams + UnsaltedPss, +> RsaDeterministicSignatureAlgorithm for RSASSA_PSS +{ + fn emsa_encode(m_hash: &[u8]) -> Result<[u8; K_LEN], SignatureError> { + const { assert!(K_LEN == K::K_LEN, "K_LEN is the size's modulus length") }; + emsa_pss_encode_from_hash::(m_hash, &[]) + } +} diff --git a/crypto/rsa/src/rsasve.rs b/crypto/rsa/src/rsasve.rs new file mode 100644 index 000000000..effbe710f --- /dev/null +++ b/crypto/rsa/src/rsasve.rs @@ -0,0 +1,474 @@ +//! RSASVE, RSA Secret-Value Encapsulation (NIST SP 800-56B Rev. 2 §7.2.1), as a +//! [`bouncycastle_core`] KEM on the key objects: the KEM-only key types [`RsaKEMPublicKey`] and +//! [`RsaKEMPrivateKey`] implement the `EncapsulatingKey` / `DecapsulatingKey` roles over `()` +//! at every signing size, naming [`RSASVE`](RSASVE) as the algorithm and handing out the workers +//! [`RsasveEncapsulator`] and [`RsasveDecapsulator`], whose `encaps_out` is RSASVE.GENERATE +//! (§7.2.1.2) and whose `decaps_out` is RSASVE.RECOVER (§7.2.1.3). +//! +//! This is the scheme BC FIPS Java 2.0 exposes as `FipsRSA.KTS_SVE` (JCA name `RSA-KAS-KEM`): the +//! encapsulating party draws a random `z` with `1 < z < n - 1` and sends `C = z^e mod n`, and both +//! parties end up holding `Z = I2BS(z, nLen)`. The shared secret *is* `Z`, the raw secret value, at +//! the modulus's full byte length. It is not a derived key. SP 800-56B Rev. 2 uses RSASVE only +//! inside its KAS1/KAS2 key-agreement schemes (§8.2, §8.3), which always pass `Z` through a key- +//! derivation method (§5.5, i.e. SP 800-56C) before use. Doing that is the caller's job here, +//! as with every other KEM in this workspace. See the crate docs' `# Security Considerations`. +//! +//! # Key separation +//! +//! The key types here wrap the signature schemes' [`RsaPublicComponents`]/[`RsaPrivateComponents`] rather than +//! reusing them, so the type system keeps key-establishment and signing keys apart. There is no +//! signing-role impl for an [`RsaKEMPrivateKey`] and no decapsulating role for an +//! [`RsaPrivateComponents`]. SP 800-56B Rev. 2 §6.1 item 5 is the requirement: "One key pair shall not +//! be used for different cryptographic purposes (for example, a digital-signature key pair shall +//! not be used for key establishment or vice versa)". BC FIPS Java checks the same thing at runtime with +//! `canBeUsed(ENCRYPT_OR_DECRYPT)`. Nothing stops a caller from building both kinds of key from +//! the same CRT components, and nothing can. +//! +//! # Key validation +//! +//! On top of what [`RsaPublicComponents::new`]/[`RsaPrivateComponents::from_crt_components`] already check, +//! the KEM keys enforce `65,537 <= e` (§6.2.1 item 2, "65,537 ≤ e < 2^256"; the upper bound +//! holds by construction, because `e` is a `u64`), the private key on the `e` it carries. +//! +//! Among the components' own checks, one matters here in particular: `n` is exactly the size's +//! `nLen` bits long, i.e. its top bit is set. §6.2.1 item 1 gives the key an `nBits`, and +//! §6.4.2.2's partial public-key validation requires "that the bit length of the modulus shall +//! be a length that is approved in this Recommendation". A 2048-bit key type holding a shorter +//! modulus would also break RSASVE.GENERATE's `nLen`, which is fixed at `K::K_LEN` bytes here. +//! And with the top bit set, each draw of step 2's rejection loop succeeds with probability +//! above one half. +//! +//! The rest of SP 800-89 §5.3.3's plausibility tests, which §6.4.2.2 also requires, are not +//! performed (beyond `n` odd and `e` odd, which [`RsaPublicComponents::new`] checks). Nothing here +//! amounts to full public-key validation, which §6.4.2.2 notes "is not specified in this +//! Recommendation". + +use crate::keygen::{fill_bytes, keygen_as}; +use crate::keys::{RsaPrivateComponents, RsaPublicComponents, decoding_error}; +use crate::rsa_core::wipe_stack_below; +use crate::size::{RsaSigningSize, RsaSize}; +use bouncycastle_core::errors::{KEMError, KeyDecodingError, RNGError, SignatureError}; +use bouncycastle_core::hazmat::do_hazardous_operations; +use bouncycastle_core::kem_key::{DecapsulatingKey, EncapsulatingKey, KEMAlgorithm}; +use bouncycastle_core::key_material::{KeyMaterial, KeyMaterialTrait, KeyType}; +use bouncycastle_core::security_strength::SecurityStrength; +use bouncycastle_core::traits::{ + Algorithm, KEMDecapsulator, KEMEncapsulator, PrivateKey, PublicKey, RNG, +}; +use bouncycastle_utils::const_str::ConstStr; +use bouncycastle_utils::secret::{Secret, ZeroizablePrimitive}; +use core::fmt; +use core::fmt::{Display, Formatter}; +use core::marker::PhantomData; + +/// The smallest public exponent SP 800-56B Rev. 2 §6.2.1 item 2 allows a key-establishment key. +pub const MIN_PUBLIC_EXPONENT: u64 = 65537; + +/// What both key types return for an `e` below [`MIN_PUBLIC_EXPONENT`]. +const EXPONENT_TOO_SMALL: KEMError = + KEMError::DecodingError("RSA key-establishment public exponent must be at least 65537"); + +/// How many draws RSASVE.GENERATE (§7.2.1.2 step 2) makes before giving up on an RNG whose +/// output never lands in `(1, n - 1)`: with the modulus's top bit set each draw succeeds with +/// probability above one half, so a genuine RNG fails this `2^-128` of the time. +pub const MAX_GENERATE_ATTEMPTS: usize = 128; + +fn kem_error(e: SignatureError) -> KEMError { + match e { + SignatureError::DecodingError(msg) => KEMError::DecodingError(msg), + SignatureError::RNGError(e) => KEMError::RNGError(e), + SignatureError::GenericError(s) => KEMError::GenericError(s), + _ => KEMError::GenericError("unexpected error from the RSA key layer"), + } +} + +/// A KEM key constructor's failure as the error a key's `from_bytes` returns, keeping the +/// message of a decoding failure, which is the only kind `from_rsa_key` produces. +fn kem_decoding_error(e: KEMError) -> KeyDecodingError { + match e { + KEMError::DecodingError(msg) => KeyDecodingError(msg), + _ => KeyDecodingError("invalid RSA key encoding"), + } +} + +/// Whether `1 < x < n - 1` (§7.2.1.2 step 2's range, §7.1.2.3 step 1's check). +pub(crate) fn in_open_range(x: &K::Limbs, n: &K::Limbs) -> bool { + // `n` is odd (every key type here checks it), so `n - 1` is `n` with its low bit cleared and + // needs no borrow propagation. + let mut n_minus_1 = *n; + n_minus_1.as_mut()[0] &= !1; + let mut one = K::Limbs::ZEROED; + one.as_mut()[0] = 1; + K::is_less(x, &n_minus_1) && K::is_less(&one, x) +} + +/// An RSA key-establishment public key at the size `K`: [`RsaPublicComponents`] under the KEM roles +/// and the `# Key validation` checks, encoded as it is. +/// +/// The roles exist at a signing size, RSA-2048 and up, as the private key's do. RSA-1024 and +/// RSA-1536 verify signatures and nothing else, so nothing encapsulates toward them: +/// +/// ```compile_fail,E0277 +/// use bouncycastle_core::kem_key::EncapsulatingKey; +/// use bouncycastle_rsa::RSA1024; +/// use bouncycastle_rsa::rsasve::RsaKEMPublicKey; +/// +/// fn encapsulates, const N: usize>() {} +/// encapsulates::, 128>(); +/// ``` +/// +/// ``` +/// use bouncycastle_core::kem_key::EncapsulatingKey; +/// use bouncycastle_rsa::RSA2048; +/// use bouncycastle_rsa::rsasve::RsaKEMPublicKey; +/// +/// fn encapsulates, const N: usize>() {} +/// encapsulates::, 256>(); +/// ``` +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct RsaKEMPublicKey(pub(crate) RsaPublicComponents); + +impl RsaKEMPublicKey { + /// Builds a public key from its modulus and exponent. Returns + /// `Err(`[`KEMError::DecodingError`]`)` in the cases [`RsaPublicComponents::new`] rejects, and also + /// if `e < 65,537` (see the module docs' `# Key validation`). + pub fn new(n: &K::Limbs, e: u64) -> Result { + Self::from_rsa_key(RsaPublicComponents::new(n, e).map_err(kem_error)?) + } + + pub(crate) fn from_rsa_key(pk: RsaPublicComponents) -> Result { + if pk.e() < MIN_PUBLIC_EXPONENT { + return Err(EXPONENT_TOO_SMALL); + } + Ok(Self(pk)) + } + + /// The modulus `n`, as little-endian limbs. + pub fn n(&self) -> &K::Limbs { + self.0.n() + } + + /// The public exponent `e`. + pub fn e(&self) -> u64 { + self.0.e() + } +} + +/// `RsaKEMPublicKey { n: , e: }`, `n` as one big-endian hex string; public +/// data only. +impl Display for RsaKEMPublicKey { + fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { + write!(f, "RsaKEMPublicKey<{}> {{ n: ", K::NAME)?; + for limb in self.0.n().as_ref().iter().rev() { + write!(f, "{limb:016x}")?; + } + write!(f, ", e: {:x} }}", self.0.e()) + } +} + +/// An RSA key-establishment private key at the size `K`: [`RsaPrivateComponents`] under the KEM roles +/// and the `# Key validation` checks, encoded as it is. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct RsaKEMPrivateKey(pub(crate) RsaPrivateComponents); + +impl RsaKEMPrivateKey { + /// Builds a private key from its CRT components and the public exponent of its key pair. + /// Returns `Err(`[`KEMError::DecodingError`]`)` in the cases + /// [`RsaPrivateComponents::from_crt_components`] rejects, and also if `e < 65,537` (see the + /// module docs' `# Key validation`). + pub fn from_crt_components( + p: &K::HalfLimbs, + q: &K::HalfLimbs, + d_p: &K::HalfLimbs, + d_q: &K::HalfLimbs, + q_inv: &K::HalfLimbs, + e: u64, + ) -> Result { + RsaPrivateComponents::from_crt_components_as(p, q, d_p, d_q, q_inv, e, |components| { + Self::from_rsa_key(components.map_err(kem_error)?) + }) + } + + pub(crate) fn from_rsa_key(sk: RsaPrivateComponents) -> Result { + if sk.e() < MIN_PUBLIC_EXPONENT { + return Err(EXPONENT_TOO_SMALL); + } + Ok(Self(sk)) + } + + /// The modulus `n = p * q`, as little-endian limbs. + pub fn n(&self) -> &K::Limbs { + self.0.n() + } + + /// The public exponent `e` of the key pair. + pub fn e(&self) -> u64 { + self.0.e() + } +} + +impl RsaKEMPrivateKey { + /// Validates the key pair as [`RsaPrivateComponents::validate`] does: SP 800-56B Rev. 2 + /// §6.4.1.4.3, for a key from elsewhere. + /// + /// # Errors + /// Those of [`RsaPrivateComponents::validate`], as the [`KEMError`] of the same name. + pub fn validate(&self, rng: &mut dyn RNG) -> Result<(), KEMError> { + self.0.validate(rng).map_err(kem_error) + } +} + +/// RSASVE (SP 800-56B Rev. 2 §7.2.1) at the modulus size `K`: the algorithm the KEM key types +/// name, `RSASVE-2048` and so on, at the size's strength. The ciphertext and the shared secret +/// are each `nLen = K::K_LEN` bytes. +#[allow(non_camel_case_types)] +pub struct RSASVE { + _size: PhantomData, +} + +impl RSASVE { + const NAME: ConstStr<16> = ConstStr::concat(&["RSASVE-", K::BITS_NAME]); +} + +impl RSASVE { + /// The same FIPS 186-5 Appendix A.1.3 generator the signature keys use, in the KEM key types. + /// + /// # Errors + /// As [`RsaSigningSize::keygen`], as a [`KEMError`]. + pub fn keygen( + rng: &mut dyn RNG, + ) -> Result<(RsaKEMPublicKey, RsaKEMPrivateKey), KEMError> { + keygen_as::(rng, keygen_from::) + } +} + +impl Algorithm for RSASVE { + const ALG_NAME: &'static str = Self::NAME.as_str(); + const MAX_SECURITY_STRENGTH: SecurityStrength = K::STRENGTH; +} + +impl KEMAlgorithm for RSASVE {} + +/// The worker [`EncapsulatingKey::create_encapsulator`] hands out: the public key, borrowed. +pub struct RsasveEncapsulator<'k, K: RsaSize> { + pk: &'k RsaKEMPublicKey, +} + +impl Algorithm for RsasveEncapsulator<'_, K> { + const ALG_NAME: &'static str = RSASVE::::ALG_NAME; + const MAX_SECURITY_STRENGTH: SecurityStrength = RSASVE::::MAX_SECURITY_STRENGTH; +} + +impl KEMEncapsulator for RsasveEncapsulator<'_, K> +where + // A signing size, as the decapsulator's is: nothing is encapsulated toward RSA-1024 or + // RSA-1536, which verify signatures and do nothing else (the crate's `# Scope`). + K: RsaSigningSize + RsaSize, +{ + /// RSASVE.GENERATE (§7.2.1.2): `Z` from the RNG until `1 < z < n - 1` (step 2), `C = z^e mod + /// n` (step 3) into `ct`, and `Z` into `ss` typed `CryptographicRandom` at the size's + /// strength (step 4's output). Both buffers are zeroized first and left so on error. + #[allow(non_snake_case)] + fn encaps_out( + &self, + rng: &mut dyn RNG, + ct: &mut [u8; N], + ss: &mut KeyMaterial, + ) -> Result { + ct.fill(0); + ss.zeroize(); + if rng.security_strength() < K::STRENGTH { + return Err(KEMError::RNGError(RNGError::SecurityStrengthInsufficientForAlgorithm)); + } + let mut Z = Secret::<[u8; N]>::new(); + let mut z = Secret::::new(); + let mut attempts = 0; + loop { + if attempts == MAX_GENERATE_ATTEMPTS { + return Err(KEMError::GenericError( + "RSASVE.GENERATE: RNG output never fell within (1, n - 1)", + )); + } + attempts += 1; + fill_bytes(rng, &mut *Z)?; + *z = K::limbs_from_be_bytes(&Z); + if in_open_range::(&z, self.pk.n()) { + break; + } + } + let c = K::public_exp(self.pk.n(), self.pk.e(), &z); + *ct = K::be_bytes_from_limbs(&c); + if let Err(e) = secret_value_into::(&Z, ss) { + ct.fill(0); + return Err(e); + } + Ok(N) + } +} + +/// `Z` into the caller's buffer, typed `CryptographicRandom` (§7.2.1.2 step 2 draws it so) at +/// the size's strength; zeroized first and left so on error. +#[allow(non_snake_case)] +fn secret_value_into( + Z: &[u8; N], + ss: &mut KeyMaterial, +) -> Result<(), KEMError> { + ss.zeroize(); + let result = do_hazardous_operations(ss, |ss| { + ss.set_bytes_as_type(Z, KeyType::CryptographicRandom)?; + ss.set_security_strength(K::STRENGTH) + }); + if let Err(e) = result { + ss.zeroize(); + return Err(e.into()); + } + Ok(()) +} + +/// The worker [`DecapsulatingKey::create_decapsulator`] hands out: the private key, borrowed. +pub struct RsasveDecapsulator<'k, K: RsaSize> { + sk: &'k RsaKEMPrivateKey, +} + +impl Algorithm for RsasveDecapsulator<'_, K> { + const ALG_NAME: &'static str = RSASVE::::ALG_NAME; + const MAX_SECURITY_STRENGTH: SecurityStrength = RSASVE::::MAX_SECURITY_STRENGTH; +} + +impl KEMDecapsulator for RsasveDecapsulator<'_, K> +where + K: RsaSigningSize + RsaSize, +{ + /// RSASVE.RECOVER (§7.2.1.3): `C` in `(1, n - 1)` or [`KEMError::DecapsulationFailed`] + /// (step 3.c, RSADP's range check), `z = C^d mod n` by the CRT (step 3.b) and + /// `Z = I2BS(z, nLen)` into `ss` (step 3.d), + /// zeroized first and left so on error. A `z` that fails the CRT result check + /// (`z^e mod n` is not `C`) is [`KEMError::DecapsulationFailed`] too, and none of it is + /// released. + fn decaps_out(&self, ct: &[u8; N], ss: &mut KeyMaterial) -> Result { + let result = self.recover_in_own_frame(ct, ss); + // The secret value passes through return slots on its way from limbs to `ss`; the + // whole operation's stack is overwritten, the CRT's own wipe being inside it. + wipe_stack_below::(); + result + } +} + +/// What [`wipe_stack_below`] overwrites after RSASVE.RECOVER: this many `K::Limbs` values and +/// this many words. Measured in x86-64 release builds (rustc 1.88 and 1.97), the operation +/// uses 9240 bytes at RSA-2048, 12248 at RSA-3072, 15960 at RSA-4096 and 31848 at RSA-8192; +/// these cover 10752, 15104, 19456 and 36864, the difference being room for a compiler that +/// lays the frames out less tightly. +const DECAPS_STACK_PER_LIMB: usize = 34; +const DECAPS_STACK_FIXED: usize = 256; + +impl RsasveDecapsulator<'_, K> { + /// The work of `decaps_out`. Never inlined, so that what it leaves lies below its caller's + /// frame, where [`wipe_stack_below`] reaches it. + #[allow(non_snake_case)] + #[inline(never)] + fn recover_in_own_frame( + &self, + ct: &[u8; N], + ss: &mut KeyMaterial, + ) -> Result + where + K: RsaSize, + { + ss.zeroize(); + let c = K::limbs_from_be_bytes(ct); + if !in_open_range::(&c, self.sk.n()) { + return Err(KEMError::DecapsulationFailed); + } + let mut z = Secret::::new(); + if !K::crt_exp(&self.sk.0, &c, &mut z).to_bool() { + return Err(KEMError::DecapsulationFailed); + } + let mut Z = Secret::<[u8; N]>::new(); + *Z = K::be_bytes_from_limbs(&z); + secret_value_into::(&Z, ss)?; + Ok(N) + } +} + +impl EncapsulatingKey<(), N, N> for RsaKEMPublicKey +where + K: RsaSigningSize + RsaSize, +{ + type Algorithm = RSASVE; + type Encapsulator<'k> = RsasveEncapsulator<'k, K>; + + /// Cannot fail: RSASVE takes no parameters beyond the key. + fn create_encapsulator<'k>(&'k self, _params: ()) -> Result, KEMError> { + Ok(RsasveEncapsulator { pk: self }) + } +} + +impl DecapsulatingKey<(), N, N> for RsaKEMPrivateKey +where + K: RsaSigningSize + RsaSize, +{ + type Algorithm = RSASVE; + type Decapsulator<'k> = RsasveDecapsulator<'k, K>; + + /// Cannot fail: RSASVE takes no parameters beyond the key. + fn create_decapsulator<'k>(&'k self, _params: ()) -> Result, KEMError> { + Ok(RsasveDecapsulator { sk: self }) + } +} + +impl PrivateKey for RsaKEMPrivateKey +where + K: RsaSigningSize + RsaSize, +{ + fn encode(&self) -> [u8; SK_LEN] { + self.0.encode_raw() + } + + fn encode_out(&self, out: &mut [u8; SK_LEN]) -> usize { + self.0.encode_raw_out(out); + SK_LEN + } + + fn from_bytes(bytes: &[u8]) -> Result { + let bytes: &[u8; SK_LEN] = bytes.try_into().map_err(|_| { + KeyDecodingError( + "an RSA private key is five components of half the modulus length and eight bytes", + ) + })?; + RsaPrivateComponents::from_bytes_raw_as(bytes, |components| { + Self::from_rsa_key(components.map_err(decoding_error)?).map_err(kem_decoding_error) + }) + } +} + +impl PublicKey for RsaKEMPublicKey +where + K: RsaSize, +{ + fn encode(&self) -> [u8; PK_LEN] { + self.0.encode_raw() + } + + fn encode_out(&self, out: &mut [u8; PK_LEN]) -> usize { + *out = self.0.encode_raw(); + PK_LEN + } + + fn from_bytes(bytes: &[u8]) -> Result { + let bytes: &[u8; PK_LEN] = bytes.try_into().map_err(|_| { + KeyDecodingError("an RSA public key is the modulus length plus eight bytes") + })?; + Self::from_rsa_key(RsaPublicComponents::from_bytes_raw(bytes).map_err(decoding_error)?) + .map_err(kem_decoding_error) + } +} + +/// The signature generator's pair as KEM keys, for [`RSASVE::keygen`] and the markers' +/// `generate_kem_key_pair`. +pub(crate) fn keygen_from( + pair: Result<(RsaPublicComponents, RsaPrivateComponents), SignatureError>, +) -> Result<(RsaKEMPublicKey, RsaKEMPrivateKey), KEMError> { + let (pk, sk) = pair.map_err(kem_error)?; + Ok((RsaKEMPublicKey::from_rsa_key(pk)?, RsaKEMPrivateKey::from_rsa_key(sk)?)) +} diff --git a/crypto/rsa/src/rsasve_kdf.rs b/crypto/rsa/src/rsasve_kdf.rs new file mode 100644 index 000000000..622d96ed5 --- /dev/null +++ b/crypto/rsa/src/rsasve_kdf.rs @@ -0,0 +1,310 @@ +//! RSASVE with its secret value derived through HKDF, over [`KdfParams`]: the KEM roles the +//! key-establishment keys of [`crate::rsasve`] carry a second time, with the KDF's description, +//! the fixed info and the derived key's length as the parameters, so that the key handed out +//! is a key and not SP 800-56B Rev. 2's secret value `Z`, which the standard passes through a +//! key-derivation method (its Section 5.5) before any use. The algorithm is +//! [`RSASVE_HKDF`], `RSASVE-2048-HKDF-SHA256` and so on, for any modulus size and any +//! HMAC hash, at the lesser of the two strengths. +//! +//! The derived key is HKDF-Hash(salt, Z, info) over RSASVE's `Z`, the salt the description's +//! ([`HkdfDescription`]), the info and the length the caller's [`KdfParams`], the length from +//! one byte to 255 hash outputs (RFC 5869 Section 2.3), checked at compile time where a worker +//! is made. The length is part of the protocol's agreement as the info is, and it does not +//! separate keys: the key at one length is a prefix of the key at a longer one under the same +//! info, so two keys from one encapsulation take two infos. The ciphertext is not fed into the +//! info: `Z` is what the ciphertext encrypts, so it is bound to the ciphertext already, and the +//! public key is the protocol's to bind through the info if it wants it. The description is +//! readable, so a key held in a token that runs RSASVE and HKDF inside the device can be handed +//! the same parameters; see the crate's `# Scope`. + +use crate::rsa_core::wipe_stack_below; +use crate::rsasve::{RsaKEMPrivateKey, RsaKEMPublicKey}; +use crate::size::{RsaSigningSize, RsaSize, min_strength}; +use bouncycastle_core::errors::KEMError; +use bouncycastle_core::kdf_params::{KdfDescription, KdfParams}; +use bouncycastle_core::kem_key::{DecapsulatingKey, EncapsulatingKey, KEMAlgorithm}; +use bouncycastle_core::key_material::{KeyMaterial, KeyMaterialTrait}; +use bouncycastle_core::security_strength::SecurityStrength; +use bouncycastle_core::traits::{Algorithm, KDF, KEMDecapsulator, KEMEncapsulator, RNG}; +use bouncycastle_hkdf::HkdfDescription; +use bouncycastle_hmac::HMACParams; +use bouncycastle_utils::const_str::ConstStr; +use core::marker::PhantomData; + +/// RSASVE at the modulus size `K` with the secret value derived through HKDF over `H`: the +/// algorithm the key-establishment keys run when made into a worker from +/// `KdfParams<'p, HkdfDescription<'s, H>, LEN>`. Named `RSASVE--HKDF-`, at the +/// lesser of the size's and the hash's strength (HKDF-SHA256 caps a key at 128 bits, so +/// RSA-2048 with it is 112 and RSA-4096 with it 128). +/// +/// Both roles exist at a signing size, RSA-2048 and up; there is no encapsulation toward +/// RSA-1024 or RSA-1536: +/// +/// ```compile_fail,E0277 +/// use bouncycastle_core::kdf_params::KdfParams; +/// use bouncycastle_core::kem_key::EncapsulatingKey; +/// use bouncycastle_hkdf::HkdfDescription; +/// use bouncycastle_rsa::RSA1024; +/// use bouncycastle_rsa::rsasve::RsaKEMPublicKey; +/// use bouncycastle_sha2::SHA256; +/// +/// type Params = KdfParams<'static, HkdfDescription<'static, SHA256>, 32>; +/// fn encapsulates, const N: usize>() {} +/// encapsulates::, 128>(); +/// ``` +/// +/// ``` +/// use bouncycastle_core::kdf_params::KdfParams; +/// use bouncycastle_core::kem_key::EncapsulatingKey; +/// use bouncycastle_hkdf::HkdfDescription; +/// use bouncycastle_rsa::RSA2048; +/// use bouncycastle_rsa::rsasve::RsaKEMPublicKey; +/// use bouncycastle_sha2::SHA256; +/// +/// type Params = KdfParams<'static, HkdfDescription<'static, SHA256>, 32>; +/// fn encapsulates, const N: usize>() {} +/// encapsulates::, 256>(); +/// ``` +#[allow(non_camel_case_types)] +pub struct RSASVE_HKDF { + _params: PhantomData<(K, H)>, +} + +impl RSASVE_HKDF { + const NAME: ConstStr<32> = ConstStr::concat(&["RSASVE-", K::BITS_NAME, "-", H::HKDF_ALG_NAME]); + + /// The most bytes one derivation produces: 255 hash outputs (RFC 5869 Section 2.3). + pub const MAX_LEN: usize = 255 * H::OUTPUT_LEN; +} + +impl Algorithm for RSASVE_HKDF { + const ALG_NAME: &'static str = Self::NAME.as_str(); + const MAX_SECURITY_STRENGTH: SecurityStrength = + min_strength(K::STRENGTH, H::MAX_SECURITY_STRENGTH); +} + +impl KEMAlgorithm for RSASVE_HKDF {} + +/// The length check, a compile-time error where it is evaluated: `SS_LEN` is from one byte to +/// [`RSASVE_HKDF::MAX_LEN`]. The role impls evaluate it when a worker is made, and `derive` +/// does, so no worker exists at a length no derivation accepts. +const fn len_check() { + assert!( + SS_LEN > 0 && SS_LEN <= 255 * H::OUTPUT_LEN, + "the derived key is from one byte to the KDF's MAX_LEN long" + ); +} + +/// HKDF(Z, info) into `out`, zeroized first: a key of `SS_LEN` bytes, labelled at no more than +/// the algorithm's strength. The engine is built from the description for this derivation, an +/// HKDF keyed with the salt. +/// +/// # Errors +/// [`KEMError::KDFError`] with what HKDF refused, building the engine or deriving; +/// [`KEMError::GenericError`] if it writes anything but `SS_LEN` bytes. `out` is left zeroized. +#[allow(non_snake_case)] +fn derive( + params: KdfParams<'_, HkdfDescription<'_, H>, SS_LEN>, + Z: &KeyMaterial, + out: &mut KeyMaterial, +) -> Result<(), KEMError> { + const { len_check::() }; + out.zeroize(); + let kdf = params.kdf().engine().map_err(KEMError::KDFError)?; + // `derive_key_out` zeroizes `out` first and leaves it so on its errors. + let written = kdf.derive_key_out(Z, params.info(), SS_LEN, out).map_err(KEMError::KDFError)?; + if written != SS_LEN || out.key_len() != SS_LEN { + out.zeroize(); + return Err(KEMError::GenericError("the KDF derived a key of the wrong length")); + } + // The label is the pairing's: HKDF credits a secret salt and would label the key above the + // modulus's strength, which this algorithm does not claim. Lowering needs no window. + let strength = + min_strength(out.security_strength(), RSASVE_HKDF::::MAX_SECURITY_STRENGTH); + if out.set_security_strength(strength).is_err() { + out.zeroize(); + return Err(KEMError::GenericError("the derived key's strength could not be set")); + } + Ok(()) +} + +/// The encapsulator [`EncapsulatingKey::create_encapsulator`] hands out over [`KdfParams`]: it +/// borrows the key, holds the parameters, and derives the key from each encapsulation's `Z`. +pub struct RsasveKdfEncapsulator<'k, 'p, 's, K: RsaSize, H: HMACParams, const SS_LEN: usize> { + pk: &'k RsaKEMPublicKey, + params: KdfParams<'p, HkdfDescription<'s, H>, SS_LEN>, +} + +impl Algorithm + for RsasveKdfEncapsulator<'_, '_, '_, K, H, SS_LEN> +{ + const ALG_NAME: &'static str = RSASVE_HKDF::::ALG_NAME; + const MAX_SECURITY_STRENGTH: SecurityStrength = RSASVE_HKDF::::MAX_SECURITY_STRENGTH; +} + +impl KEMEncapsulator + for RsasveKdfEncapsulator<'_, '_, '_, K, H, SS_LEN> +where + K: RsaSigningSize + RsaSize, + H: HMACParams, +{ + /// RSASVE.GENERATE for `Z` and the ciphertext, then HKDF over `Z`. `Z` lives in one local, + /// zeroized when it drops; a ciphertext for a key the caller never gets is not left in the + /// buffer. + fn encaps_out( + &self, + rng: &mut dyn RNG, + ct: &mut [u8; N], + ss: &mut KeyMaterial, + ) -> Result { + let result = self.derive_in_own_frame(rng, ct, ss); + // As after decapsulation: HKDF's pseudorandom key is left in the frames of the + // derivation, on this side as on that one. + wipe_stack_below::(); + result + } +} + +/// What [`wipe_stack_below`] overwrites after encapsulation with HKDF: this many `K::Limbs` +/// values and this many words. Measured in x86-64 release builds (rustc 1.88 and 1.97) with +/// SHA-256, the operation uses 7160 bytes at RSA-2048, 9336 at RSA-3072, 12280 at RSA-4096 and +/// 24056 at RSA-8192; these cover 8320, 11648, 14976 and 28288, the difference being room for +/// a compiler that lays the frames out less tightly. +const KDF_ENCAPS_STACK_PER_LIMB: usize = 26; +const KDF_ENCAPS_STACK_FIXED: usize = 208; + +impl + RsasveKdfEncapsulator<'_, '_, '_, K, H, SS_LEN> +{ + /// The work of `encaps_out`. Never inlined, so that what it and the derivation leave lies + /// below its caller's frame, where [`wipe_stack_below`] reaches it. + #[allow(non_snake_case)] + #[inline(never)] + fn derive_in_own_frame( + &self, + rng: &mut dyn RNG, + ct: &mut [u8; N], + ss: &mut KeyMaterial, + ) -> Result + where + K: RsaSize, + { + ss.zeroize(); + let mut Z = KeyMaterial::::new(); + self.pk.create_encapsulator(())?.encaps_out(rng, ct, &mut Z)?; + if let Err(e) = derive::(self.params, &Z, ss) { + ct.fill(0); + return Err(e); + } + Ok(N) + } +} + +/// The decapsulator [`DecapsulatingKey::create_decapsulator`] hands out over [`KdfParams`]: it +/// borrows the key, holds the parameters, and derives the key from each ciphertext's `Z`. +pub struct RsasveKdfDecapsulator<'k, 'p, 's, K: RsaSize, H: HMACParams, const SS_LEN: usize> { + sk: &'k RsaKEMPrivateKey, + params: KdfParams<'p, HkdfDescription<'s, H>, SS_LEN>, +} + +impl Algorithm + for RsasveKdfDecapsulator<'_, '_, '_, K, H, SS_LEN> +{ + const ALG_NAME: &'static str = RSASVE_HKDF::::ALG_NAME; + const MAX_SECURITY_STRENGTH: SecurityStrength = RSASVE_HKDF::::MAX_SECURITY_STRENGTH; +} + +impl KEMDecapsulator + for RsasveKdfDecapsulator<'_, '_, '_, K, H, SS_LEN> +where + K: RsaSigningSize + RsaSize, + H: HMACParams, +{ + /// RSASVE.RECOVER for `Z`, then HKDF over it; a ciphertext RSASVE refuses is refused here + /// with the caller's buffer zeroized. + fn decaps_out(&self, ct: &[u8; N], ss: &mut KeyMaterial) -> Result { + let result = self.derive_in_own_frame(ct, ss); + // HKDF's pseudorandom key, from which every key under this `Z` follows, is left in + // the frames of the derivation: the whole operation's stack is overwritten. + wipe_stack_below::(); + result + } +} + +/// What [`wipe_stack_below`] overwrites after decapsulation with HKDF: this many `K::Limbs` +/// values and this many words. Measured in x86-64 release builds (rustc 1.88 and 1.97) with +/// SHA-256, the operation, RSASVE.RECOVER's own wipe included, uses 12024 bytes at RSA-2048, +/// 16504 at RSA-3072, 20984 at RSA-4096 and 38904 at RSA-8192; these cover 12800, 17408, 22016 +/// and 40448. +const KDF_DECAPS_STACK_PER_LIMB: usize = 36; +const KDF_DECAPS_STACK_FIXED: usize = 448; + +impl + RsasveKdfDecapsulator<'_, '_, '_, K, H, SS_LEN> +{ + /// The work of `decaps_out`. Never inlined, so that what it and the derivation leave lies + /// below its caller's frame, where [`wipe_stack_below`] reaches it. + #[allow(non_snake_case)] + #[inline(never)] + fn derive_in_own_frame( + &self, + ct: &[u8; N], + ss: &mut KeyMaterial, + ) -> Result + where + K: RsaSize, + { + ss.zeroize(); + let mut Z = KeyMaterial::::new(); + self.sk.create_decapsulator(())?.decaps_out(ct, &mut Z)?; + derive::(self.params, &Z, ss)?; + Ok(SS_LEN) + } +} + +impl<'p, 's, K, H, const N: usize, const SS_LEN: usize> + EncapsulatingKey, SS_LEN>, N, SS_LEN> + for RsaKEMPublicKey +where + K: RsaSigningSize + RsaSize, + H: HMACParams, +{ + type Algorithm = RSASVE_HKDF; + type Encapsulator<'k> + = RsasveKdfEncapsulator<'k, 'p, 's, K, H, SS_LEN> + where + Self: 'k; + + /// The length is checked at compile time; the description validated its salt when it was + /// made, so this cannot fail. + fn create_encapsulator<'k>( + &'k self, + params: KdfParams<'p, HkdfDescription<'s, H>, SS_LEN>, + ) -> Result, KEMError> { + const { len_check::() }; + Ok(RsasveKdfEncapsulator { pk: self, params }) + } +} + +impl<'p, 's, K, H, const N: usize, const SS_LEN: usize> + DecapsulatingKey, SS_LEN>, N, SS_LEN> + for RsaKEMPrivateKey +where + K: RsaSigningSize + RsaSize, + H: HMACParams, +{ + type Algorithm = RSASVE_HKDF; + type Decapsulator<'k> + = RsasveKdfDecapsulator<'k, 'p, 's, K, H, SS_LEN> + where + Self: 'k; + + /// As [`EncapsulatingKey::create_encapsulator`]: cannot fail. + fn create_decapsulator<'k>( + &'k self, + params: KdfParams<'p, HkdfDescription<'s, H>, SS_LEN>, + ) -> Result, KEMError> { + const { len_check::() }; + Ok(RsasveKdfDecapsulator { sk: self, params }) + } +} diff --git a/crypto/rsa/src/size.rs b/crypto/rsa/src/size.rs new file mode 100644 index 000000000..c43985b40 --- /dev/null +++ b/crypto/rsa/src/size.rs @@ -0,0 +1,845 @@ +//! The modulus size as a type: [`RsaSize`], implemented by the markers [`RSA1024`] to +//! [`RSA8192`], names a size's limb and byte widths and routes to the width-fixed engine +//! ([`crate::modexp`], `rsa_core`, [`crate::keygen`], the codec), so that the scheme types and +//! the keys are written once over `K: RsaSize`. [`RsaSigningSize`] marks the sizes that sign +//! and generate keys, RSA-2048 and up; RSA-1024 and RSA-1536 implement only [`RsaSize`], which +//! is what keeps them verify-only (the crate's `# Scope`). Widths reach generic code as array +//! types: `K::Modulus` is the `[u8; N]` a signature or ciphertext is, and where a `core` trait +//! needs `N` itself an impl is bound `K: RsaSize`, which the solver resolves +//! from `K`. + +use crate::codec::{be_bytes_from_limbs, limbs_from_be_bytes}; +use crate::keygen::{keygen_as, keygen_from_rng, validate_key_pair}; +use crate::keys::{ + RsaPrivateComponents, RsaPrivateKey, RsaPublicComponents, RsaPublicKey, modulus_strength, +}; +use crate::rsa_core; +use crate::rsassa_pkcs1_v1_5::RSASSA_PKCS1_v1_5; +use crate::rsassa_pss::{PssHash, PssParams, RSASSA_PSS}; +use crate::rsasve::{RsaKEMPrivateKey, RsaKEMPublicKey}; +use bouncycastle_core::errors::{KEMError, SignatureError}; +use bouncycastle_core::security_strength::SecurityStrength; +use bouncycastle_core::traits::{AlgorithmOID, HashAlgParams, HashOneShot, RNG}; +use bouncycastle_ec::montgomery; +use bouncycastle_ec::nat; +use bouncycastle_utils::ct::Condition; +use bouncycastle_utils::secret::{NoPadding, ZeroizablePrimitive}; +use core::fmt::Debug; +use core::num::NonZeroUsize; + +/// A fixed-size array a size's values are held or encoded in: `[u64; L]` limbs or `[u8; N]` +/// bytes. `ZEROED` (from [`ZeroizablePrimitive`]) stands in for `Default`, which arrays over +/// 32 elements lack. +pub trait Array: + ZeroizablePrimitive + NoPadding + AsRef<[T]> + AsMut<[T]> + PartialEq + Eq + Debug + 'static +{ + /// The number of elements. + const LEN: usize; +} + +impl Array + for [T; N] +{ + const LEN: usize = N; +} + +/// A modulus size: the marker's view of the engine at one width. Sealed, since an impl is a +/// routing table into this crate's arithmetic and every length below must agree with it +/// ([`check_lengths`]). +pub trait RsaSize: + sealed::Sealed + Copy + Clone + Debug + Default + PartialEq + Eq + 'static +{ + /// The size's name, `RSA-2048`. + const NAME: &'static str; + /// The modulus length in bits as text, for algorithm names: `2048`. + const BITS_NAME: &'static str; + /// `nLen`, the modulus length in bits. + const BITS: usize; + /// `nLen / 8`: the byte length of the modulus, of a signature, of an RSASVE ciphertext and + /// of its shared secret. + const K_LEN: usize; + /// `K_LEN + 8`: the public key's encoding, `n || e`. + const PK_LEN: usize; + /// `5 * K_LEN / 2 + 8`: the private key's encoding, `p || q || dP || dQ || qInv || e`. + const SK_LEN: usize; + /// The strength SP 800-57 Part 1 Rev. 5 Table 2 gives the modulus length; `None` below + /// 2048 bits. + const STRENGTH: SecurityStrength; + + /// `[u64; K_LEN / 8]`, a modulus-width integer. + type Limbs: Array; + /// `[u64; K_LEN / 16]`, a prime-width integer. + type HalfLimbs: Array; + /// `[u8; K_LEN]`. + type Modulus: Array; + /// `[u8; K_LEN / 2]`, one CRT component's encoding. + type HalfBytes: Array; + /// `[u8; PK_LEN]`. + type PublicKeyEncoded: Array; + /// `[u8; SK_LEN]`. + type PrivateKeyEncoded: Array; + + /// Big-endian bytes to limbs. + fn limbs_from_be_bytes(bytes: &Self::Modulus) -> Self::Limbs; + /// Limbs to big-endian bytes. + fn be_bytes_from_limbs(limbs: &Self::Limbs) -> Self::Modulus; + /// Whether `x < y`. + fn is_less(x: &Self::Limbs, y: &Self::Limbs) -> bool; + /// `x^e mod n`, the public-key operation (RSAVP1 / RSAEP's exponentiation), `x < n`. + /// + /// # Panics + /// + /// If `n` is even. A key's `n` never is, its constructor having refused it; only a caller + /// that hands this limbs of its own can get here. + fn public_exp(n: &Self::Limbs, e: u64, x: &Self::Limbs) -> Self::Limbs; +} + +/// A size this crate signs, generates keys and establishes keys at: RSA-2048 and up (SP +/// 800-131A's 112-bit floor). +/// +/// The private-key exponentiation is not among its methods: a private key is used through a +/// scheme, by the roles its key types implement. +/// +/// ```compile_fail,E0599 +/// use bouncycastle_rsa::RSA2048; +/// use bouncycastle_rsa::keys::RsaPrivateComponents; +/// use bouncycastle_rsa::size::{RsaSigningSize, RsaSize}; +/// fn raw(sk: &RsaPrivateComponents, m: &[u64; 32], out: &mut [u64; 32]) { +/// let _ = RSA2048::crt_exp(sk, m, out); +/// } +/// ``` +/// +/// ``` +/// use bouncycastle_rsa::RSA2048; +/// use bouncycastle_rsa::keys::RsaPrivateComponents; +/// use bouncycastle_rsa::size::{RsaSigningSize, RsaSize}; +/// fn modulus(sk: &RsaPrivateComponents) -> [u8; 256] { +/// RSA2048::be_bytes_from_limbs(sk.n()) +/// } +/// ``` +pub trait RsaSigningSize: RsaSize + sealed::PrivateKeyEngine { + /// The Miller-Rabin rounds run on a prime of this size: 25 at every size, the count the FIPS + /// 140-3 Implementation Guidance (IG C.F, option 2) strongly recommends in place of FIPS 186-5 + /// Table B.1's minimum, which is 5 for a 1024-bit prime and 4 for larger ones. + const MR_ROUNDS: NonZeroUsize; + /// The Miller-Rabin rounds [`RsaPrivateComponents::validate`] runs on each prime of a key + /// from elsewhere: half of `ES(nBits)`, the strength SP 800-56B Rev. 2 Appendix D Table 4 + /// estimates for the modulus length (112, 128, 152 and 200 bits at 2048, 3072, 4096 and + /// 8192), so that a composite passes with probability at most `2^-ES(nBits)` (§6.4.1.2.1 + /// step 5). + const VALIDATION_MR_ROUNDS: NonZeroUsize; + /// FIPS 186-5 Appendix A.1.3 key generation from `rng`, which must offer the size's + /// [`STRENGTH`](RsaSize::STRENGTH). + /// + /// # Errors + /// [`SignatureError::RNGError`] if the RNG is weaker than the size or fails to deliver; + /// [`SignatureError::GenericError`] if no prime was found within the candidate budget, or + /// no usable Miller-Rabin base in 128 draws. + fn keygen( + rng: &mut dyn RNG, + ) -> Result<(RsaPublicComponents, RsaPrivateComponents), SignatureError>; + + // The private key's arithmetic: only a signing size has a private key, so only a signing + // size routes it. + /// Big-endian bytes to prime-width limbs. + fn half_limbs_from_be_bytes(bytes: &Self::HalfBytes) -> Self::HalfLimbs; + /// Prime-width limbs to big-endian bytes. + fn half_be_bytes_from_limbs(limbs: &Self::HalfLimbs) -> Self::HalfBytes; + /// `p * q`, exact: the modulus from its primes. + fn modulus_from_primes(p: &Self::HalfLimbs, q: &Self::HalfLimbs) -> Self::Limbs; + /// Whether `x < y`, at prime width. + fn half_is_less(x: &Self::HalfLimbs, y: &Self::HalfLimbs) -> bool; +} + +/// Implemented on a signing size marker: a signature key pair for one scheme and hash, so a +/// caller starts from the size and spells the algorithm, +/// `RSA2048::generate_pss_signature_key_pair::(&mut rng)`, and the pair is a key for +/// that algorithm and no other (SP 800-57 Part 1 Rev. 5's one scheme per key pair). The hash +/// is spelled, never defaulted, as on the ECDSA markers: the customary pairing is a convention +/// that moves. All of them run [`RsaSigningSize::keygen`], FIPS 186-5 Appendix A.1.3; the RNG is +/// an argument, not a default. The KEM pair is [`KemKeyPair`], a different type, as +/// [`rsasve`](crate::rsasve)'s `# Key separation` asks. +pub trait SignatureKeyPair: RsaSigningSize { + /// A key pair for RSASSA-PKCS1-v1_5 with `H`. + /// + /// # Errors + /// As [`RsaSigningSize::keygen`]. + #[allow(clippy::type_complexity)] + fn generate_pkcs1_v1_5_signature_key_pair( + rng: &mut dyn RNG, + ) -> Result< + (RsaPublicKey>, RsaPrivateKey>), + SignatureError, + >; + + /// A key pair for RSASSA-PSS with `H` under its conventional parameters + /// ([`PssHash`]: MGF1 over `H` for SHA-2 and SHA-3, the XOF + /// itself for SHAKE). + /// + /// # Errors + /// As [`RsaSigningSize::keygen`]. + #[allow(clippy::type_complexity)] + fn generate_pss_signature_key_pair( + rng: &mut dyn RNG, + ) -> Result< + (RsaPublicKey>, RsaPrivateKey>), + SignatureError, + >; + + /// A key pair for RSASSA-PSS with `H` under the spelled parameters `P`: another MGF1 hash + /// or salt length ([`Mgf1`](crate::rsassa_pss::Mgf1)) or no salt + /// ([`NoSalt`](crate::rsassa_pss::NoSalt)). + /// + /// # Errors + /// As [`RsaSigningSize::keygen`]. + #[allow(clippy::type_complexity)] + fn generate_pss_signature_key_pair_with>( + rng: &mut dyn RNG, + ) -> Result< + (RsaPublicKey>, RsaPrivateKey>), + SignatureError, + >; +} + +impl SignatureKeyPair for K { + fn generate_pkcs1_v1_5_signature_key_pair( + rng: &mut dyn RNG, + ) -> Result< + (RsaPublicKey>, RsaPrivateKey>), + SignatureError, + > { + keygen_as::(rng, |pair| { + let (pk, sk) = pair?; + Ok((RsaPublicKey::from_components(pk), RsaPrivateKey::from_components(sk))) + }) + } + + fn generate_pss_signature_key_pair( + rng: &mut dyn RNG, + ) -> Result<(RsaPublicKey>, RsaPrivateKey>), SignatureError> + { + keygen_as::(rng, |pair| { + let (pk, sk) = pair?; + Ok((RsaPublicKey::from_components(pk), RsaPrivateKey::from_components(sk))) + }) + } + + fn generate_pss_signature_key_pair_with>( + rng: &mut dyn RNG, + ) -> Result< + (RsaPublicKey>, RsaPrivateKey>), + SignatureError, + > { + keygen_as::(rng, |pair| { + let (pk, sk) = pair?; + Ok((RsaPublicKey::from_components(pk), RsaPrivateKey::from_components(sk))) + }) + } +} + +/// Implemented on a signing size marker: the RSASVE key-establishment pair +/// (`RSA2048::generate_kem_key_pair(&mut rng)`), the same generator as the signature pair's, +/// in the KEM key types. +pub trait KemKeyPair { + /// The size's KEM public key. + type PublicKey; + /// The size's KEM private key. + type PrivateKey; + + /// Key pair generation from `rng`. + /// + /// # Errors + /// As [`RsaSigningSize::keygen`], as a [`KEMError`]. + fn generate_kem_key_pair( + rng: &mut dyn RNG, + ) -> Result<(Self::PublicKey, Self::PrivateKey), KEMError>; +} + +impl KemKeyPair for K { + type PublicKey = RsaKEMPublicKey; + type PrivateKey = RsaKEMPrivateKey; + + fn generate_kem_key_pair( + rng: &mut dyn RNG, + ) -> Result<(RsaKEMPublicKey, RsaKEMPrivateKey), KEMError> { + keygen_as::(rng, crate::rsasve::keygen_from::) + } +} + +/// The lesser of two strengths: a scheme's strength is its modulus's or its hash's, whichever +/// is lower. +pub const fn min_strength(a: SecurityStrength, b: SecurityStrength) -> SecurityStrength { + if (a as u8) <= (b as u8) { a } else { b } +} + +/// The lengths an [`RsaSize`] impl states, checked against the array types it names and each +/// other; evaluated as a `const` beside every impl. +pub const fn check_lengths() { + assert!(K::BITS % 64 == 0, "the modulus is whole limbs"); + assert!(K::K_LEN == K::BITS / 8, "K_LEN is the modulus's byte length"); + assert!(>::LEN * 8 == K::K_LEN, "Limbs spans the modulus"); + assert!( + >::LEN * 2 == >::LEN, + "HalfLimbs is half" + ); + assert!(>::LEN == K::K_LEN, "Modulus is K_LEN bytes"); + assert!(>::LEN * 2 == K::K_LEN, "HalfBytes is K_LEN / 2 bytes"); + assert!(K::PK_LEN == K::K_LEN + 8, "PK_LEN is n || e"); + assert!( + >::LEN == K::PK_LEN, + "PublicKeyEncoded is PK_LEN bytes" + ); + assert!(K::SK_LEN == 5 * K::K_LEN / 2 + 8, "SK_LEN is the five CRT components and e"); + assert!( + >::LEN == K::SK_LEN, + "PrivateKeyEncoded is SK_LEN bytes" + ); +} + +/// RSA-1024 (verification only). +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub struct RSA1024; + +impl sealed::Sealed for RSA1024 {} + +impl RsaSize for RSA1024 { + const NAME: &'static str = "RSA-1024"; + const BITS_NAME: &'static str = "1024"; + const BITS: usize = 1024; + const K_LEN: usize = 128; + const PK_LEN: usize = 136; + const SK_LEN: usize = 328; + const STRENGTH: SecurityStrength = modulus_strength(16); + + type Limbs = [u64; 16]; + type HalfLimbs = [u64; 8]; + type Modulus = [u8; 128]; + type HalfBytes = [u8; 64]; + type PublicKeyEncoded = [u8; 136]; + type PrivateKeyEncoded = [u8; 328]; + + fn limbs_from_be_bytes(bytes: &Self::Modulus) -> Self::Limbs { + limbs_from_be_bytes::<16, 128>(bytes) + } + + fn be_bytes_from_limbs(limbs: &Self::Limbs) -> Self::Modulus { + be_bytes_from_limbs::<16, 128>(limbs) + } + + fn is_less(x: &Self::Limbs, y: &Self::Limbs) -> bool { + nat::sub(x, y).1 == 1 + } + + fn public_exp(n: &Self::Limbs, e: u64, x: &Self::Limbs) -> Self::Limbs { + rsa_core::public_exp::<16, 32, 33>(n, e, x) + } +} + +const _: () = check_lengths::(); + +/// RSA-1536 (verification only). +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub struct RSA1536; + +impl sealed::Sealed for RSA1536 {} + +impl RsaSize for RSA1536 { + const NAME: &'static str = "RSA-1536"; + const BITS_NAME: &'static str = "1536"; + const BITS: usize = 1536; + const K_LEN: usize = 192; + const PK_LEN: usize = 200; + const SK_LEN: usize = 488; + const STRENGTH: SecurityStrength = modulus_strength(24); + + type Limbs = [u64; 24]; + type HalfLimbs = [u64; 12]; + type Modulus = [u8; 192]; + type HalfBytes = [u8; 96]; + type PublicKeyEncoded = [u8; 200]; + type PrivateKeyEncoded = [u8; 488]; + + fn limbs_from_be_bytes(bytes: &Self::Modulus) -> Self::Limbs { + limbs_from_be_bytes::<24, 192>(bytes) + } + + fn be_bytes_from_limbs(limbs: &Self::Limbs) -> Self::Modulus { + be_bytes_from_limbs::<24, 192>(limbs) + } + + fn is_less(x: &Self::Limbs, y: &Self::Limbs) -> bool { + nat::sub(x, y).1 == 1 + } + + fn public_exp(n: &Self::Limbs, e: u64, x: &Self::Limbs) -> Self::Limbs { + rsa_core::public_exp::<24, 48, 49>(n, e, x) + } +} + +const _: () = check_lengths::(); + +/// RSA-2048. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub struct RSA2048; + +impl sealed::Sealed for RSA2048 {} + +impl RsaSize for RSA2048 { + const NAME: &'static str = "RSA-2048"; + const BITS_NAME: &'static str = "2048"; + const BITS: usize = 2048; + const K_LEN: usize = 256; + const PK_LEN: usize = 264; + const SK_LEN: usize = 648; + const STRENGTH: SecurityStrength = modulus_strength(32); + + type Limbs = [u64; 32]; + type HalfLimbs = [u64; 16]; + type Modulus = [u8; 256]; + type HalfBytes = [u8; 128]; + type PublicKeyEncoded = [u8; 264]; + type PrivateKeyEncoded = [u8; 648]; + + fn limbs_from_be_bytes(bytes: &Self::Modulus) -> Self::Limbs { + limbs_from_be_bytes::<32, 256>(bytes) + } + + fn be_bytes_from_limbs(limbs: &Self::Limbs) -> Self::Modulus { + be_bytes_from_limbs::<32, 256>(limbs) + } + + fn is_less(x: &Self::Limbs, y: &Self::Limbs) -> bool { + nat::sub(x, y).1 == 1 + } + + fn public_exp(n: &Self::Limbs, e: u64, x: &Self::Limbs) -> Self::Limbs { + rsa_core::public_exp::<32, 64, 65>(n, e, x) + } +} + +const _: () = check_lengths::(); + +impl RsaSigningSize for RSA2048 { + const MR_ROUNDS: NonZeroUsize = NonZeroUsize::new(25).unwrap(); + const VALIDATION_MR_ROUNDS: NonZeroUsize = NonZeroUsize::new(56).unwrap(); + + fn keygen( + rng: &mut dyn RNG, + ) -> Result<(RsaPublicComponents, RsaPrivateComponents), SignatureError> { + keygen_from_rng::(rng, Self::MR_ROUNDS, Self::STRENGTH) + } + + fn half_limbs_from_be_bytes(bytes: &Self::HalfBytes) -> Self::HalfLimbs { + limbs_from_be_bytes::<16, 128>(bytes) + } + + fn half_be_bytes_from_limbs(limbs: &Self::HalfLimbs) -> Self::HalfBytes { + be_bytes_from_limbs::<16, 128>(limbs) + } + + fn modulus_from_primes(p: &Self::HalfLimbs, q: &Self::HalfLimbs) -> Self::Limbs { + montgomery::widening_mul::<16, 32>(p, q) + } + + fn half_is_less(x: &Self::HalfLimbs, y: &Self::HalfLimbs) -> bool { + nat::sub(x, y).1 == 1 + } +} + +impl sealed::PrivateKeyEngine for RSA2048 { + fn crt_congruences( + p: &Self::HalfLimbs, + q: &Self::HalfLimbs, + d_p: &Self::HalfLimbs, + d_q: &Self::HalfLimbs, + q_inv: &Self::HalfLimbs, + e: u64, + ) -> [Condition; 3] { + rsa_core::crt_congruences::<16, 32>(p, q, d_p, d_q, q_inv, e) + } + + fn validate_key_pair( + sk: &RsaPrivateComponents, + rng: &mut dyn RNG, + ) -> Result<(), SignatureError> { + validate_key_pair::(sk, rng) + } + + fn crt_exp( + sk: &RsaPrivateComponents, + m: &Self::Limbs, + out: &mut Self::Limbs, + ) -> Condition { + rsa_core::crt_exp_checked::<32, 64, 65, 16, 32, 33>( + sk.p(), + sk.q(), + sk.d_p(), + sk.d_q(), + sk.q_inv(), + sk.n(), + sk.e(), + m, + out, + ) + } +} + +/// RSA-3072. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub struct RSA3072; + +impl sealed::Sealed for RSA3072 {} + +impl RsaSize for RSA3072 { + const NAME: &'static str = "RSA-3072"; + const BITS_NAME: &'static str = "3072"; + const BITS: usize = 3072; + const K_LEN: usize = 384; + const PK_LEN: usize = 392; + const SK_LEN: usize = 968; + const STRENGTH: SecurityStrength = modulus_strength(48); + + type Limbs = [u64; 48]; + type HalfLimbs = [u64; 24]; + type Modulus = [u8; 384]; + type HalfBytes = [u8; 192]; + type PublicKeyEncoded = [u8; 392]; + type PrivateKeyEncoded = [u8; 968]; + + fn limbs_from_be_bytes(bytes: &Self::Modulus) -> Self::Limbs { + limbs_from_be_bytes::<48, 384>(bytes) + } + + fn be_bytes_from_limbs(limbs: &Self::Limbs) -> Self::Modulus { + be_bytes_from_limbs::<48, 384>(limbs) + } + + fn is_less(x: &Self::Limbs, y: &Self::Limbs) -> bool { + nat::sub(x, y).1 == 1 + } + + fn public_exp(n: &Self::Limbs, e: u64, x: &Self::Limbs) -> Self::Limbs { + rsa_core::public_exp::<48, 96, 97>(n, e, x) + } +} + +const _: () = check_lengths::(); + +impl RsaSigningSize for RSA3072 { + const MR_ROUNDS: NonZeroUsize = NonZeroUsize::new(25).unwrap(); + const VALIDATION_MR_ROUNDS: NonZeroUsize = NonZeroUsize::new(64).unwrap(); + + fn keygen( + rng: &mut dyn RNG, + ) -> Result<(RsaPublicComponents, RsaPrivateComponents), SignatureError> { + keygen_from_rng::(rng, Self::MR_ROUNDS, Self::STRENGTH) + } + + fn half_limbs_from_be_bytes(bytes: &Self::HalfBytes) -> Self::HalfLimbs { + limbs_from_be_bytes::<24, 192>(bytes) + } + + fn half_be_bytes_from_limbs(limbs: &Self::HalfLimbs) -> Self::HalfBytes { + be_bytes_from_limbs::<24, 192>(limbs) + } + + fn modulus_from_primes(p: &Self::HalfLimbs, q: &Self::HalfLimbs) -> Self::Limbs { + montgomery::widening_mul::<24, 48>(p, q) + } + + fn half_is_less(x: &Self::HalfLimbs, y: &Self::HalfLimbs) -> bool { + nat::sub(x, y).1 == 1 + } +} + +impl sealed::PrivateKeyEngine for RSA3072 { + fn crt_congruences( + p: &Self::HalfLimbs, + q: &Self::HalfLimbs, + d_p: &Self::HalfLimbs, + d_q: &Self::HalfLimbs, + q_inv: &Self::HalfLimbs, + e: u64, + ) -> [Condition; 3] { + rsa_core::crt_congruences::<24, 48>(p, q, d_p, d_q, q_inv, e) + } + + fn validate_key_pair( + sk: &RsaPrivateComponents, + rng: &mut dyn RNG, + ) -> Result<(), SignatureError> { + validate_key_pair::(sk, rng) + } + + fn crt_exp( + sk: &RsaPrivateComponents, + m: &Self::Limbs, + out: &mut Self::Limbs, + ) -> Condition { + rsa_core::crt_exp_checked::<48, 96, 97, 24, 48, 49>( + sk.p(), + sk.q(), + sk.d_p(), + sk.d_q(), + sk.q_inv(), + sk.n(), + sk.e(), + m, + out, + ) + } +} + +/// RSA-4096. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub struct RSA4096; + +impl sealed::Sealed for RSA4096 {} + +impl RsaSize for RSA4096 { + const NAME: &'static str = "RSA-4096"; + const BITS_NAME: &'static str = "4096"; + const BITS: usize = 4096; + const K_LEN: usize = 512; + const PK_LEN: usize = 520; + const SK_LEN: usize = 1288; + const STRENGTH: SecurityStrength = modulus_strength(64); + + type Limbs = [u64; 64]; + type HalfLimbs = [u64; 32]; + type Modulus = [u8; 512]; + type HalfBytes = [u8; 256]; + type PublicKeyEncoded = [u8; 520]; + type PrivateKeyEncoded = [u8; 1288]; + + fn limbs_from_be_bytes(bytes: &Self::Modulus) -> Self::Limbs { + limbs_from_be_bytes::<64, 512>(bytes) + } + + fn be_bytes_from_limbs(limbs: &Self::Limbs) -> Self::Modulus { + be_bytes_from_limbs::<64, 512>(limbs) + } + + fn is_less(x: &Self::Limbs, y: &Self::Limbs) -> bool { + nat::sub(x, y).1 == 1 + } + + fn public_exp(n: &Self::Limbs, e: u64, x: &Self::Limbs) -> Self::Limbs { + rsa_core::public_exp::<64, 128, 129>(n, e, x) + } +} + +const _: () = check_lengths::(); + +impl RsaSigningSize for RSA4096 { + const MR_ROUNDS: NonZeroUsize = NonZeroUsize::new(25).unwrap(); + const VALIDATION_MR_ROUNDS: NonZeroUsize = NonZeroUsize::new(76).unwrap(); + + fn keygen( + rng: &mut dyn RNG, + ) -> Result<(RsaPublicComponents, RsaPrivateComponents), SignatureError> { + keygen_from_rng::(rng, Self::MR_ROUNDS, Self::STRENGTH) + } + + fn half_limbs_from_be_bytes(bytes: &Self::HalfBytes) -> Self::HalfLimbs { + limbs_from_be_bytes::<32, 256>(bytes) + } + + fn half_be_bytes_from_limbs(limbs: &Self::HalfLimbs) -> Self::HalfBytes { + be_bytes_from_limbs::<32, 256>(limbs) + } + + fn modulus_from_primes(p: &Self::HalfLimbs, q: &Self::HalfLimbs) -> Self::Limbs { + montgomery::widening_mul::<32, 64>(p, q) + } + + fn half_is_less(x: &Self::HalfLimbs, y: &Self::HalfLimbs) -> bool { + nat::sub(x, y).1 == 1 + } +} + +impl sealed::PrivateKeyEngine for RSA4096 { + fn crt_congruences( + p: &Self::HalfLimbs, + q: &Self::HalfLimbs, + d_p: &Self::HalfLimbs, + d_q: &Self::HalfLimbs, + q_inv: &Self::HalfLimbs, + e: u64, + ) -> [Condition; 3] { + rsa_core::crt_congruences::<32, 64>(p, q, d_p, d_q, q_inv, e) + } + + fn validate_key_pair( + sk: &RsaPrivateComponents, + rng: &mut dyn RNG, + ) -> Result<(), SignatureError> { + validate_key_pair::(sk, rng) + } + + fn crt_exp( + sk: &RsaPrivateComponents, + m: &Self::Limbs, + out: &mut Self::Limbs, + ) -> Condition { + rsa_core::crt_exp_checked::<64, 128, 129, 32, 64, 65>( + sk.p(), + sk.q(), + sk.d_p(), + sk.d_q(), + sk.q_inv(), + sk.n(), + sk.e(), + m, + out, + ) + } +} + +/// RSA-8192. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub struct RSA8192; + +impl sealed::Sealed for RSA8192 {} + +impl RsaSize for RSA8192 { + const NAME: &'static str = "RSA-8192"; + const BITS_NAME: &'static str = "8192"; + const BITS: usize = 8192; + const K_LEN: usize = 1024; + const PK_LEN: usize = 1032; + const SK_LEN: usize = 2568; + const STRENGTH: SecurityStrength = modulus_strength(128); + + type Limbs = [u64; 128]; + type HalfLimbs = [u64; 64]; + type Modulus = [u8; 1024]; + type HalfBytes = [u8; 512]; + type PublicKeyEncoded = [u8; 1032]; + type PrivateKeyEncoded = [u8; 2568]; + + fn limbs_from_be_bytes(bytes: &Self::Modulus) -> Self::Limbs { + limbs_from_be_bytes::<128, 1024>(bytes) + } + + fn be_bytes_from_limbs(limbs: &Self::Limbs) -> Self::Modulus { + be_bytes_from_limbs::<128, 1024>(limbs) + } + + fn is_less(x: &Self::Limbs, y: &Self::Limbs) -> bool { + nat::sub(x, y).1 == 1 + } + + fn public_exp(n: &Self::Limbs, e: u64, x: &Self::Limbs) -> Self::Limbs { + rsa_core::public_exp::<128, 256, 257>(n, e, x) + } +} + +const _: () = check_lengths::(); + +impl RsaSigningSize for RSA8192 { + const MR_ROUNDS: NonZeroUsize = NonZeroUsize::new(25).unwrap(); + const VALIDATION_MR_ROUNDS: NonZeroUsize = NonZeroUsize::new(100).unwrap(); + + fn keygen( + rng: &mut dyn RNG, + ) -> Result<(RsaPublicComponents, RsaPrivateComponents), SignatureError> { + keygen_from_rng::(rng, Self::MR_ROUNDS, Self::STRENGTH) + } + + fn half_limbs_from_be_bytes(bytes: &Self::HalfBytes) -> Self::HalfLimbs { + limbs_from_be_bytes::<64, 512>(bytes) + } + + fn half_be_bytes_from_limbs(limbs: &Self::HalfLimbs) -> Self::HalfBytes { + be_bytes_from_limbs::<64, 512>(limbs) + } + + fn modulus_from_primes(p: &Self::HalfLimbs, q: &Self::HalfLimbs) -> Self::Limbs { + montgomery::widening_mul::<64, 128>(p, q) + } + + fn half_is_less(x: &Self::HalfLimbs, y: &Self::HalfLimbs) -> bool { + nat::sub(x, y).1 == 1 + } +} + +impl sealed::PrivateKeyEngine for RSA8192 { + fn crt_congruences( + p: &Self::HalfLimbs, + q: &Self::HalfLimbs, + d_p: &Self::HalfLimbs, + d_q: &Self::HalfLimbs, + q_inv: &Self::HalfLimbs, + e: u64, + ) -> [Condition; 3] { + rsa_core::crt_congruences::<64, 128>(p, q, d_p, d_q, q_inv, e) + } + + fn validate_key_pair( + sk: &RsaPrivateComponents, + rng: &mut dyn RNG, + ) -> Result<(), SignatureError> { + validate_key_pair::(sk, rng) + } + + fn crt_exp( + sk: &RsaPrivateComponents, + m: &Self::Limbs, + out: &mut Self::Limbs, + ) -> Condition { + rsa_core::crt_exp_checked::<128, 256, 257, 64, 128, 129>( + sk.p(), + sk.q(), + sk.d_p(), + sk.d_q(), + sk.q_inv(), + sk.n(), + sk.e(), + m, + out, + ) + } +} + +pub(crate) mod sealed { + use super::{RsaSize, SignatureError}; + use crate::keys::RsaPrivateComponents; + use bouncycastle_core::traits::RNG; + use bouncycastle_utils::ct::Condition; + + pub trait Sealed {} + + /// What a signing size routes of the private key's arithmetic and is no part of the + /// public API: the checked exponentiation above all, which is RSADP on any key and a way + /// to sign nothing. A supertrait of `RsaSigningSize` in a module that is private to the + /// crate, so that code outside the crate can neither name it nor call its methods. + pub trait PrivateKeyEngine: RsaSize { + /// Whether the CRT components and `e` belong together, RFC 8017 §3.2, for odd `p` and + /// `q`: `e * dP == 1 (mod (p - 1))`, `e * dQ == 1 (mod (q - 1))` and + /// `q * qInv == 1 (mod p)`, in that order. Constant time in the components. + fn crt_congruences( + p: &Self::HalfLimbs, + q: &Self::HalfLimbs, + d_p: &Self::HalfLimbs, + d_q: &Self::HalfLimbs, + q_inv: &Self::HalfLimbs, + e: u64, + ) -> [Condition; 3]; + /// SP 800-56B Rev. 2 §6.4.1.4.3 validation of the key pair `sk` holds; + /// [`RsaPrivateComponents::validate`] is the way to it. + fn validate_key_pair( + sk: &RsaPrivateComponents, + rng: &mut dyn RNG, + ) -> Result<(), SignatureError>; + /// `m^d mod n` by the CRT (RSASP1 / RSADP's exponentiation), `m < n`, into `out`, constant + /// time in the key, with the result checked before it is released: TRUE if `out^e mod n` is + /// `m` again, as it is for a sound key and a sound computation. Otherwise FALSE, with + /// `out` zero, and the caller reports a failure. + fn crt_exp( + sk: &RsaPrivateComponents, + m: &Self::Limbs, + out: &mut Self::Limbs, + ) -> Condition; + } +} diff --git a/crypto/rsa/tests/from_hash_length_tests.rs b/crypto/rsa/tests/from_hash_length_tests.rs new file mode 100644 index 000000000..d6712ac00 --- /dev/null +++ b/crypto/rsa/tests/from_hash_length_tests.rs @@ -0,0 +1,273 @@ +//! The `*_from_hash` entry points take the message hash, and for RSASSA-PSS the salt, as +//! slices, so their lengths are the caller's to get wrong. A hash that is not one output of +//! the algorithm's hash, or a salt that is not the algorithm's salt length, is an error in +//! every build profile: no signature over a `DigestInfo` that no hash produces, and no panic. +//! These tests are meant to be run with `--release` as well as without. + +use bouncycastle_core::errors::{RNGError, SignatureError}; +use bouncycastle_core::hex::decode as hex_decode; +use bouncycastle_core::key_material::KeyMaterialTrait; +use bouncycastle_core::security_strength::SecurityStrength; +use bouncycastle_core::traits::{HashOneShot, RNG}; +use bouncycastle_rsa::RSA2048; +use bouncycastle_rsa::keys::{RsaPrivateComponents, RsaPublicComponents}; +use bouncycastle_rsa::rsassa::{ + self, RsaDeterministicSignatureAlgorithm, RsaRandomizedSignatureAlgorithm, + RsaSignatureAlgorithm, +}; +use bouncycastle_rsa::rsassa_pkcs1_v1_5::RSASSA_PKCS1_v1_5; +use bouncycastle_rsa::rsassa_pss::{Mgf1, NoSalt, RSASSA_PSS}; +use bouncycastle_rsa::size::RsaSize; +use bouncycastle_sha2::{SHA256, SHA512}; + +// A genuine RSA-2048 key: the first SHA-256 group of Wycheproof's +// `rsa_pkcs1_2048_sig_gen_test.json` (`tests/rsa_2048_pkcs1_v1_5_tests.rs` has the provenance). +const P: [u64; 16] = [ + 0x0ea36cfb3a5b18f1, 0x48a6e65332119129, 0x110ad9e7b48a1c93, 0x569156b90113e2e9, + 0xe79813a575cfad9c, 0x69d659d143ec6f17, 0xe81e6bab5ddaa783, 0xbff1c5b80a69f788, + 0x978f6c35814f50ee, 0xe6a289ad4cfbf78f, 0x34d5681e5809d415, 0xbb028bda42eeb5d2, + 0x41c56e4de086b0d5, 0x58b8d1e24f3b55d0, 0xfb5248247d98cb7d, 0xdc431050f782e894, +]; +const Q: [u64; 16] = [ + 0x669f140cfbc20f25, 0xb97bb03677207d95, 0xfd4e06f3ed7299d4, 0x160f90536abc9492, + 0xf5b131f39098f7bc, 0xae8d72c57088d7ab, 0x89b94fbde542aba9, 0x3d3f9880ec47d5e0, + 0x1378a6868af3b7a0, 0x5544070beb057c94, 0x16611debc472fac4, 0xe500ffb79f5b8868, + 0x308a5e32196603b2, 0xea5fb19eb4eabc38, 0x122273ae3222b598, 0xbd1a81e7977f9898, +]; +const D_P: [u64; 16] = [ + 0x209f33f09515d7c1, 0xb4a9b37656917205, 0x276933bb07e4efb9, 0x8c14019808e00414, + 0x289f96da220711e5, 0xfbbd2923d31532fe, 0xc06b414e61c0e1e7, 0x4c23c4588488961d, + 0x4dc48ae34514759c, 0x9c786961ae3e2c35, 0x497e8d9c650688e0, 0x18bf08472612dbe5, + 0x8885fb161870ee12, 0xf21d7c1479d99d47, 0x9121d91952ffd1c7, 0xa94b528b28f29159, +]; +const D_Q: [u64; 16] = [ + 0xf7597ffb68011d8d, 0x7b3cc538c4bab8c9, 0xa8fa480a81a925af, 0x6d6ede7251a383bf, + 0x8a63f788ce3a0f85, 0x0b920502eb478bc9, 0x7e37e755edfe70d9, 0x9cf9948422a16555, + 0x0d6d9ea1f2ef71fd, 0xf7efa32ea0cb6e00, 0x0629b114ca7f780f, 0xcf51176359654348, + 0x540cdcbd4ad35435, 0x31c02ff1a2bc437c, 0xff2503df78bafed5, 0x3af0e72a933aef09, +]; +const Q_INV: [u64; 16] = [ + 0x552fe4bfce945f7b, 0x67e50c999c67247b, 0xfb54ef17be3b2853, 0x241f5921b5ad3983, + 0x02de5eccd143cf31, 0x74e45f6fcc60f216, 0xafa5428a74f12708, 0x88d42294b6a2759b, + 0xe923e1097c0c562f, 0xc968b48a91c38b5b, 0x933e85179c0320b0, 0x7993d0445f758d51, + 0x9bfc042ee0924b1b, 0x41f956d90fa8a793, 0xee7a87b6483a66ee, 0x2640fbfbcfefb163, +]; + +type V15 = RSASSA_PKCS1_v1_5; +type Pss = RSASSA_PSS; +type PssSalt20 = RSASSA_PSS>; +type PssNoSalt = RSASSA_PSS>; + +const HASH_LEN: SignatureError = + SignatureError::LengthError("the message hash must be the hash's output length"); +const SALT_LEN: SignatureError = + SignatureError::LengthError("the salt must be the parameters' salt length"); + +fn key_pair() -> (RsaPublicComponents, RsaPrivateComponents) { + let sk = + RsaPrivateComponents::::from_crt_components(&P, &Q, &D_P, &D_Q, &Q_INV, 0x10001) + .unwrap(); + (RsaPublicComponents::::new(sk.n(), sk.e()).unwrap(), sk) +} + +/// Hash lengths that are not SHA-256's 32: none, SHA-1's 20, one short, one long, SHA-512's. +const WRONG_HASH_LENS: [usize; 5] = [0, 20, 31, 33, 64]; + +/// An RNG that counts its draws and otherwise fills with a constant. +struct Counting(usize); + +impl RNG for Counting { + fn add_seed_keymaterial(&mut self, _: &dyn KeyMaterialTrait) -> Result<(), RNGError> { + Err(RNGError::GenericError("not seedable")) + } + fn next_int(&mut self) -> Result { + Err(RNGError::GenericError("not used")) + } + fn next_bytes_out(&mut self, out: &mut [u8]) -> Result { + self.0 += 1; + out.fill(0x5A); + Ok(out.len()) + } + fn fill_keymaterial_out(&mut self, _: &mut dyn KeyMaterialTrait) -> Result { + Err(RNGError::GenericError("not used")) + } + fn security_strength(&self) -> SecurityStrength { + SecurityStrength::_256bit + } +} + +#[test] +fn pkcs1_v1_5_from_hash_refuses_a_hash_of_the_wrong_length() { + let (pk, sk) = key_pair(); + let (pk, sk) = (pk.key::(), sk.key::()); + let digest = [0x11u8; 64]; + let good = rsassa::sign_from_hash_deterministic(&sk, &digest[..32]).unwrap(); + rsassa::verify_from_hash(&pk, &digest[..32], &good).unwrap(); + + for len in WRONG_HASH_LENS { + assert_eq!( + rsassa::sign_from_hash_deterministic(&sk, &digest[..len]), + Err(HASH_LEN), + "{len}" + ); + assert_eq!(rsassa::verify_from_hash(&pk, &digest[..len], &good), Err(HASH_LEN), "{len}"); + // The scheme's own encoding and verification, which the functions above go through. + assert_eq!(V15::emsa_encode::<256>(&digest[..len]), Err(HASH_LEN), "{len}"); + } +} + +/// What a release build used to sign for a 20-byte "SHA-256 hash": a `DigestInfo` naming +/// SHA-256 over a 20-byte OCTET STRING. Made here by hand, with its signature under the test +/// key by Python 3.12 (`pow(em, d, n)`), which the public exponentiation takes back to the +/// structure: a well-formed signature of it, and not accepted for those 20 bytes, by +/// `verify_from_hash`, which reports the length, or by the scheme's decoding. +#[test] +fn pkcs1_v1_5_does_not_verify_a_digest_info_over_a_short_hash() { + let (pk, _) = key_pair(); + let short = [0x11u8; 20]; + // RFC 8017 Section 9.2 note 1's SHA-256 prefix with its two lengths cut from 0x31 and 0x20 + // to 0x25 and 0x14, then the 20 bytes. + let mut t = vec![ + 0x30, 0x25, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x01, + 0x05, 0x00, 0x04, 0x14, + ]; + t.extend_from_slice(&short); + let mut em = [0xFFu8; 256]; + em[0] = 0x00; + em[1] = 0x01; + em[256 - t.len() - 1] = 0x00; + em[256 - t.len()..].copy_from_slice(&t); + + let signature: [u8; 256] = hex_decode(concat!( + "01060f84ad7e852a590229460ecedaf84de77c0f1d050a8d0b880db39aabf17e07ab11e726141b00", + "2e1c8f7efae8c57adfbfca4ba027a25706e61e407f0e623d87207f09e30f3c4eba05f2ce1fba2631", + "9b4f57072f8a7393092a9c1fe82f467dcd8f29ea2adc9209932847dbabf0faf43eb81ccedc75a194", + "6bf69f5986120ed0e080fce97b030aa874fd4be4755f035cb784f938d978b65779207b80eebf3bcb", + "05dbb114a0a57c3395f38de2f25d2a4e18ba34b9d841566b5ebcc77f7e4e0902e67c20374e6d188d", + "ccfc30c5a9b7349dbca0bc45363d9d5d55dcfdfd20b8b9c172b2068d8d2db6252d7e072d7e347417", + "a0e41df4927f2b8b65c9b414cfc38398", + )) + .unwrap() + .try_into() + .unwrap(); + assert_eq!( + RSA2048::public_exp(pk.n(), pk.e(), &RSA2048::limbs_from_be_bytes(&signature)), + RSA2048::limbs_from_be_bytes(&em) + ); + + assert_eq!(rsassa::verify_from_hash(&pk.key::(), &short, &signature), Err(HASH_LEN)); + assert!(!V15::emsa_verify::<256>(&short, &em)); + // The same structure over a real hash length is what verification is for. + let digest = [0x11u8; 32]; + let em = V15::emsa_encode::<256>(&digest).unwrap(); + assert!(V15::emsa_verify::<256>(&digest, &em)); +} + +#[test] +fn pss_from_hash_refuses_a_hash_of_the_wrong_length() { + let (pk, sk) = key_pair(); + let digest = [0x11u8; 64]; + let salt = [0x42u8; 32]; + let (pk_pss, sk_pss) = (pk.key::(), sk.key::()); + let good = rsassa::sign_from_hash_with_salt(&sk_pss, &digest[..32], &salt).unwrap(); + rsassa::verify_from_hash(&pk_pss, &digest[..32], &good).unwrap(); + + for len in WRONG_HASH_LENS { + let h = &digest[..len]; + assert_eq!(rsassa::sign_from_hash_with_salt(&sk_pss, h, &salt), Err(HASH_LEN), "{len}"); + assert_eq!(rsassa::verify_from_hash(&pk_pss, h, &good), Err(HASH_LEN), "{len}"); + // Nothing is drawn for a hash that will be refused. + let mut rng = Counting(0); + assert_eq!(rsassa::sign_from_hash(&sk_pss, h, &mut rng), Err(HASH_LEN), "{len}"); + assert_eq!(rng.0, 0, "{len}"); + assert_eq!(Pss::emsa_encode::<256>(h, &salt), Err(HASH_LEN), "{len}"); + assert!(!Pss::emsa_verify::<256>(h, &[0u8; 256]), "{len}"); + } + let mut rng = Counting(0); + let drawn = rsassa::sign_from_hash(&sk_pss, &digest[..32], &mut rng).unwrap(); + assert_eq!(rng.0, 1); + rsassa::verify_from_hash(&pk_pss, &digest[..32], &drawn).unwrap(); + + // Unsalted PSS is the deterministic entry point. + let (pk_ns, sk_ns) = (pk.key::(), sk.key::()); + let good = rsassa::sign_from_hash_deterministic(&sk_ns, &digest[..32]).unwrap(); + rsassa::verify_from_hash(&pk_ns, &digest[..32], &good).unwrap(); + for len in WRONG_HASH_LENS { + let h = &digest[..len]; + assert_eq!(rsassa::sign_from_hash_deterministic(&sk_ns, h), Err(HASH_LEN), "{len}"); + assert_eq!(rsassa::verify_from_hash(&pk_ns, h, &good), Err(HASH_LEN), "{len}"); + assert_eq!(PssNoSalt::emsa_encode::<256>(h), Err(HASH_LEN), "{len}"); + } +} + +#[test] +fn pss_from_hash_refuses_a_salt_of_the_wrong_length() { + let (pk, sk) = key_pair(); + let salt = [0x42u8; 64]; + + // The conventional parameters: the salt is one SHA-256 output. + let sk_pss = sk.key::(); + let digest = [0x11u8; 32]; + for len in [0, 20, 31, 33, 64] { + assert_eq!( + rsassa::sign_from_hash_with_salt(&sk_pss, &digest, &salt[..len]), + Err(SALT_LEN), + "{len}" + ); + assert_eq!(Pss::emsa_encode::<256>(&digest, &salt[..len]), Err(SALT_LEN), "{len}"); + } + + // Spelled parameters: SHA-512 with a 20-byte salt. The hash is 64 bytes and the salt 20, + // and neither length stands in for the other. + assert_eq!(::SALT_LEN, 20); + let (pk_20, sk_20) = (pk.key::(), sk.key::()); + let mut digest = [0u8; 64]; + SHA512::hash_out(b"the message", &mut digest); + let good = rsassa::sign_from_hash_with_salt(&sk_20, &digest, &salt[..20]).unwrap(); + rsassa::verify_from_hash(&pk_20, &digest, &good).unwrap(); + for len in [0, 19, 21, 32, 64] { + assert_eq!( + rsassa::sign_from_hash_with_salt(&sk_20, &digest, &salt[..len]), + Err(SALT_LEN), + "{len}" + ); + } + assert_eq!(rsassa::sign_from_hash_with_salt(&sk_20, &digest[..20], &salt[..20]), Err(HASH_LEN)); + assert_eq!(rsassa::verify_from_hash(&pk_20, &digest[..32], &good), Err(HASH_LEN)); +} + +/// RFC 8017 Section 9.1.1 step 3: "If emLen < hLen + sLen + 2, output "encoding error" and +/// stop." RSA-1024 with SHA-512 and its 64-byte salt needs 130 bytes of a 128-byte modulus. +/// No key signs at RSA-1024, but the pairing can be named and its encoding called through +/// the algorithm traits: an error, and from the verification (Section 9.1.2 step 3, +/// "inconsistent") a refusal, in every build. The next size up has the room. +#[test] +fn pss_encoding_refuses_a_modulus_too_short_for_the_hash_and_salt() { + use bouncycastle_rsa::{RSA1024, RSA1536}; + type Short = RSASSA_PSS; + type Unsalted = RSASSA_PSS>; + type Fits = RSASSA_PSS; + let too_short = + || SignatureError::EncodingError("the modulus is too short for this hash and salt length"); + let (digest, salt) = ([0x11u8; 64], [0x42u8; 64]); + + assert_eq!(Short::emsa_encode::<128>(&digest, &salt), Err(too_short())); + assert!(!Short::emsa_verify::<128>(&digest, &[0u8; 128])); + let mut em = [0u8; 128]; + em[127] = 0xbc; + assert!(!Short::emsa_verify::<128>(&digest, &em)); + + // Without a salt the same hash fits (66 of 128 bytes), and with one at RSA-1536 too. + let em = Unsalted::emsa_encode::<128>(&digest).unwrap(); + assert!(Unsalted::emsa_verify::<128>(&digest, &em)); + let em = Fits::emsa_encode::<192>(&digest, &salt).unwrap(); + assert!(Fits::emsa_verify::<192>(&digest, &em)); + + // The boundary itself: a 62-byte salt makes hLen + sLen + 2 exactly emLen, which fits, and + // one byte more does not. + type Exact = RSASSA_PSS>; + type OneOver = RSASSA_PSS>; + let em = Exact::emsa_encode::<128>(&digest, &[0x42u8; 62]).unwrap(); + assert!(Exact::emsa_verify::<128>(&digest, &em)); + assert_eq!(OneOver::emsa_encode::<128>(&digest, &[0x42u8; 63]), Err(too_short())); +} diff --git a/crypto/rsa/tests/keygen_tests.rs b/crypto/rsa/tests/keygen_tests.rs new file mode 100644 index 000000000..0c50c683d --- /dev/null +++ b/crypto/rsa/tests/keygen_tests.rs @@ -0,0 +1,342 @@ +//! Tests for [`bouncycastle_rsa::keygen`] and the per-size `keygen` functions: +//! known-answer checks of the Miller-Rabin test, and FIPS 186-5 Appendix A.1.1's criteria checked +//! on generated RSA-2048 (and, more slowly, RSA-3072) key pairs, plus the failure modes a broken +//! RNG produces. +//! +//! Key generation is randomized, so there is no fixed expected key; the generated pair is checked +//! against the criteria the generator claims to meet -- the candidates' top bits and parity (A.1.3 +//! steps 4.2.1/4.3), `e` coprime to `p - 1` and `q - 1` (A.1.1 2(a)), `|p - q| > 2^(nlen/2 - 100)` +//! (2(d)), `n = p * q`, and the primality of `p` and `q` under this crate's own Miller-Rabin, +//! whose known-answer tests are in this file too -- and by signing and verifying with it under +//! both schemes, which exercises every CRT component. The primality facts asserted below (the +//! documented Wycheproof `p`/`q` are prime, `p + 2` has the factor 173, `p + 6` is composite with +//! no factor below 2000, `2^521 - 1` and `2^607 - 1` are prime, `2^521 + 1` is divisible by 3) were +//! confirmed offline in Python before being pinned here; nothing here depends on a bignum crate. +//! +//! The RSA-4096 and RSA-8192 generators are exercised only under `--ignored`: an RSA-8192 +//! candidate's Miller-Rabin round is a 4096-bit modular exponentiation and a key needs hundreds of +//! candidates, which is tens of minutes in a debug build (the two together take about half a +//! minute in release). Run them with +//! `cargo test -p bouncycastle-rsa --release --test keygen_tests -- --ignored`. + +use bouncycastle_core::errors::{RNGError, SignatureError}; +use bouncycastle_core::security_strength::SecurityStrength; +use bouncycastle_core::signature_key::{ + DeterministicOneShotSigningKey, OneShotSigningKey, OneShotVerifyingKey, +}; +use bouncycastle_core::traits::PrivateKey; +use bouncycastle_core::traits::RNG; +use bouncycastle_core_test_framework::signature::{CtxBehaviour, TestFrameworkSignature}; +use bouncycastle_ec::montgomery::widening_mul; +use bouncycastle_rng::DefaultRNG; +use bouncycastle_rsa::RSA2048; +use bouncycastle_rsa::RSA3072; +use bouncycastle_rsa::RSA4096; +use bouncycastle_rsa::RSA8192; +use bouncycastle_rsa::keygen::{PUBLIC_EXPONENT, is_probable_prime}; +use bouncycastle_rsa::keys::{RsaPrivateKey, RsaPublicKey}; +use bouncycastle_rsa::rsa_2048::{RSASSA_PKCS1_v1_5_SHA256, RSASSA_PSS_SHA256, SIG_LEN}; +use bouncycastle_rsa::rsassa_pkcs1_v1_5::RSASSA_PKCS1_v1_5; +use bouncycastle_rsa::size::RsaSigningSize; +use bouncycastle_rsa::{rsa_3072, rsa_4096, rsa_8192}; +use bouncycastle_sha2::SHA256; +use core::num::NonZeroUsize; + +/// The documented Wycheproof RSA-2048 key's `p` and `q` (see `rsa_2048_pkcs1_v1_5_tests.rs` for +/// their provenance): two genuine 1024-bit primes. +const P: [u64; 16] = [ + 0x0ea36cfb3a5b18f1, 0x48a6e65332119129, 0x110ad9e7b48a1c93, 0x569156b90113e2e9, + 0xe79813a575cfad9c, 0x69d659d143ec6f17, 0xe81e6bab5ddaa783, 0xbff1c5b80a69f788, + 0x978f6c35814f50ee, 0xe6a289ad4cfbf78f, 0x34d5681e5809d415, 0xbb028bda42eeb5d2, + 0x41c56e4de086b0d5, 0x58b8d1e24f3b55d0, 0xfb5248247d98cb7d, 0xdc431050f782e894, +]; +const Q: [u64; 16] = [ + 0x669f140cfbc20f25, 0xb97bb03677207d95, 0xfd4e06f3ed7299d4, 0x160f90536abc9492, + 0xf5b131f39098f7bc, 0xae8d72c57088d7ab, 0x89b94fbde542aba9, 0x3d3f9880ec47d5e0, + 0x1378a6868af3b7a0, 0x5544070beb057c94, 0x16611debc472fac4, 0xe500ffb79f5b8868, + 0x308a5e32196603b2, 0xea5fb19eb4eabc38, 0x122273ae3222b598, 0xbd1a81e7977f9898, +]; + +fn small(v: u64) -> [u64; N] { + let mut out = [0u64; N]; + out[0] = v; + out +} + +/// `P + k` for a small `k` (no carry out of the low limb for the values used here). +fn p_plus(k: u64) -> [u64; 16] { + let mut out = P; + out[0] = out[0].checked_add(k).unwrap(); + out +} + +/// `2^bits - 1` as 16 limbs. +fn mersenne(bits: u32) -> [u64; 16] { + let mut out = [0u64; 16]; + for (i, limb) in out.iter_mut().enumerate() { + let lo = 64 * i as u32; + *limb = if bits >= lo + 64 { + u64::MAX + } else if bits > lo { + (1u64 << (bits - lo)) - 1 + } else { + 0 + }; + } + out +} + +fn rounds(n: usize) -> NonZeroUsize { + NonZeroUsize::new(n).unwrap() +} + +fn mr16(w: &[u64; 16], n: usize) -> bool { + is_probable_prime::<16, 32, 33>(w, rounds(n), &mut DefaultRNG::default()).unwrap() +} + +#[test] +fn miller_rabin_accepts_known_primes() { + assert!(mr16(&P, 5)); + assert!(mr16(&Q, 5)); + assert!(mr16(&mersenne(521), 5), "2^521 - 1 (M521) is prime"); + assert!(mr16(&mersenne(607), 5), "2^607 - 1 (M607) is prime"); +} + +/// Twenty rounds here: a composite passes one random round with probability at most 1/4, so a +/// false "prime" is a `2^-40` event rather than the `2^-10` five rounds would leave. +#[test] +fn miller_rabin_rejects_known_composites() { + assert!(!mr16(&p_plus(2), 20), "p + 2 has the factor 173 (trial division)"); + assert!(!mr16(&p_plus(4), 20), "p + 4 is divisible by 3"); + assert!(!mr16(&p_plus(6), 20), "p + 6 is composite with no factor below 2000 (Miller-Rabin)"); + let mut m521_plus_2 = mersenne(521); + m521_plus_2[0] = m521_plus_2[0].wrapping_add(2); // 2^521 + 1, divisible by 3 + assert!(!mr16(&m521_plus_2, 20)); + let mut even = P; + even[0] &= !1; + assert!(!mr16(&even, 20), "even"); + assert!(!mr16(&small(0), 20)); + assert!(!mr16(&small(1), 20)); +} + +/// Below `2^20` the trial division against the primes below `2^10` is conclusive on its own +/// (Appendix B.7), so these do not touch the RNG-driven Miller-Rabin rounds at all. +#[test] +fn miller_rabin_decides_small_values_by_trial_division() { + for prime in [2u64, 3, 5, 7, 1021, 65537, 1_048_573] { + assert!(mr16(&small(prime), 1), "{prime} is prime"); + } + for composite in [4u64, 9, 15, 561, 1023, 65535, 1_048_575] { + assert!(!mr16(&small(composite), 1), "{composite} is composite"); + } +} + +/// The CRT components of an encoded private key (`p || q || dP || dQ || qInv`, each `8 * HALF` +/// big-endian bytes, ahead of `e`) as little-endian limbs. +fn crt_components(sk_bytes: &[u8]) -> [[u64; HALF]; 5] { + let field_len = 8 * HALF; + let mut out = [[0u64; HALF]; 5]; + for (f, field) in out.iter_mut().enumerate() { + let bytes = &sk_bytes[f * field_len..(f + 1) * field_len]; + for i in 0..HALF { + let start = field_len - 8 * (i + 1); + field[i] = u64::from_be_bytes(bytes[start..start + 8].try_into().unwrap()); + } + } + out +} + +fn mod_small(a: &[u64; N], m: u64) -> u64 { + let mut rem: u128 = 0; + for limb in a.iter().rev() { + rem = ((rem << 64) | u128::from(*limb)) % u128::from(m); + } + rem as u64 +} + +/// FIPS 186-5 Appendix A.1.1's criteria, checked on the CRT components of a generated key. +fn assert_fips_186_5_criteria( + sk_bytes: &[u8], + n: &[u64; HALF2], + mr_rounds: usize, +) { + let [p, q, d_p, d_q, q_inv] = crt_components::(sk_bytes); + let e = u64::from(PUBLIC_EXPONENT); + let mut rng = DefaultRNG::default(); + for (name, prime) in [("p", &p), ("q", &q)] { + // A.1.3 step 4.2.1 (two most significant bits set) and 4.3 (odd). + assert_eq!(prime[HALF - 1] >> 62, 0b11, "{name}: top two bits set"); + assert_eq!(prime[0] & 1, 1, "{name}: odd"); + // A.1.1 2(a): GCD(p - 1, e) = 1, i.e. p mod e != 1 for prime e. + assert_ne!(mod_small(prime, e), 1, "{name} - 1 must be coprime to e"); + // 2(b)/(c): probably prime. + assert!( + is_probable_prime::(prime, rounds(mr_rounds), &mut rng).unwrap(), + "{name} must be prime" + ); + } + assert_ne!(p, q); + // 2(d): |p - q| > 2^(nlen/2 - 100). nlen/2 - 100 = 64 * (HALF - 2) + 28, so the bits at and + // above that position are limb HALF - 1 and the top 36 bits of limb HALF - 2; some must be set + // (the "exactly 2^(nlen/2 - 100)" edge is a 2^-924 event, not worth a test branch). + let (diff, borrow) = bouncycastle_ec::nat::sub(&p, &q); + let diff = if borrow == 1 { bouncycastle_ec::nat::sub(&q, &p).0 } else { diff }; + assert!( + diff[HALF - 1] != 0 || diff[HALF - 2] >> 28 != 0, + "|p - q| must exceed 2^(nlen/2 - 100)" + ); + // n = p * q. + assert_eq!(widening_mul::(&p, &q), *n); + // The CRT exponents are reduced (RFC 8017 §3.2) and nonzero. + assert!(bouncycastle_ec::nat::sub(&d_p, &p).1 == 1 && d_p != [0u64; HALF]); + assert!(bouncycastle_ec::nat::sub(&d_q, &q).1 == 1 && d_q != [0u64; HALF]); + assert!(bouncycastle_ec::nat::sub(&q_inv, &p).1 == 1 && q_inv != [0u64; HALF]); +} + +#[test] +fn keygen_2048_meets_fips_186_5_criteria_and_signs() { + let (pk, sk) = RSA2048::keygen(&mut DefaultRNG::default()).unwrap(); + assert_eq!(pk.e(), PUBLIC_EXPONENT); + assert_eq!(pk.n(), sk.n()); + assert_fips_186_5_criteria::<16, 32, 33>( + &sk.key::>().encode(), + pk.n(), + 5, + ); + + // Every CRT component takes part in signing, so a round trip under both schemes is a + // functional check of dP, dQ and qInv against n. + let msg = b"signed with a freshly generated RSA-2048 key"; + let sig = sk.key::().sign_deterministic(msg, None).unwrap(); + pk.key::().verify(msg, None, &sig).unwrap(); + assert!(pk.key::().verify(b"other", None, &sig).is_err()); + let sig = sk.key::().sign(&mut DefaultRNG::default(), msg, None).unwrap(); + pk.key::().verify(msg, None, &sig).unwrap(); + + // Two generations give two keys. + let (pk2, _) = RSA2048::keygen(&mut DefaultRNG::default()).unwrap(); + assert_ne!(pk2.n(), pk.n()); +} + +/// The shared conformance suite with the real generator in the `keygen` slot, as the ECDSA tests +/// pass theirs (the fixed-key runs elsewhere in this crate exist because keygen used not to). +#[test] +fn conformance_suite_with_generated_keys() { + TestFrameworkSignature::with_ctx_behaviour(CtxBehaviour::Refused).test_deterministic_signature::, RsaPrivateKey, SIG_LEN>( + || RSA2048::keygen(&mut DefaultRNG::default()).map(|(pk, sk)| (pk.into_key::(), sk.into_key::())), false); +} + +#[test] +fn keygen_3072_meets_fips_186_5_criteria_and_signs() { + let (pk, sk) = RSA3072::keygen(&mut DefaultRNG::default()).unwrap(); + assert_fips_186_5_criteria::<24, 48, 49>( + &sk.key::>().encode(), + pk.n(), + 4, + ); + let msg = b"signed with a freshly generated RSA-3072 key"; + let sig = sk.key::().sign_deterministic(msg, None).unwrap(); + pk.key::().verify(msg, None, &sig).unwrap(); +} + +#[test] +#[ignore = "tens of minutes in a debug build: run with --release --ignored"] +fn keygen_4096_meets_fips_186_5_criteria_and_signs() { + let (pk, sk) = RSA4096::keygen(&mut DefaultRNG::default()).unwrap(); + assert_fips_186_5_criteria::<32, 64, 65>( + &sk.key::>().encode(), + pk.n(), + 4, + ); + let msg = b"signed with a freshly generated RSA-4096 key"; + let sig = sk + .key::() + .sign(&mut DefaultRNG::default(), msg, None) + .unwrap(); + pk.key::().verify(msg, None, &sig).unwrap(); +} + +#[test] +#[ignore = "tens of minutes in a debug build: run with --release --ignored"] +fn keygen_8192_meets_fips_186_5_criteria_and_signs() { + let (pk, sk) = RSA8192::keygen(&mut DefaultRNG::default()).unwrap(); + assert_fips_186_5_criteria::<64, 128, 129>( + &sk.key::>().encode(), + pk.n(), + 4, + ); + let msg = b"signed with a freshly generated RSA-8192 key"; + let sig = sk.key::().sign_deterministic(msg, None).unwrap(); + pk.key::().verify(msg, None, &sig).unwrap(); +} + +/// An RNG whose every output is the byte `fill`, reporting `strength`. +struct ConstantRng { + fill: u8, + strength: SecurityStrength, +} +impl RNG for ConstantRng { + fn add_seed_keymaterial( + &mut self, + _additional_seed: &dyn bouncycastle_core::key_material::KeyMaterialTrait, + ) -> Result<(), RNGError> { + Ok(()) + } + fn next_int(&mut self) -> Result { + Ok(u32::from_ne_bytes([self.fill; 4])) + } + fn next_bytes_out(&mut self, out: &mut [u8]) -> Result { + out.fill(self.fill); + Ok(out.len()) + } + fn fill_keymaterial_out( + &mut self, + _out: &mut dyn bouncycastle_core::key_material::KeyMaterialTrait, + ) -> Result { + unimplemented!() + } + fn security_strength(&self) -> SecurityStrength { + self.strength + } +} + +/// A.1.3's preamble: the DRBG must offer the modulus's security strength (SP 800-57 Part 1: +/// 112 bits for RSA-2048). +#[test] +fn keygen_rejects_an_rng_below_the_required_strength() { + let mut weak = ConstantRng { fill: 0x42, strength: SecurityStrength::None }; + assert!(matches!( + RSA2048::keygen(&mut weak), + Err(SignatureError::RNGError(RNGError::SecurityStrengthInsufficientForAlgorithm)) + )); +} + +/// A generated key pair is a valid one (SP 800-56B Rev. 2 Section 6.4.1.4.3), and validation +/// holds its RNG to what key generation does: the size's strength, and an error where no +/// Miller-Rabin base can be drawn. +#[test] +fn a_generated_key_validates_and_validation_checks_its_rng() { + let (_, sk) = RSA2048::keygen(&mut DefaultRNG::default()).unwrap(); + assert_eq!(sk.validate(&mut DefaultRNG::default()), Ok(())); + + let mut weak = ConstantRng { fill: 0x42, strength: SecurityStrength::None }; + assert_eq!( + sk.validate(&mut weak), + Err(SignatureError::RNGError(RNGError::SecurityStrengthInsufficientForAlgorithm)) + ); + // Every base drawn is zero, which is outside [2, w - 2]. + let mut zeros = ConstantRng { fill: 0, strength: SecurityStrength::_256bit }; + assert_eq!( + sk.validate(&mut zeros), + Err(SignatureError::GenericError("RNG produced no usable Miller-Rabin base in 128 draws")) + ); +} + +/// Steps 4.7/5.8: an RNG that keeps producing the same candidate cannot make progress -- the one +/// candidate is either composite, or equal to `p` and so rejected as too close (5.5) -- and the +/// candidate limits (`5 * nlen`, then `10 * nlen`) turn that into an error instead of a hang. +#[test] +fn keygen_gives_up_on_a_stuck_rng() { + let mut stuck = ConstantRng { fill: 0x42, strength: SecurityStrength::_256bit }; + assert!(matches!(RSA2048::keygen(&mut stuck), Err(SignatureError::GenericError(_)))); +} diff --git a/crypto/rsa/tests/keys_tests.rs b/crypto/rsa/tests/keys_tests.rs new file mode 100644 index 000000000..0980dafc7 --- /dev/null +++ b/crypto/rsa/tests/keys_tests.rs @@ -0,0 +1,1111 @@ +//! Validation tests for [`bouncycastle_rsa::keys`]'s public API, including the +//! `PrivateKey`/`PublicKey` impls `rsa_2048` gives its aliases of these types +//! (`RsaPrivateComponents<32, 16>` *is* `RsaPrivateComponents`, so the traits' methods resolve here once +//! imported). The generic boundary conditions every size shares are covered by +//! `core-test-framework`'s `test_keys` in each size's own test file; these pin the layout itself. + +use bouncycastle_core::errors::{KEMError, KeyDecodingError, RNGError, SignatureError}; +use bouncycastle_core::key_material::KeyMaterialTrait; +use bouncycastle_core::security_strength::SecurityStrength; +use bouncycastle_core::signature_key::DeterministicOneShotSigningKey; +use bouncycastle_core::traits::{PrivateKey, PublicKey, RNG}; +use bouncycastle_rng::DefaultRNG; +use bouncycastle_rsa::keys::{ + RsaPrivateComponents, RsaPrivateKey, RsaPublicComponents, RsaPublicKey, +}; +use bouncycastle_rsa::rsa_2048::{RSA2048KEMPrivateKey, RSASSA_PKCS1_v1_5_SHA256}; +use bouncycastle_rsa::rsassa_pss::RSASSA_PSS; +use bouncycastle_rsa::size::{RsaSigningSize, RsaSize}; +use bouncycastle_rsa::{RSA2048, RSA3072, RSA4096, RSA8192}; +use bouncycastle_sha2::SHA256; +use bouncycastle_utils::secret::ZeroizablePrimitive; + +/// The scheme the encoding tests type their keys with; the bytes are the same under any. +type Pss256 = RSASSA_PSS; + +// A genuine RSA-2048 key: the first SHA-256 group of Wycheproof's +// `rsa_pkcs1_2048_sig_gen_test.json` (`tests/rsa_2048_pkcs1_v1_5_tests.rs` has the provenance), +// with `N = P * Q` by Python's integers. +const P: [u64; 16] = [ + 0x0ea36cfb3a5b18f1, 0x48a6e65332119129, 0x110ad9e7b48a1c93, 0x569156b90113e2e9, + 0xe79813a575cfad9c, 0x69d659d143ec6f17, 0xe81e6bab5ddaa783, 0xbff1c5b80a69f788, + 0x978f6c35814f50ee, 0xe6a289ad4cfbf78f, 0x34d5681e5809d415, 0xbb028bda42eeb5d2, + 0x41c56e4de086b0d5, 0x58b8d1e24f3b55d0, 0xfb5248247d98cb7d, 0xdc431050f782e894, +]; +const Q: [u64; 16] = [ + 0x669f140cfbc20f25, 0xb97bb03677207d95, 0xfd4e06f3ed7299d4, 0x160f90536abc9492, + 0xf5b131f39098f7bc, 0xae8d72c57088d7ab, 0x89b94fbde542aba9, 0x3d3f9880ec47d5e0, + 0x1378a6868af3b7a0, 0x5544070beb057c94, 0x16611debc472fac4, 0xe500ffb79f5b8868, + 0x308a5e32196603b2, 0xea5fb19eb4eabc38, 0x122273ae3222b598, 0xbd1a81e7977f9898, +]; +const D_P: [u64; 16] = [ + 0x209f33f09515d7c1, 0xb4a9b37656917205, 0x276933bb07e4efb9, 0x8c14019808e00414, + 0x289f96da220711e5, 0xfbbd2923d31532fe, 0xc06b414e61c0e1e7, 0x4c23c4588488961d, + 0x4dc48ae34514759c, 0x9c786961ae3e2c35, 0x497e8d9c650688e0, 0x18bf08472612dbe5, + 0x8885fb161870ee12, 0xf21d7c1479d99d47, 0x9121d91952ffd1c7, 0xa94b528b28f29159, +]; +const D_Q: [u64; 16] = [ + 0xf7597ffb68011d8d, 0x7b3cc538c4bab8c9, 0xa8fa480a81a925af, 0x6d6ede7251a383bf, + 0x8a63f788ce3a0f85, 0x0b920502eb478bc9, 0x7e37e755edfe70d9, 0x9cf9948422a16555, + 0x0d6d9ea1f2ef71fd, 0xf7efa32ea0cb6e00, 0x0629b114ca7f780f, 0xcf51176359654348, + 0x540cdcbd4ad35435, 0x31c02ff1a2bc437c, 0xff2503df78bafed5, 0x3af0e72a933aef09, +]; +const Q_INV: [u64; 16] = [ + 0x552fe4bfce945f7b, 0x67e50c999c67247b, 0xfb54ef17be3b2853, 0x241f5921b5ad3983, + 0x02de5eccd143cf31, 0x74e45f6fcc60f216, 0xafa5428a74f12708, 0x88d42294b6a2759b, + 0xe923e1097c0c562f, 0xc968b48a91c38b5b, 0x933e85179c0320b0, 0x7993d0445f758d51, + 0x9bfc042ee0924b1b, 0x41f956d90fa8a793, 0xee7a87b6483a66ee, 0x2640fbfbcfefb163, +]; +const N: [u64; 32] = [ + 0xf7820283f742b9d5, 0x6f453d1f5b4c2e9c, 0x9a02e5a530e77306, 0x5d12569a62807d3b, + 0xc22c4e5ac0f7c1a4, 0xf9f85e7975005d9b, 0x1b4d9cae79d460d8, 0x69816f48698bcbba, + 0x126422f590975a19, 0xfd7afc3e09ada0f1, 0xed5411eb878daf05, 0x4c03145b5d3495d4, + 0x12be82de4d1ece6b, 0x21d0fceca08d945a, 0x7d9658594266f5c0, 0x4c22da610428e09c, + 0x90ed81299615d981, 0x7a1fa26a8dce26f4, 0x3eff8f17e1a02939, 0x254a2fe9765313a0, + 0x3d3e42e46e48c98e, 0xcd20f79c15e8247f, 0x2ed8a7711a1253fa, 0xb5ab393189db9251, + 0x9e89d6eac8845097, 0x1700f65903b46942, 0x1878d80325b6ef5a, 0x37f9746d3f7cafd3, + 0x094fa1fee82224e6, 0x4a8a5b462ebef717, 0x6e45567151355051, 0xa2b451a07d0aa5f9, +]; + +// The same primes under other public exponents, with the `dP` and `dQ` that go with each +// (Python 3.12: `pow(e, -1, P - 1)`, `pow(e, -1, Q - 1)`): the smallest odd `e` with an inverse +// modulo both, the largest below 65537, the smallest above 2^32 and the largest of 64 bits. +const E_SMALL: u64 = 0x7; +const E_SMALL_D_P: [u64; 16] = [ + 0xbf38d08f8f0f7bf7, 0x973accc1d377c0a9, 0x2e4f57f21e05c72f, 0x7a9c318e49c23885, + 0xcd7b78f0d59b3ea2, 0x17e83353023df656, 0x3b7f18f435a1844b, 0x491c70fb73aa444e, + 0x9fbfab8c49e42e3f, 0x3aa6058799b48d76, 0x6755601156e10b7a, 0xfd2606c5dd1ab10a, + 0x6eb9f5e35bbaae30, 0xa0699c8151d8c352, 0x6b0a725dfea07447, 0x7ddd2de51fb884e7, +]; +const E_SMALL_D_Q: [u64; 16] = [ + 0x494d0e526aaf2f63, 0xcda17dddc2ce108f, 0x4737bbd2ce2d494e, 0xeb2fb03b956220fb, + 0x41c7b5f71e241eaa, 0xa140768d073d2c56, 0xab845d87a3c1e854, 0x74e4485c167c7432, + 0xc4c3e4a93eae1572, 0xaa9e4e2d15963469, 0x348e83161e9b4567, 0xc82548f0df8a8601, + 0x22abfa23c8ffb97f, 0xcbfb35ba8139f428, 0x0cf4097c6cf43891, 0x8712ef132311ff48, +]; +const E_BELOW: u64 = 0xfffd; +const E_BELOW_D_P: [u64; 16] = [ + 0x77e6a34950d3cb45, 0x18e839c8bec68dce, 0x535f3bbc7add4f66, 0x158e1c8c426a3cb6, + 0xb733c15ba1860dff, 0xdc74a5a22f0078ac, 0xf218ab3dd9b0832a, 0xe6a06dd278d3d999, + 0xe1352bb095d9d052, 0x8863cc6003e9d305, 0xc215c51ea4476905, 0x7512ff4e89da1d31, + 0x835e8b2b98ab635b, 0x04d6d535dcfd533b, 0xfa8ff1b88cb32028, 0x005dc9a74f6f510a, +]; +const E_BELOW_D_Q: [u64; 16] = [ + 0x03826470445163b9, 0xf0d38e97e5146cf2, 0xb2d17021f389ad85, 0xf615156a2a2c9422, + 0x350f50b09febf84d, 0x5e4a38e29ea4071e, 0x9df43b6bec7674d4, 0x9eb0cfdf8a76ae95, + 0x575724326fb39135, 0x732640a7c5606412, 0x54d81126d12a574a, 0x33669f24940094f0, + 0xb2fb9cc530c6b5f4, 0x93e903f90fa61063, 0x8d9f09cd08d53532, 0x49e8d2d188652245, +]; +const E_WIDE: u64 = 0x100000001; +const E_WIDE_D_P: [u64; 16] = [ + 0x2a5aadf862509241, 0xf4e20920ff315f12, 0xaeee9ede3c51ac00, 0x8bfc23f3be90233a, + 0xe3ba1b4fc024a574, 0xbf1114de95cd0ccd, 0x99b53863ef13800b, 0x1ec975792f3daece, + 0xfcacb48978fdb324, 0x6e2fdd52d1aa2c70, 0x139b5a277eb919ec, 0x39fb7db865e8df3e, + 0x7c2390466bf502a2, 0x8b8cdb4674eeeb33, 0x98c61c689f2266a7, 0x8c145c9cf5717a8c, +]; +const E_WIDE_D_Q: [u64; 16] = [ + 0x01593384c82b3989, 0x8b72990d63f57e7a, 0xac6fd29d8dc6a8c7, 0x20878c7a0bf9b0c9, + 0x5061b5bc2701a64d, 0xe39713da5fc8694b, 0x79406f9357eeaaa4, 0x86c92fa01aae34db, + 0x6d6cc27867f92710, 0x18ee118e11964127, 0x7ffeeac8bbafb780, 0x3c209fc23c7a39e2, + 0x1683eebb30e62085, 0x6d6ed21bad159c65, 0xeae8d36fd3e99db9, 0x38c34f9e91cfd1d9, +]; +const E_TOP: u64 = 0xfffffffffffffffd; +const E_TOP_D_P: [u64; 16] = [ + 0x2d8f40f711030b55, 0x612763e1a7e4d026, 0x466b92677fcb720c, 0x710630dad58debc5, + 0x271660ecf1f4e376, 0xe8a2b8fc28878425, 0x920c2036ef255e14, 0x48e81c71ca282490, + 0x8674acbc5ad74738, 0x18583b1402b582b2, 0x0a09b5d952847ed0, 0x5ce58cfd03517976, + 0x4ed20001082a4aa6, 0x3517632c437b0b34, 0x1ceb827a39234d34, 0x6d0343843e622cb6, +]; +const E_TOP_D_Q: [u64; 16] = [ + 0x7466c40e5e4fdf4d, 0xd485574b3574477e, 0xa8c65f4c534ffb00, 0xc7f41139b8b0b17f, + 0xa6fd09e60c48b8b9, 0x7fecbee2c09736de, 0xf204586ce1479ae9, 0x0a2125f0ccdc0532, + 0x4672d26c4f4bff30, 0x12dcf4d1a17957c1, 0x832911cd468281f7, 0xcb91763e8bf7d54f, + 0x6e5e6376f37061b0, 0x490eb823fda561c3, 0x9f27c91a5600208d, 0x17f04b3290f24fc2, +]; + +// `D_P` and `Q_INV` times `2^64 + 1`, modulo `P - 1` and `P`: components whose congruence +// comes to `2^64 + 1` and not 1, a value that differs from 1 above its lowest word only. +const D_P_HIGH: [u64; 16] = [ + 0x329bfae4efd19691, 0x20ac80997b1152e1, 0x3dc78d8e5b3fc2e0, 0xc196ac7710ac253f, + 0x69a71a0ece3e762e, 0x8da3f876623df6e4, 0x98b816f165a71c4c, 0xd855c2f8fea734b2, + 0x03f9a99108d99a49, 0x524e49160f8060db, 0x5e27b31a72033dab, 0x767b84b4093701f8, + 0xcf4687de505b2b4e, 0x8b822646a477e4be, 0x26f16a0e2866d812, 0x765394c55a623a1e, +]; +const Q_INV_HIGH: [u64; 16] = [ + 0xfa55eba0dee1766a, 0x6fbe7cd2bee98a08, 0x7a2fb9386f2dff81, 0x1c0e71343137908c, + 0xd2414046f66b13c7, 0xa5a5fb79d4b06a80, 0xdb850e432f80fa5c, 0xa439055284c1bb2e, + 0x3be23ace28716a26, 0xeae616db11f7cc78, 0x0c40539dfedf1ed6, 0x7da41e9398944b5b, + 0xd411f9513c198515, 0xb390f8a4faeafae9, 0x21dd8e936ffcc49a, 0x570c1d12866056bb, +]; + +// Key pairs that the constructor takes and SP 800-56B Rev. 2 §6.4.1.4.3 does not, one for each +// of its criteria, by Python 3.12 (primes by 40 rounds of Miller-Rabin; every `dP`, `dQ` and +// `qInv` the inverse it should be, with e = 65537 where none is named). +// +// LOW: `p` is about 1.3 * 2^1023, below sqrt(2) * 2^1023; `LOW_P_INV` is `p^-1 mod q`, for the +// same pair with its primes exchanged. +// CLOSE: `q - p` is just above 2^900. +// COMPOSITE_SMALL: `p` is three times a prime. COMPOSITE_MR: `p` is the product of two 512-bit +// primes. Both go with `COMPOSITE_Q`. COMPOSITE_SECOND: `P` above with `COMPOSITE_MR_P` as `q`. +// SHARED: `p = 6g + 1` and `q = 8g + 1`, so LCM(p - 1, q - 1) is 24g and the private exponent +// of e = 65537 has 1023 bits; that of e = 65539 has 1025. +const LOW_P: [u64; 16] = [ + 0x2de7a655eb9290af, 0x6424696b02a0d676, 0xd9edc4c41ba8f717, 0xaea9413abfe74974, + 0xfe824590319e16d3, 0xfe9bc4d06047f54d, 0x65190b64a4c53325, 0xc371b3af45b32031, + 0x93d0438a38c8c25e, 0x999cc2e548f3fcc2, 0x696327472c84f674, 0xeb8748b4c0811bd9, + 0x0ea2fdcbb98eaac2, 0x2310b977c40191a3, 0x8a9a069bae2c6d07, 0xab43d7d93b360a0e, +]; +const LOW_Q: [u64; 16] = [ + 0x0d65180d51ca1125, 0xf8299b0f564b3ae7, 0xa07cde51c81bfa20, 0x6aa109b59dc4ba7c, + 0xd673e9aae15f5a37, 0x0562871e19c938c2, 0x4a6b368a555d7a9d, 0x71ffd529afe6d367, + 0x7be663d9a71e1120, 0xc3010a24a9af5e80, 0x7ebb7f93461e4430, 0x94896263f78e5d68, + 0x54e1fbe387424519, 0x1d30bc9ccbe3cba8, 0x84080730aa8f63d6, 0xfb81051c7ba4f1c0, +]; +const LOW_D_P: [u64; 16] = [ + 0x4f8abe02f3ea72bb, 0x615c24be44c0f34d, 0x5d3661d05041bfc1, 0x82cb140f65b79279, + 0x3aef4fe501e90bda, 0xeb2e22962cb7263a, 0x659532390d1d974a, 0xa11b5f0f149e87ae, + 0x3f858c502d185fc2, 0x1155104991eb671c, 0x4987cf6b755f1a68, 0xf8ce1b0a3ce80c37, + 0xf3f4ea85d8fd81aa, 0xa4aee9a4b1d6b07b, 0x7b279328cbf00492, 0x327443239900fb87, +]; +const LOW_D_Q: [u64; 16] = [ + 0xdbf01377225990a9, 0x61dd380ba9bbef8c, 0x37a046dd83b86bc8, 0x1cd37ed6b4726747, + 0x0594efe763efbe32, 0x42a4b6a5fe64f810, 0x4ac1f18610f1bd5d, 0x4d3fc44408da6145, + 0x1318088ee5ed0e9d, 0x2259fb16a9696d18, 0x3f0fed94c3aa99d6, 0x5531ab2d957d02da, + 0x98900ba6e57fe8b6, 0x60d724fa0bb2096c, 0xd2f00c4abc7a5916, 0x0e972b8ebd759238, +]; +const LOW_Q_INV: [u64; 16] = [ + 0xa02ab48c5187f38b, 0x4b53433cf8a912ae, 0x7addbde0d72a9449, 0xd1e8eee1bf5ac5e3, + 0x3ab68f0bfb75a0bf, 0xf6161746d69891c4, 0xf2a991a9bd83bfb1, 0x9a54a4c2acb63ec0, + 0x7b8419b805f3b684, 0x693a3f6bb58b6b13, 0x8a4a4557ad6df369, 0xae7c232b2eaa53b0, + 0xe6bcc18d0b3b63b2, 0xf36ec7b8ce6adc33, 0x16dd5765e8cb0077, 0x742945219cd0054f, +]; +const CLOSE_P: [u64; 16] = [ + 0x8a97813bb61ea68b, 0xf30375327149366e, 0xfbb68d825612bf7b, 0xfad0e2248020fa92, + 0x32b0fc3ce8c8ebe5, 0xa05de23aac5639cb, 0x40203b30aad0b96a, 0x4de40677b1a9d14b, + 0x9b2c85e8c6a2cb79, 0x7af44989469a0312, 0xfa5b08c7cffeca8b, 0x4a2c40e5a3c8663d, + 0x67dd2736d38987f4, 0xb12ed4fb1375c4cb, 0x1fd4ec92f6c63295, 0xec121853419bd041, +]; +const CLOSE_Q: [u64; 16] = [ + 0x8a97813bb61eace5, 0xf30375327149366e, 0xfbb68d825612bf7b, 0xfad0e2248020fa92, + 0x32b0fc3ce8c8ebe5, 0xa05de23aac5639cb, 0x40203b30aad0b96a, 0x4de40677b1a9d14b, + 0x9b2c85e8c6a2cb79, 0x7af44989469a0312, 0xfa5b08c7cffeca8b, 0x4a2c40e5a3c8663d, + 0x67dd2736d38987f4, 0xb12ed4fb1375c4cb, 0x1fd4ec92f6c632a5, 0xec121853419bd041, +]; +const CLOSE_D_P: [u64; 16] = [ + 0x888a413e05914903, 0x7a69ea399158d16c, 0xf22bff064094ab6a, 0x84a89f9715608981, + 0xf214df95b5037d71, 0x3cc6c9b57f695ffc, 0x5eb25731a1134f36, 0x8305bf443fa7b0bc, + 0xc84b672ee4fee8e6, 0xbaeb2c67bfe4cca3, 0x0aa509bace09b0b5, 0x2d34a8555deadd85, + 0xe2a4a034c45363ae, 0x26ce30984755ad60, 0xc4d9d1cfef819137, 0xd07325f196344c8e, +]; +const CLOSE_D_Q: [u64; 16] = [ + 0xb51dc53887b98e31, 0x6c6b13cadc3295bc, 0x991b6887dd640c12, 0x722b555021da7ece, + 0xac0241a29a577722, 0x5ef94d814625633e, 0x2c1b59b2de85233f, 0x9898627ff1220f08, + 0xac9e76bbcf0390e1, 0xa0b41e8d70a6b3bf, 0x3f5efec06ae329b0, 0x1c4e515ce7ba7afe, + 0x881b742131559f0a, 0x6b09534157ddb29b, 0xf01d8484aab3ecef, 0x211ff8e1d5d6f345, +]; +const CLOSE_Q_INV: [u64; 16] = [ + 0x51e5420152d64096, 0xfd4868cdfcce4ff7, 0x9fc33558191eb2e2, 0xfcdd44f3dc04e47d, + 0x98e906d1c575856e, 0x0c0ebfdc2dd9482c, 0x91a11624a391c69a, 0xcb2a5d7bf256f875, + 0x509afda3c58e4312, 0x24bdd0c90f69b548, 0x8e1d1279ca6f506f, 0xa7ddc0a8bb85b43f, + 0x637c9052c0c000ae, 0xe0139f9b12298311, 0xfa32c902b1adde0c, 0x2c3429dad65bb79a, +]; +const COMPOSITE_SMALL_P: [u64; 16] = [ + 0x99700d4db1e29b31, 0x0a0bf0bfc97f85c5, 0xaf0a6802589f67bf, 0x66d8dc7c6caeb939, + 0xd0c79d317b7d0bcd, 0xa1f380c565ef7cde, 0xd75a82c6ab92eba0, 0x006a20f983502b39, + 0xe68901c2783e5178, 0x6f440c83c818b332, 0xd73459d7d9019396, 0xf92edae27de6dec3, + 0x7a3c2ca631572eba, 0xa670352b85cb5acc, 0x7a647423c0876909, 0xc748520bbc92082e, +]; +const COMPOSITE_SMALL_D_P: [u64; 16] = [ + 0x240b73f899b01131, 0x64ab6a36dc2a9805, 0x96516c7e159e3063, 0x8e9004ddbfd7c4a3, + 0x9a17e364804aca55, 0x9ebbb8305ca31199, 0x076f9ed9c621a7ee, 0xfc35a0e357eb0746, + 0x86c213fa8141ac46, 0x15e62e69182cc2b5, 0xc5bb37e0a3456746, 0xfa692808ca925bc2, + 0x78fadeb206d91465, 0x84dfc1dff77c04a1, 0xc9814e6f33726f85, 0x08a9c32f516e43be, +]; +const COMPOSITE_SMALL_Q_INV: [u64; 16] = [ + 0x88b4bd98d7369220, 0x58eaae378022d46b, 0xf7172070956c9c15, 0x71ac0bb4dc8ef543, + 0x64872fa1c14baa4c, 0x2dd1c8253eeca512, 0xfc087cb3ad0b7f9e, 0xb91b897d9f5a5657, + 0x191953f77a7e3e17, 0x0c1468a477398f66, 0x5bf8dc5bc4250857, 0x4013fc236caffaec, + 0xce7199f1799b53c5, 0x655fe9a53b558c5e, 0x5506352d12dc99bb, 0xb9128974bb640972, +]; +const COMPOSITE_Q: [u64; 16] = [ + 0x61fc4b8f90b13e67, 0xab62f01d9209f77b, 0x5910844011bcd161, 0x883778b6aa03c85a, + 0x3c0977eb6cda92ab, 0x08c03adf8dc16f56, 0x28325cc990ad7879, 0x3b1d6d202ca0dfbc, + 0x6c8a2785da2b283b, 0x489b3a348da37d2a, 0xb75ea63bbed850c0, 0xf308674f78527135, + 0x27da49422c00e463, 0x6e7cd5032530cd80, 0x8e8cfde9778bc9d1, 0xfb9553049924adfe, +]; +const COMPOSITE_D_Q: [u64; 16] = [ + 0x46a11c1255dcc2ff, 0xabff482b9fbaa640, 0xcd17cb15ecb1d7d8, 0x08c18909ddc4fe5e, + 0x1dd467f400aa4984, 0x8ccf0756febcda6a, 0xe9e90d4d7fc30f4d, 0xa8303172068bc87e, + 0x4d4b8409d72e92e5, 0xce23beb0e287b102, 0x3171621b61c52ff7, 0x862febb4ed802d40, + 0xd5ce90e6ccaa2fea, 0x14d1dffd3bdff360, 0xaf55339f8b7b3886, 0x23e3905d368f81f6, +]; +const COMPOSITE_MR_P: [u64; 16] = [ + 0x3d816d53f5c204f9, 0x87cc04ff4b97b7de, 0xaf0f58ede9d5efd7, 0xd383d0b65bf8e3b0, + 0xef1cae6d06c25187, 0xd9651fc1f13dbf80, 0x032f21a717d174da, 0x46cfe8b2154ada9f, + 0x3662f71a81ba1834, 0x13c6d175301d5c53, 0x94afaed7f0a4ce91, 0x956518b151abea51, + 0x919ac818db2112da, 0x6860620f30d8676d, 0xc3050169dcd1cef8, 0xe7ba00ec1db593d7, +]; +const COMPOSITE_MR_D_P: [u64; 16] = [ + 0xe193d881e75faf91, 0x060fb8ee2ee78958, 0xb8faa9f5edd955a7, 0x5232821d5bb77bea, + 0x9ecb7ee6bff091cd, 0xc5dcc0b89eeba22f, 0x2ae4208e5dcf29e8, 0x3332e4479283d796, + 0xe0cc1f61113bda7c, 0x39d84e8177b01115, 0x3b2d3ce0e25dcc24, 0x0f3bbe2b37eab4dd, + 0x3ff74f69c889f92b, 0x426c8b38db03f417, 0x510a6f3812320a97, 0x26bed514a5cb0c93, +]; +const COMPOSITE_MR_Q_INV: [u64; 16] = [ + 0xe4b315cbe51c3bc7, 0x108d1a43a2fb29cd, 0xb40013de40010024, 0x7f4720ae73149400, + 0x08539072730686b9, 0xc06af9560f730262, 0xc5c4587962ea9cfb, 0x0dc6b586f0a02dc2, + 0x16269017260359c1, 0x2cb0157e5ec1f433, 0x625653e254127f39, 0xa6a751f17ca1bbbd, + 0x4eb998e18cc9f0a3, 0xed769524aeabd3c7, 0x1f17540877b860e9, 0x45d93af77ad1f349, +]; +const COMPOSITE_SECOND_D_Q: [u64; 16] = [ + 0xe193d881e75faf91, 0x060fb8ee2ee78958, 0xb8faa9f5edd955a7, 0x5232821d5bb77bea, + 0x9ecb7ee6bff091cd, 0xc5dcc0b89eeba22f, 0x2ae4208e5dcf29e8, 0x3332e4479283d796, + 0xe0cc1f61113bda7c, 0x39d84e8177b01115, 0x3b2d3ce0e25dcc24, 0x0f3bbe2b37eab4dd, + 0x3ff74f69c889f92b, 0x426c8b38db03f417, 0x510a6f3812320a97, 0x26bed514a5cb0c93, +]; +const COMPOSITE_SECOND_Q_INV: [u64; 16] = [ + 0x6b6ee542e598d393, 0x82fd60ee47af0965, 0xc3f0cd147ac0183f, 0x3f371ddc53b83a3a, + 0x6a2be84b4033aa0d, 0xcf31b64d97500836, 0x24f576bbb41d6362, 0x80ba6364b1db641a, + 0xdb81c9885dccede3, 0xc547c357c5777fca, 0x83ba215c3a6fc766, 0x53a16c6abb7a2948, + 0xc755d8449d799b96, 0x1a871a3d1e24ad4e, 0x536a78e3d125d2ef, 0x529bc0bdc269d5ec, +]; +const SHARED_P: [u64; 16] = [ + 0x3a41dafa7af63da7, 0x070cb59dccae7585, 0x66dfa71a24527bd3, 0x83fd40b7168acd75, + 0x5cc9c98715a18470, 0xc6dd5479b640d157, 0xce4f20447a085018, 0x0f4d08062af17f1a, + 0xc321b5483d617f19, 0xc6742291057e1d3e, 0x4d34ea0bc1e65c89, 0xcf77247ebeec6e6b, + 0x6ac694686b7ccb61, 0xd495a4e4a2c5538d, 0xba34deac71b65a74, 0xbeb66586afa59a9a, +]; +const SHARED_Q: [u64; 16] = [ + 0xf857cea34e9da789, 0x5ebb9cd2663df206, 0x892a3422db18a519, 0xaffc56497363bc9c, + 0xd10d0cb41cd75b40, 0xb3d1c5f79dabc1c9, 0x6869805b4d606acb, 0xbf1160083941fece, + 0x042cf1b5a72ca976, 0xb345836c0752d1a9, 0x119be2ba57ddd0b7, 0xbf4985fe53e5e88f, + 0xe3b3708b39fbb9d7, 0x1b723130d9071a11, 0x4d9bd390979dcdf1, 0xfe48875e3f8778ce, +]; +const SHARED_Q_INV: [u64; 16] = [ + 0x3a41dafa7af63da4, 0x070cb59dccae7585, 0x66dfa71a24527bd3, 0x83fd40b7168acd75, + 0x5cc9c98715a18470, 0xc6dd5479b640d157, 0xce4f20447a085018, 0x0f4d08062af17f1a, + 0xc321b5483d617f19, 0xc6742291057e1d3e, 0x4d34ea0bc1e65c89, 0xcf77247ebeec6e6b, + 0x6ac694686b7ccb61, 0xd495a4e4a2c5538d, 0xba34deac71b65a74, 0xbeb66586afa59a9a, +]; +const SHARED_E_SMALL_D: u64 = 65537; +const SHARED_E_SMALL_D_D_P: [u64; 16] = [ + 0x8d67d1085a791951, 0xf1523ce2c9e284ca, 0xa27e4a7d54e9f630, 0x5b8c6783c6264647, + 0x1c45c4d86df31a6d, 0xde391dd891f680da, 0xc3245bb6629aab98, 0x64779920a6956121, + 0xc10f0f1b4d830ab3, 0x57c905982bd9848f, 0x477380bf72b79a16, 0xec07214a18a041bc, + 0xd0ebd384dac79cbe, 0xbed7420f3fc322ae, 0x80b19ae5d2cc46a9, 0x4d4428ae00cbdf6f, +]; +const SHARED_E_SMALL_D_D_Q: [u64; 16] = [ + 0x8d67d1085a791951, 0xf1523ce2c9e284ca, 0xa27e4a7d54e9f630, 0x5b8c6783c6264647, + 0x1c45c4d86df31a6d, 0xde391dd891f680da, 0xc3245bb6629aab98, 0x64779920a6956121, + 0xc10f0f1b4d830ab3, 0x57c905982bd9848f, 0x477380bf72b79a16, 0xec07214a18a041bc, + 0xd0ebd384dac79cbe, 0xbed7420f3fc322ae, 0x80b19ae5d2cc46a9, 0x4d4428ae00cbdf6f, +]; +const SHARED_E_LARGE_D: u64 = 65539; +const SHARED_E_LARGE_D_D_P: [u64; 16] = [ + 0x2ebe9fe53cd80b2d, 0xdb3d9390ac1f4d02, 0xe68485decfb6630b, 0x0e67049811480eb0, + 0xc4b33aadb7fc1c50, 0x187221e36fb51fa4, 0xf7f18d74bfb4289c, 0xc4d0c07310dccafb, + 0x0fdf28009d64fad1, 0x6b1269efa73a02a4, 0xbb19d7db8bedacdb, 0xb4d23872b5bfef13, + 0xc324aa88da34728a, 0x2ac20da95bf46ae6, 0x7da302931771a92b, 0xb3053dd4aacad3f6, +]; +const SHARED_E_LARGE_D_D_Q: [u64; 16] = [ + 0x70a8ac3c6930a14b, 0x838eac5c128fd080, 0xc439f8d618f039c5, 0xe267ef05b46f1f89, + 0x506ff780b0c6457f, 0x2b7db065884a2f32, 0x5dd72d5dec5c0de9, 0x150c6871028c4b48, + 0xced3eb933399d074, 0x7e410914a5654e39, 0xf6b2df2cf5f638ad, 0xc4ffd6f320c674ef, + 0x4a37ce660bb58414, 0xe3e5815d25b2a462, 0xea3c0daef18a35ae, 0x73731bfd1ae8f5c2, +]; +const LOW_P_INV: [u64; 16] = [ + 0x534eca1d89d7145b, 0xccb16100a7bc160a, 0xb3a42e82520df80a, 0x969de6623e4088eb, + 0xce40f28f68823bfb, 0xc44479ddd30ef501, 0xff2095bc1e0668d0, 0x49f0ebbe010bdade, + 0xc8f33199463bff38, 0x64bbb79d7a8b4f15, 0xe86d85cfcd9331b9, 0x14e31ae0c5c1b577, + 0x2fbf36cdeeb81ada, 0x1e9b8b95c35be4a7, 0x9a210fe72baabd0b, 0x50eb9c5e894e9400, +]; + +#[test] +fn from_crt_components_accepts_a_genuine_key_and_derives_n() { + let sk = + RsaPrivateComponents::::from_crt_components(&P, &Q, &D_P, &D_Q, &Q_INV, 0x10001) + .expect("genuine RSA-2048 CRT components must be accepted"); + assert_eq!(*sk.n(), N); +} + +#[test] +fn from_crt_components_rejects_equal_primes() { + assert!(matches!( + RsaPrivateComponents::::from_crt_components(&P, &P, &D_P, &D_Q, &Q_INV, 0x10001), + Err(SignatureError::DecodingError(_)) + )); +} + +#[test] +fn from_crt_components_rejects_even_prime() { + let mut even_p = P; + even_p[0] &= !1; + assert!(matches!( + RsaPrivateComponents::::from_crt_components( + &even_p, &Q, &D_P, &D_Q, &Q_INV, 0x10001 + ), + Err(SignatureError::DecodingError(_)) + )); +} + +#[test] +fn from_crt_components_rejects_even_q() { + let mut even_q = Q; + even_q[0] &= !1; + assert!(matches!( + RsaPrivateComponents::::from_crt_components( + &P, &even_q, &D_P, &D_Q, &Q_INV, 0x10001 + ), + Err(SignatureError::DecodingError(_)) + )); +} + +#[test] +fn from_crt_components_rejects_dp_out_of_range() { + assert!(matches!( + RsaPrivateComponents::::from_crt_components(&P, &Q, &P, &D_Q, &Q_INV, 0x10001), + Err(SignatureError::DecodingError(_)) + )); +} + +#[test] +fn from_crt_components_rejects_qinv_out_of_range() { + assert!(matches!( + RsaPrivateComponents::::from_crt_components(&P, &Q, &D_P, &D_Q, &P, 0x10001), + Err(SignatureError::DecodingError(_)) + )); +} + +#[test] +fn public_key_accepts_e_65537() { + let pk = RsaPublicComponents::::new(&N, 0x00010001).expect("e = 65537 is valid"); + assert_eq!(*pk.n(), N); + assert_eq!(pk.e(), 0x00010001); +} + +#[test] +fn public_key_rejects_even_exponent() { + for e in [0, 2, 4, 65536, 1 << 32, u64::MAX - 1] { + assert!(matches!( + RsaPublicComponents::::new(&N, e), + Err(SignatureError::DecodingError(_)) + )); + } +} + +#[test] +fn public_key_rejects_exponent_below_three() { + assert!(matches!( + RsaPublicComponents::::new(&N, 1), + Err(SignatureError::DecodingError(_)) + )); + assert!(RsaPublicComponents::::new(&N, 3).is_ok()); +} + +#[test] +fn public_key_rejects_even_modulus() { + let mut even_n = N; + even_n[0] &= !1; + assert!(matches!( + RsaPublicComponents::::new(&even_n, 3), + Err(SignatureError::DecodingError(_)) + )); +} + +#[test] +fn public_key_encode_round_trips() { + // 65537, a 33-bit and a 56-bit exponent, and the largest there is. + for e in [0x10001, 0x1_0000_0001, 0x00c0_ffee_1234_5677, u64::MAX] { + let pk = RsaPublicComponents::::new(&N, e).unwrap().into_key::(); + let bytes: [u8; 264] = pk.encode(); + assert_eq!(bytes[256..], e.to_be_bytes()); + let decoded = RsaPublicKey::::from_bytes(&bytes).expect("must decode"); + assert_eq!(decoded, pk); + assert_eq!(decoded.e(), e); + } +} + +/// `PublicKey`'s `n || e` layout, checked field by field rather than only by round +/// trip: `n` big-endian (its most significant limb's top byte first), then `e` big-endian in +/// eight bytes. +#[test] +fn public_key_encode_layout_is_n_then_e_big_endian() { + let pk = RsaPublicComponents::::new(&N, 0x10001).unwrap().into_key::(); + let bytes = pk.encode(); + assert_eq!(bytes[..8], N[31].to_be_bytes()); + assert_eq!(bytes[248..256], N[0].to_be_bytes()); + assert_eq!(bytes[256..], [0, 0, 0, 0, 0x00, 0x01, 0x00, 0x01]); + + let mut out = [0xaau8; 264]; + assert_eq!(pk.encode_out(&mut out), 264); + assert_eq!(out, bytes); +} + +#[test] +fn public_key_from_bytes_rejects_even_modulus() { + let pk = RsaPublicComponents::::new(&N, 0x10001).unwrap().into_key::(); + let mut bytes: [u8; 264] = pk.encode(); + bytes[255] &= !1; // clear n's low bit (last byte, big-endian) + assert!(matches!(RsaPublicKey::::from_bytes(&bytes), Err(KeyDecodingError(_)))); +} + +#[test] +fn public_key_from_bytes_rejects_wrong_lengths() { + let pk = RsaPublicComponents::::new(&N, 0x10001).unwrap().into_key::(); + let bytes = pk.encode(); + assert!(matches!(RsaPublicKey::::from_bytes(&bytes[..263]), Err(KeyDecodingError(_)))); + let mut too_long = bytes.to_vec(); + too_long.push(0); + assert!(matches!(RsaPublicKey::::from_bytes(&too_long), Err(KeyDecodingError(_)))); +} + +/// `Display` (a `PublicKey` supertrait) prints `n` as one big-endian hex string and `e` +/// in hex, so a printed key can be matched by eye against a hex dump of its encoding. +#[test] +fn public_key_display_prints_big_endian_hex() { + let pk = RsaPublicComponents::::new(&N, 0x10001).unwrap().into_key::(); + let shown = format!("{pk}"); + let n_hex: String = pk.encode()[..256].iter().map(|b| format!("{b:02x}")).collect(); + assert_eq!( + shown, + format!("RsaPublicKey {{ n: {n_hex}, e: 10001 }}") + ); +} + +#[test] +fn private_key_encode_round_trips() { + let sk = + RsaPrivateComponents::::from_crt_components(&P, &Q, &D_P, &D_Q, &Q_INV, 0x10001) + .unwrap() + .into_key::(); + let bytes: [u8; 648] = sk.encode(); + let decoded = RsaPrivateKey::::from_bytes(&bytes).expect("must decode"); + assert_eq!(decoded, sk); + assert_eq!(decoded.e(), 0x10001); + assert_eq!(decoded.components().e(), 0x10001); + + // The exponent is part of the key and of its encoding, at any width: the same primes + // under another `e` are another key, which round trips as itself. + for (e, d_p, d_q) in [ + (E_SMALL, &E_SMALL_D_P, &E_SMALL_D_Q), + (E_WIDE, &E_WIDE_D_P, &E_WIDE_D_Q), + (E_TOP, &E_TOP_D_P, &E_TOP_D_Q), + ] { + let other = + RsaPrivateComponents::::from_crt_components(&P, &Q, d_p, d_q, &Q_INV, e) + .unwrap() + .into_key::(); + assert_ne!(other, sk); + let bytes = other.encode(); + assert_eq!(bytes[640..], e.to_be_bytes()); + let decoded = RsaPrivateKey::::from_bytes(&bytes).expect("must decode"); + assert_eq!(decoded, other); + assert_eq!(decoded.e(), e); + } +} + +/// The private key's copy of `e` is held to the public key's rule, odd and at least 3 (RFC +/// 8017 Section 3.1), by the constructors and on decoding. +#[test] +fn private_key_rejects_an_even_or_small_exponent() { + let good = + RsaPrivateComponents::::from_crt_components(&P, &Q, &D_P, &D_Q, &Q_INV, 0x10001) + .unwrap() + .into_key::(); + for e in [0, 1, 2, 4, 65536, 1 << 32, u64::MAX - 1] { + let expected = + SignatureError::DecodingError("RSA public exponent must be odd and at least 3"); + assert_eq!( + RsaPrivateComponents::::from_crt_components(&P, &Q, &D_P, &D_Q, &Q_INV, e) + .unwrap_err(), + expected + ); + assert!(matches!( + RsaPrivateKey::::from_crt_components(&P, &Q, &D_P, &D_Q, &Q_INV, e), + Err(SignatureError::DecodingError(_)) + )); + let mut bytes = good.encode(); + bytes[640..].copy_from_slice(&e.to_be_bytes()); + assert_eq!( + RsaPrivateKey::::from_bytes(&bytes).unwrap_err(), + KeyDecodingError("RSA public exponent must be odd and at least 3") + ); + } +} + +/// `PrivateKey`'s `p || q || dP || dQ || qInv || e` layout: five fields of 128 bytes +/// big-endian, then `e` big-endian in eight. +#[test] +fn private_key_encode_layout_is_five_big_endian_fields_and_e() { + let sk = + RsaPrivateComponents::::from_crt_components(&P, &Q, &D_P, &D_Q, &Q_INV, 0x10001) + .unwrap() + .into_key::(); + let bytes = sk.encode(); + for (i, field) in [P, Q, D_P, D_Q, Q_INV].iter().enumerate() { + let start = 128 * i; + assert_eq!(bytes[start..start + 8], field[15].to_be_bytes(), "field {i} MSB"); + assert_eq!(bytes[start + 120..start + 128], field[0].to_be_bytes(), "field {i} LSB"); + } + assert_eq!(bytes[640..], [0, 0, 0, 0, 0x00, 0x01, 0x00, 0x01]); + + let mut out = [0xaau8; 648]; + assert_eq!(sk.encode_out(&mut out), 648); + assert_eq!(out, bytes); +} + +#[test] +fn private_key_from_bytes_rejects_equal_primes() { + let sk = + RsaPrivateComponents::::from_crt_components(&P, &Q, &D_P, &D_Q, &Q_INV, 0x10001) + .unwrap() + .into_key::(); + let mut bytes: [u8; 648] = sk.encode(); + // Overwrite q (the second 128-byte field) with p, making the two primes equal. + let p_field = bytes[..128].to_vec(); + bytes[128..256].copy_from_slice(&p_field); + assert!(matches!(RsaPrivateKey::::from_bytes(&bytes), Err(KeyDecodingError(_)))); +} + +#[test] +fn private_key_from_bytes_rejects_wrong_lengths() { + let sk = + RsaPrivateComponents::::from_crt_components(&P, &Q, &D_P, &D_Q, &Q_INV, 0x10001) + .unwrap() + .into_key::(); + let bytes = sk.encode(); + assert!(matches!(RsaPrivateKey::::from_bytes(&bytes[..647]), Err(KeyDecodingError(_)))); + let mut too_long = bytes.to_vec(); + too_long.push(0); + assert!(matches!(RsaPrivateKey::::from_bytes(&too_long), Err(KeyDecodingError(_)))); +} + +/// The CRT checks run through the size's own forwarders: at every signing size a `dP` not +/// below `p`, a `dQ` not below `q` and a `qInv` not below `p` are refused, and so are +/// components in range that are not the inverses they should be (no primality check, so odd +/// values with their top two bits set, whose product is then full length, stand in for the +/// primes). +fn crt_components_out_of_range_rejected() { + let mut p = ::HalfLimbs::ZEROED; + p.as_mut()[0] = 7; + let mut q = ::HalfLimbs::ZEROED; + q.as_mut()[0] = 11; + let top = p.as_ref().len() - 1; + p.as_mut()[top] |= 0b11 << 62; + q.as_mut()[top] |= 0b11 << 62; + let mut small = ::HalfLimbs::ZEROED; + small.as_mut()[0] = 3; + let refused = |d_p, d_q, q_inv, why| { + assert_eq!( + RsaPrivateComponents::::from_crt_components(&p, &q, d_p, d_q, q_inv, 0x10001) + .unwrap_err(), + SignatureError::DecodingError(why) + ); + }; + refused(&small, &small, &small, "dP is not the inverse of e modulo p - 1"); + refused(&p, &small, &small, "dP must be less than p"); + refused(&small, &q, &small, "dQ must be less than q"); + refused(&small, &small, &p, "qInv must be less than p"); +} + +#[test] +fn crt_components_out_of_range_rejected_at_every_signing_size() { + crt_components_out_of_range_rejected::(); + crt_components_out_of_range_rejected::(); + crt_components_out_of_range_rejected::(); + crt_components_out_of_range_rejected::(); +} + +// Key material whose modulus is not full length, for the tests below. Both are genuine keys +// (checked with Python 3.12: `p` and `q` pass 40 rounds of Miller-Rabin, and `dP`, `dQ`, `qInv` +// are `pow(e, -1, p - 1)`, `pow(e, -1, q - 1)`, `pow(q, -1, p)` for e = 65537), so every check +// but the modulus's length passes. +// +// SHORT_2047: two 1024-bit primes whose product has 2047 bits. This file's own test key until +// the length was checked. +const SHORT_2047_P: [u64; 16] = [ + 0xfec673c1b07d4997, 0x98c9e3737faecc8b, 0x01369d6bebcfd19b, 0x8aadc1799d493a6e, + 0x958ca74fe2a455a1, 0x686e62c9e375661d, 0xbf73814b7bf6fe14, 0x791ffe2d364719e4, + 0xc82e25af581825a1, 0x716d239de20732c7, 0xdb517e266b0c15bc, 0xe92c721464fa1e50, + 0x683e7fcc3898a002, 0xc7f69cb8c57e630f, 0xc467ab3a006acdf7, 0xe189725eddf8ccb3, +]; +const SHORT_2047_Q: [u64; 16] = [ + 0x7b4cf8c928cc535f, 0x59f055409b91aa89, 0xcd0ba689661c56d5, 0xe4659bfb595039f4, + 0x751842ab04e21054, 0xe2c2655760ebb5fc, 0xb2f71094e48dc76b, 0x2efed995e680919d, + 0x83c35ffcfdb9ee9d, 0xfe4a5fdb9f28a01b, 0x0ebf4a61e23c7524, 0x8cc355a69e45d7e6, + 0x9589828fca436940, 0x4cd1bfe875cddd70, 0x203e0d5e8d4d3acb, 0x86278c27281306ec, +]; +const SHORT_2047_D_P: [u64; 16] = [ + 0xa7c48ae44e99dd99, 0xa6794425077c6c01, 0x0f7f8dfabf278380, 0xb481c3d6cf359f60, + 0xa5b5efbc5d9f744a, 0x91b95de874b741a1, 0xea3152a3da97ddf5, 0xe180bda330e9eba0, + 0xbcbfcc51e73a7a34, 0x019d0405e258c3c0, 0x0b08c52c187e3667, 0x84a723999981f7c1, + 0x5e50dc3287b126ff, 0xd0204fd4674f4ac6, 0x6e786ef11d0686f6, 0xa82c39200c1c4d67, +]; +const SHORT_2047_D_Q: [u64; 16] = [ + 0x0bc1fcecb5c853bf, 0x2000c1caf24e96d2, 0xb423419c07e0736a, 0x90bcb6fb03d68029, + 0xd811d2e24994ff2e, 0x5a89a6b7c7c83737, 0xbdea803dc4157f87, 0xffe93a09240b9b65, + 0xe6f584c8dc80c30a, 0x5e66076e22c91c3c, 0xb41221e6b67af91b, 0x2e3d8c36b1d9d161, + 0x7b1309bb3857cb1f, 0xee8de5186c920235, 0x5e4785a534bec7a3, 0x85883dd007ea907c, +]; +const SHORT_2047_Q_INV: [u64; 16] = [ + 0xf1be36246c217ae1, 0x079e038ceb7506d7, 0x2021f982bc5f6713, 0x55fa8fdd926a4d0f, + 0xb927b5edab1a24b8, 0xc2a1d37632cfb70e, 0x9ef39b4a3f144e8a, 0x70efa5974ed43d2f, + 0x6ea50741414ce321, 0x7df35889e34d4f38, 0x859106459f51850b, 0xd59e422a92f4a7a2, + 0x0c1e16e70fcbe362, 0xcf95cadb6a1f450d, 0x106a4e948e405012, 0x95a3415bfb9b5ff6, +]; +const SHORT_2047_N: [u64; 32] = [ + 0xbc9607fe59ae4409, 0x33fb0be666401931, 0x29fe66e068d6028b, 0xf4225b99e1483032, + 0x3e05752e447f3448, 0x3621f382f494e49c, 0xb12e1f7bd18e9f62, 0xba911df383b4764d, + 0x206002df096d6863, 0x07e881cdab73cfe3, 0x4e9ca660d04d6b6c, 0xfdd0169786ca06a2, + 0xffc09630c54f5731, 0x79ff3ac5ce73cc72, 0x72dd018024dd28a7, 0x4155291016140929, + 0x21a0943f3500f009, 0xd386df1b9afb0808, 0xd06dca00e14b1311, 0x31ed2137effa6d2a, + 0xb914de4e6361f98f, 0x181ad8797a7574fb, 0x98285be3abda6248, 0xcce5cb7a03c57a7d, + 0x3bdb7daa02c2b084, 0x8bb59db9b76bd95d, 0x95e3a77cea5ff912, 0x841d24a921abd3db, + 0x2895f5b063db401c, 0xe57dc21fc3866988, 0xb88f89afa429e300, 0x7630c947be6e9710, +]; +// SHORT_1024: two 512-bit primes, a 1024-bit modulus held in RSA-2048's widths. Generated for +// this file with Python (`random.Random(20261122)`, candidates with their top two bits set). +const SHORT_1024_P: [u64; 16] = [ + 0x6ef620d8244eb173, 0xc405f88ed21e8bab, 0x4078517af66e0441, 0x036fcb2eab272e2e, + 0x57f09c6542c341ad, 0x8655e0db4ac425db, 0xdc698685e27377e4, 0xcb9dc67a2e18f929, + 0x0000000000000000, 0x0000000000000000, 0x0000000000000000, 0x0000000000000000, + 0x0000000000000000, 0x0000000000000000, 0x0000000000000000, 0x0000000000000000, +]; +const SHORT_1024_Q: [u64; 16] = [ + 0xbcf68cf7e0d108c3, 0xb482cc7300abbbe5, 0xd118d4ab1ffa26fe, 0xeb6cc5ba79b7eeca, + 0xc65068d06f2c1194, 0x4b36e61a4ba7bc16, 0x050695b809674898, 0xd89d96cb1d2958b9, + 0x0000000000000000, 0x0000000000000000, 0x0000000000000000, 0x0000000000000000, + 0x0000000000000000, 0x0000000000000000, 0x0000000000000000, 0x0000000000000000, +]; +const SHORT_1024_D_P: [u64; 16] = [ + 0x507439de1e33939f, 0x0cd5993cb34799c4, 0xcf4386325df05157, 0xef856dc0b69eeb9a, + 0x39358ce56ac1db00, 0x4ac1f2816ff6d7ee, 0x0bec72dd511fa67a, 0xb45edc7e492d9833, + 0x0000000000000000, 0x0000000000000000, 0x0000000000000000, 0x0000000000000000, + 0x0000000000000000, 0x0000000000000000, 0x0000000000000000, 0x0000000000000000, +]; +const SHORT_1024_D_Q: [u64; 16] = [ + 0x04dbb2eefd45ce41, 0xcaa851093ed448e4, 0x476aff0896b72309, 0xcd8f1478d9bfb8ac, + 0x14ad71efe9532d06, 0x72b90e38ea541108, 0x09ff6630bfaedf41, 0x9e559283a52d33cd, + 0x0000000000000000, 0x0000000000000000, 0x0000000000000000, 0x0000000000000000, + 0x0000000000000000, 0x0000000000000000, 0x0000000000000000, 0x0000000000000000, +]; +const SHORT_1024_Q_INV: [u64; 16] = [ + 0x5d11de90a81493d9, 0x8a5a13bcd31c8f63, 0xb9713767ed1bec03, 0xfc6236e7ee0221a8, + 0xb718e73a2653ec00, 0x14428a8dc324d06f, 0x7b8178b611797b9e, 0x4c68e71595d411cf, + 0x0000000000000000, 0x0000000000000000, 0x0000000000000000, 0x0000000000000000, + 0x0000000000000000, 0x0000000000000000, 0x0000000000000000, 0x0000000000000000, +]; +const SHORT_1024_N: [u64; 32] = [ + 0x30365f3e9c5fc299, 0xea89d3517b5001ef, 0x0e1662fd6aff00e2, 0xfaa88695226220ad, + 0x61261165da096479, 0xff857d4c85008a3a, 0xed8cee4bc3cd0936, 0x93dcc09276ea8c4b, + 0xd846665bc425d759, 0x2187cf1d8b30d252, 0xe4c0359865f1981c, 0xcdf3a6d470131436, + 0xc583be54081dfae1, 0xd2439a393fe4795b, 0x56794795de362947, 0xac4a7729cf6d13c3, + 0x0000000000000000, 0x0000000000000000, 0x0000000000000000, 0x0000000000000000, + 0x0000000000000000, 0x0000000000000000, 0x0000000000000000, 0x0000000000000000, + 0x0000000000000000, 0x0000000000000000, 0x0000000000000000, 0x0000000000000000, + 0x0000000000000000, 0x0000000000000000, 0x0000000000000000, 0x0000000000000000, +]; + +/// A modulus with one limb set. +fn small_modulus(value: u64) -> [u64; 32] { + let mut n = [0u64; 32]; + n[0] = value; + n +} + +const TOP_BIT_CLEAR: &str = "RSA modulus must have its top bit set"; + +/// A signature public key's modulus has exactly the size's bit length: RFC 8017 Section 8.1.1 +/// step 1 encodes to `modBits - 1` bits, which EMSA-PSS here takes as `8 * K_LEN - 1`. `n = 1`, +/// `n = 105`, a 1024-bit modulus and a genuine 2047-bit one are each refused, by the +/// components, by the typed key and on decoding. +#[test] +fn public_key_rejects_a_modulus_that_is_not_full_length() { + for n in [small_modulus(1), small_modulus(105), SHORT_1024_N, SHORT_2047_N] { + assert_eq!( + RsaPublicComponents::::new(&n, 0x10001), + Err(SignatureError::DecodingError(TOP_BIT_CLEAR)) + ); + assert!(matches!( + RsaPublicKey::::new(&n, 0x10001), + Err(SignatureError::DecodingError(TOP_BIT_CLEAR)) + )); + // The encoding of what would be that key: n big-endian, then e. + let mut bytes = + RsaPublicComponents::::new(&N, 0x10001).unwrap().key::().encode(); + for (i, limb) in n.iter().enumerate() { + bytes[256 - 8 * (i + 1)..256 - 8 * i].copy_from_slice(&limb.to_be_bytes()); + } + assert_eq!( + RsaPublicKey::::from_bytes(&bytes).unwrap_err(), + KeyDecodingError(TOP_BIT_CLEAR) + ); + } + // The 2047-bit modulus is the largest that is refused: with its top bit set it is taken. + let mut full = SHORT_2047_N; + full[31] |= 1 << 63; + assert!(RsaPublicComponents::::new(&full, 0x10001).is_ok()); +} + +/// The private key's check is on `p * q`. The genuine keys pass every other check, so the +/// error names this one; `n = 105` is `15 * 7` and `n = 1` is `1 * 1`, which the distinct-primes +/// check refuses first. +#[test] +fn private_key_rejects_a_modulus_that_is_not_full_length() { + for (p, q, d_p, d_q, q_inv) in [ + (SHORT_2047_P, SHORT_2047_Q, SHORT_2047_D_P, SHORT_2047_D_Q, SHORT_2047_Q_INV), + (SHORT_1024_P, SHORT_1024_Q, SHORT_1024_D_P, SHORT_1024_D_Q, SHORT_1024_Q_INV), + ] { + assert_eq!( + RsaPrivateComponents::::from_crt_components( + &p, &q, &d_p, &d_q, &q_inv, 0x10001 + ) + .unwrap_err(), + SignatureError::DecodingError(TOP_BIT_CLEAR) + ); + assert!(matches!( + RsaPrivateKey::::from_crt_components(&p, &q, &d_p, &d_q, &q_inv, 0x10001), + Err(SignatureError::DecodingError(TOP_BIT_CLEAR)) + )); + // The encoding of what would be that key: five big-endian fields, then e. + let mut bytes = [0u8; 648]; + for (f, field) in [p, q, d_p, d_q, q_inv].iter().enumerate() { + for (i, limb) in field.iter().enumerate() { + let end = 128 * (f + 1) - 8 * i; + bytes[end - 8..end].copy_from_slice(&limb.to_be_bytes()); + } + } + bytes[640..].copy_from_slice(&0x10001u64.to_be_bytes()); + assert_eq!( + RsaPrivateKey::::from_bytes(&bytes).unwrap_err(), + KeyDecodingError(TOP_BIT_CLEAR) + ); + } + + let limb = |value: u64| { + let mut x = [0u64; 16]; + x[0] = value; + x + }; + // 15 * 7 = 105, with dP = dQ = qInv = 1 in range. + assert_eq!( + RsaPrivateComponents::::from_crt_components( + &limb(15), + &limb(7), + &limb(1), + &limb(1), + &limb(1), + 0x10001 + ) + .unwrap_err(), + SignatureError::DecodingError(TOP_BIT_CLEAR) + ); + assert!(matches!( + RsaPrivateComponents::::from_crt_components( + &limb(1), + &limb(1), + &limb(0), + &limb(0), + &limb(0), + 0x10001 + ), + Err(SignatureError::DecodingError(_)) + )); +} + +/// A typed key exposes its exponent, names its algorithm in `Debug`, and compares by its +/// material. +#[test] +fn typed_keys_expose_e_debug_names_the_algorithm_and_eq_compares_material() { + let pk = RsaPublicComponents::::new(&N, 0x10001).unwrap().into_key::(); + assert_eq!(pk.e(), 0x10001); + let shown = format!("{pk:?}"); + assert!(shown.starts_with("RsaPublicKey { algorithm: \"RSASSA-PSS-SHA256\", components: ")); + let pk_other_e = RsaPublicComponents::::new(&N, 0x10003).unwrap().into_key::(); + assert_eq!(pk, pk.clone()); + assert_ne!(pk, pk_other_e); + + let sk = + RsaPrivateComponents::::from_crt_components(&P, &Q, &D_P, &D_Q, &Q_INV, 0x10001) + .unwrap() + .into_key::(); + let shown = format!("{sk:?}"); + assert!(shown.starts_with("RsaPrivateKey { algorithm: \"RSASSA-PSS-SHA256\", components: ")); + let sk_other = RsaPrivateComponents::::from_crt_components( + &P, &Q, &E_WIDE_D_P, &E_WIDE_D_Q, &Q_INV, E_WIDE, + ) + .unwrap() + .into_key::(); + assert_eq!(sk, sk.clone()); + assert_ne!(sk, sk_other); +} + +/// RFC 8017 Section 3.2: `e * dP == 1 (mod (p - 1))`, `e * dQ == 1 (mod (q - 1))` and +/// `q * qInv == 1 (mod p)`. Components in range that fail one are refused, with the one named, +/// by the constructors and on decoding. +#[test] +fn private_key_rejects_components_that_do_not_belong_together() { + const D_P_WRONG: &str = "dP is not the inverse of e modulo p - 1"; + const D_Q_WRONG: &str = "dQ is not the inverse of e modulo q - 1"; + const Q_INV_WRONG: &str = "qInv is not the inverse of q modulo p"; + let flipped = |x: &[u64; 16], limb: usize, bit: u32| { + let mut x = *x; + x[limb] ^= 1 << bit; + x + }; + let mut one = [0u64; 16]; + one[0] = 1; + let mut p_minus_1 = P; + p_minus_1[0] -= 1; + let mut q_minus_1 = Q; + q_minus_1[0] -= 1; + + let cases: [(&str, [u64; 16], [u64; 16], [u64; 16], u64, &str); 15] = [ + ("dP, a low bit", flipped(&D_P, 0, 1), D_Q, Q_INV, 0x10001, D_P_WRONG), + ("dP, a high bit", flipped(&D_P, 15, 3), D_Q, Q_INV, 0x10001, D_P_WRONG), + ("dP of 1", one, D_Q, Q_INV, 0x10001, D_P_WRONG), + ("dP of p - 1", p_minus_1, D_Q, Q_INV, 0x10001, D_P_WRONG), + ("dP off above its lowest word", D_P_HIGH, D_Q, Q_INV, 0x10001, D_P_WRONG), + ("dP of another exponent", E_WIDE_D_P, D_Q, Q_INV, 0x10001, D_P_WRONG), + ("dQ, a low bit", D_P, flipped(&D_Q, 0, 1), Q_INV, 0x10001, D_Q_WRONG), + ("dQ, a high bit", D_P, flipped(&D_Q, 7, 40), Q_INV, 0x10001, D_Q_WRONG), + ("dQ of 1", D_P, one, Q_INV, 0x10001, D_Q_WRONG), + ("dQ of q - 1", D_P, q_minus_1, Q_INV, 0x10001, D_Q_WRONG), + ("dQ of another exponent", D_P, E_WIDE_D_Q, Q_INV, 0x10001, D_Q_WRONG), + ("qInv, a low bit", D_P, D_Q, flipped(&Q_INV, 0, 0), 0x10001, Q_INV_WRONG), + ("qInv, a high bit", D_P, D_Q, flipped(&Q_INV, 15, 3), 0x10001, Q_INV_WRONG), + ("qInv of 1", D_P, D_Q, one, 0x10001, Q_INV_WRONG), + ("qInv off above its lowest word", D_P, D_Q, Q_INV_HIGH, 0x10001, Q_INV_WRONG), + ]; + for (what, d_p, d_q, q_inv, e, why) in cases { + assert_eq!( + RsaPrivateComponents::::from_crt_components(&P, &Q, &d_p, &d_q, &q_inv, e) + .unwrap_err(), + SignatureError::DecodingError(why), + "{what}" + ); + assert_eq!( + RsaPrivateKey::::from_crt_components(&P, &Q, &d_p, &d_q, &q_inv, e) + .unwrap_err(), + SignatureError::DecodingError(why), + "{what}" + ); + } + // An exponent that is not the key's: neither dP nor dQ is its inverse, and dP is looked + // at first. With the primes exchanged and nothing else, all three are wrong. + let build = RsaPrivateComponents::::from_crt_components; + assert_eq!( + build(&P, &Q, &D_P, &D_Q, &Q_INV, 65539).unwrap_err(), + SignatureError::DecodingError(D_P_WRONG) + ); + assert_eq!( + build(&P, &Q, &D_P, &E_WIDE_D_Q, &Q_INV, E_WIDE).unwrap_err(), + SignatureError::DecodingError(D_P_WRONG) + ); + assert_eq!( + build(&P, &Q, &E_WIDE_D_P, &D_Q, &Q_INV, E_WIDE).unwrap_err(), + SignatureError::DecodingError(D_Q_WRONG) + ); + + // On decoding: one bit of the encoded dP, of the encoded qInv, and of the exponent. + let good = build(&P, &Q, &D_P, &D_Q, &Q_INV, 0x10001).unwrap().into_key::(); + let bytes: [u8; 648] = good.encode(); + for (at, why) in [(383, D_P_WRONG), (511, D_Q_WRONG), (639, Q_INV_WRONG), (647, D_P_WRONG)] { + let mut damaged = bytes; + damaged[at] ^= 2; + assert_eq!( + RsaPrivateKey::::from_bytes(&damaged).unwrap_err(), + KeyDecodingError(why), + "byte {at}" + ); + } +} + +/// SP 800-56B Rev. 2 Section 6.2.1: a key-establishment key needs `e >= 65537`. Genuine keys +/// under a smaller exponent, which the signature key type takes, are refused for that and +/// nothing else, by the constructor and on decoding; one under a larger exponent is taken. +#[test] +fn a_key_establishment_key_refuses_a_genuine_key_with_a_small_exponent() { + const TOO_SMALL: &str = "RSA key-establishment public exponent must be at least 65537"; + for (e, d_p, d_q) in + [(E_SMALL, &E_SMALL_D_P, &E_SMALL_D_Q), (E_BELOW, &E_BELOW_D_P, &E_BELOW_D_Q)] + { + let as_signature_key = + RsaPrivateComponents::::from_crt_components(&P, &Q, d_p, d_q, &Q_INV, e) + .unwrap() + .into_key::(); + assert_eq!( + RSA2048KEMPrivateKey::from_crt_components(&P, &Q, d_p, d_q, &Q_INV, e).unwrap_err(), + KEMError::DecodingError(TOO_SMALL), + "e = {e}" + ); + let bytes: [u8; 648] = as_signature_key.encode(); + assert_eq!( + RSA2048KEMPrivateKey::from_bytes(&bytes).unwrap_err(), + KeyDecodingError(TOO_SMALL), + "e = {e}" + ); + } + let wide = + RSA2048KEMPrivateKey::from_crt_components(&P, &Q, &E_WIDE_D_P, &E_WIDE_D_Q, &Q_INV, E_WIDE) + .unwrap(); + assert_eq!(wide.e(), E_WIDE); + let bytes: [u8; 648] = wide.encode(); + assert_eq!(RSA2048KEMPrivateKey::from_bytes(&bytes).unwrap().e(), E_WIDE); + // The key-establishment key validates as its components do. + assert_eq!(wide.validate(&mut DefaultRNG::default()), Ok(())); + let composite = RSA2048KEMPrivateKey::from_crt_components( + &COMPOSITE_MR_P, &COMPOSITE_Q, &COMPOSITE_MR_D_P, &COMPOSITE_D_Q, &COMPOSITE_MR_Q_INV, + 0x10001, + ) + .unwrap(); + assert_eq!( + composite.validate(&mut DefaultRNG::default()), + Err(KEMError::DecodingError("a prime factor is composite")) + ); +} + +/// The components of a key pair the constructor takes. +fn components( + p: &[u64; 16], + q: &[u64; 16], + d_p: &[u64; 16], + d_q: &[u64; 16], + q_inv: &[u64; 16], + e: u64, +) -> RsaPrivateComponents { + RsaPrivateComponents::::from_crt_components(p, q, d_p, d_q, q_inv, e) + .expect("every check of the constructor passes") +} + +/// SP 800-56B Rev. 2 Section 6.4.1.4.3 on sound key pairs: at e = 65537, under the widest +/// exponent, and with a private exponent just above 2^(nBits/2). +#[test] +fn validate_accepts_a_sound_key_pair() { + let mut rng = DefaultRNG::default(); + assert_eq!(components(&P, &Q, &D_P, &D_Q, &Q_INV, 0x10001).validate(&mut rng), Ok(())); + assert_eq!( + components(&P, &Q, &E_TOP_D_P, &E_TOP_D_Q, &Q_INV, E_TOP).validate(&mut rng), + Ok(()) + ); + let just_above = components( + &SHARED_P, &SHARED_Q, &SHARED_E_LARGE_D_D_P, &SHARED_E_LARGE_D_D_Q, &SHARED_Q_INV, + SHARED_E_LARGE_D, + ); + assert_eq!(just_above.validate(&mut rng), Ok(())); +} + +/// Each criterion of Section 6.4.1.4.3 that the constructor does not check, on a key pair that +/// fails it and no other. +#[test] +fn validate_refuses_a_key_pair_that_fails_a_criterion() { + let mut rng = DefaultRNG::default(); + let mut refused = |sk: RsaPrivateComponents, why: &'static str| { + assert_eq!(sk.validate(&mut rng), Err(SignatureError::DecodingError(why)), "{why}"); + }; + // Step 1.c. + let below = "the public exponent is below 65537"; + refused(components(&P, &Q, &E_SMALL_D_P, &E_SMALL_D_Q, &Q_INV, E_SMALL), below); + refused(components(&P, &Q, &E_BELOW_D_P, &E_BELOW_D_Q, &Q_INV, E_BELOW), below); + // Step 5.a and, with the primes exchanged, 5.b. + let low = "a prime factor is below sqrt(2) * 2^(nBits/2 - 1)"; + refused(components(&LOW_P, &LOW_Q, &LOW_D_P, &LOW_D_Q, &LOW_Q_INV, 0x10001), low); + refused(components(&LOW_Q, &LOW_P, &LOW_D_Q, &LOW_D_P, &LOW_P_INV, 0x10001), low); + // Step 5.c. + refused( + components(&CLOSE_P, &CLOSE_Q, &CLOSE_D_P, &CLOSE_D_Q, &CLOSE_Q_INV, 0x10001), + "the prime factors are too close together", + ); + // Step 5.f, by trial division and by Miller-Rabin, and 5.g. + let composite = "a prime factor is composite"; + refused( + components( + &COMPOSITE_SMALL_P, &COMPOSITE_Q, &COMPOSITE_SMALL_D_P, &COMPOSITE_D_Q, + &COMPOSITE_SMALL_Q_INV, 0x10001, + ), + composite, + ); + refused( + components( + &COMPOSITE_MR_P, &COMPOSITE_Q, &COMPOSITE_MR_D_P, &COMPOSITE_D_Q, &COMPOSITE_MR_Q_INV, + 0x10001, + ), + composite, + ); + refused( + components( + &P, &COMPOSITE_MR_P, &D_P, &COMPOSITE_SECOND_D_Q, &COMPOSITE_SECOND_Q_INV, 0x10001, + ), + composite, + ); + // Step 6.a. + refused( + components( + &SHARED_P, &SHARED_Q, &SHARED_E_SMALL_D_D_P, &SHARED_E_SMALL_D_D_Q, &SHARED_Q_INV, + SHARED_E_SMALL_D, + ), + "the private exponent is not above 2^(nBits/2)", + ); +} + +/// A key with a composite factor is one the constructor takes, its components being the +/// inverses they should be. The result check of the private-key operation is what stops it: +/// nothing is signed, and the caller's buffer is left zeroized. +#[test] +fn a_key_with_a_composite_factor_signs_nothing() { + let sk = components( + &COMPOSITE_MR_P, &COMPOSITE_Q, &COMPOSITE_MR_D_P, &COMPOSITE_D_Q, &COMPOSITE_MR_Q_INV, + 0x10001, + ) + .into_key::(); + assert_eq!(sk.sign_deterministic(b"a message", None), Err(SignatureError::ComputationFault)); + let mut out = [0xFFu8; 256]; + assert_eq!( + sk.sign_deterministic_out(b"a message", None, &mut out), + Err(SignatureError::ComputationFault) + ); + assert_eq!(out, [0u8; 256]); +} + +/// The workspace RNG, counting the bytes it hands out. +struct CountingRng { + inner: DefaultRNG, + bytes: usize, +} + +impl RNG for CountingRng { + fn add_seed_keymaterial(&mut self, seed: &dyn KeyMaterialTrait) -> Result<(), RNGError> { + self.inner.add_seed_keymaterial(seed) + } + fn next_int(&mut self) -> Result { + self.inner.next_int() + } + fn next_bytes_out(&mut self, out: &mut [u8]) -> Result { + self.bytes += out.len(); + self.inner.next_bytes_out(out) + } + fn fill_keymaterial_out(&mut self, out: &mut dyn KeyMaterialTrait) -> Result { + self.inner.fill_keymaterial_out(out) + } + fn security_strength(&self) -> SecurityStrength { + self.inner.security_strength() + } +} + +/// SP 800-56B Rev. 2 Section 6.4.1.2.1 step 5: a composite passes with probability at most +/// 2^-ES(nBits), which at RSA-2048 is 56 Miller-Rabin rounds on each prime. A round draws one +/// base of 128 bytes, and again if the base is out of range, which is less than once in four: +/// a sound key draws at least 2 * 56 bases and nowhere near twice that. +#[test] +fn validate_runs_the_rounds_the_size_asks_for() { + assert_eq!(RSA2048::VALIDATION_MR_ROUNDS.get(), 56); + assert_eq!(RSA3072::VALIDATION_MR_ROUNDS.get(), 64); + assert_eq!(RSA4096::VALIDATION_MR_ROUNDS.get(), 76); + assert_eq!(RSA8192::VALIDATION_MR_ROUNDS.get(), 100); + + let mut rng = CountingRng { inner: DefaultRNG::default(), bytes: 0 }; + assert_eq!(components(&P, &Q, &D_P, &D_Q, &Q_INV, 0x10001).validate(&mut rng), Ok(())); + let bases = 2 * 56; + assert!(rng.bytes >= bases * 128, "{} bytes drawn", rng.bytes); + assert!(rng.bytes < 2 * bases * 128, "{} bytes drawn", rng.bytes); +} diff --git a/crypto/rsa/tests/modexp_tests.rs b/crypto/rsa/tests/modexp_tests.rs new file mode 100644 index 000000000..61d6b006a --- /dev/null +++ b/crypto/rsa/tests/modexp_tests.rs @@ -0,0 +1,311 @@ +//! Known-answer and round-trip tests for [`bouncycastle_rsa::modexp`]. +//! +//! Every KAT value below was computed with Python's arbitrary-precision `pow(base, exp, mod)` +//! (not from recall), so this file is the record of that cross-check rather than a duplicate of +//! it: see each case's comment for how it was produced. + +use bouncycastle_rsa::RSA2048; +use bouncycastle_rsa::modexp::{ + MontgomeryContext, mod_pow, mod_pow_public_exponent, mont_n_prime, mul_mod, reduce_wide, + sub_mod, +}; +use bouncycastle_rsa::size::RsaSize; + +/// The context for `n` from each constructor, the constant-time one for a secret modulus and the +/// variable-time one for a public modulus: every known answer below holds under both. +fn both_contexts(n: &[u64; L]) -> [MontgomeryContext; 2] { + [ + MontgomeryContext::for_secret_modulus(n), + MontgomeryContext::for_public_modulus(n).expect("modulus is odd"), + ] +} + +/// `n' = -n0^-1 mod 2^64` must satisfy `n0 * n' ≡ -1 (mod 2^64)` -- the exact identity +/// [`bouncycastle_ec::montgomery::redc`] relies on. Checked directly by wrapping multiplication, +/// across small, large, and adversarial (all-ones) odd values. +#[test] +fn mont_n_prime_satisfies_redc_identity() { + let candidates: [u64; 6] = [1, 3, 0xFFFFFFFFFFFFFFFF, 0x0CA1, 0xDEADBEEFDEADBEEF, u64::MAX - 4]; + for &n0 in &candidates { + let n_prime = mont_n_prime(n0); + assert_eq!( + n0.wrapping_mul(n_prime), + 0u64.wrapping_sub(1), + "n0 * n' must be -1 mod 2^64 for n0 = {n0:#x}" + ); + } +} + +/// Classic textbook RSA (Wikipedia's worked example): p=61, q=53, n=3233, e=17, d=2753, m=65. +/// `c = pow(65, 17, 3233) = 2790` and `pow(2790, 2753, 3233) = 65`, both via Python's `pow`. +#[test] +fn textbook_rsa_l1() { + let n: [u64; 1] = [0x0000000000000ca1]; + let e: [u64; 1] = [0x0000000000000011]; + let d: [u64; 1] = [0x0000000000000ac1]; + let m: [u64; 1] = [0x0000000000000041]; + let expected_c: [u64; 1] = [0x0000000000000ae6]; + + for ctx in both_contexts(&n) { + let c = mod_pow::<1, 2, 3>(&m, &e, &ctx); + assert_eq!(c, expected_c); + + let decrypted = mod_pow::<1, 2, 3>(&c, &d, &ctx); + assert_eq!(decrypted, m); + } +} + +/// `L = 1`: `n = 2^64 - 59`, `pow(123456789, 987654321, n)`, via Python. +#[test] +fn kat_l1_large_modulus() { + let n: [u64; 1] = [0xffffffffffffffc5]; + let base: [u64; 1] = [0x00000000075bcd15]; + let exp: [u64; 1] = [0x000000003ade68b1]; + let expected: [u64; 1] = [0xb922a86ec0ff6fe7]; + + for ctx in both_contexts(&n) { + assert_eq!(mod_pow::<1, 2, 3>(&base, &exp, &ctx), expected); + } +} + +/// `L = 2` (128-bit modulus `2^127 - 1`), via Python. +#[test] +fn kat_l2_128_bit() { + let n: [u64; 2] = [0xffffffffffffffff, 0x7fffffffffffffff]; + let base: [u64; 2] = [0xc373e0ee4e3f0ad2, 0x000000018ee90ff6]; + let exp: [u64; 2] = [0x0000000000000003, 0x0000000000000000]; + let expected: [u64; 2] = [0xc327da61b1a46a17, 0x02d0b2240ebf02da]; + + for ctx in both_contexts(&n) { + assert_eq!(mod_pow::<2, 4, 5>(&base, &exp, &ctx), expected); + } +} + +/// `L = 4` (256-bit random odd, non-prime modulus), via Python (`random.seed(42)`). +#[test] +fn kat_l4_256_bit() { + let n: [u64; 4] = + [0x1c80317fa3b1799d, 0xbdd640fb06671ad1, 0x3eb13b9046685257, 0x23b8c1e9392456de]; + let base: [u64; 4] = + [0xa83c59a92dc37a35, 0xc64362c7939fc228, 0x90d835f3cac497f1, 0x08477cc431b04409]; + let exp: [u64; 4] = + [0x0822e8f36c031199, 0x17fc695a07a0ca6e, 0x3b8faa1837f8a88b, 0x9a1de644815ef6d1]; + let expected: [u64; 4] = + [0x9c1037426d1f8616, 0x7a21504a60dc2678, 0x8f54fb0513201d76, 0x1d2469f43bb3a703]; + + for ctx in both_contexts(&n) { + assert_eq!(mod_pow::<4, 8, 9>(&base, &exp, &ctx), expected); + } +} + +/// `L = 2`, a genuine 128-bit RSA keypair (two random 64-bit primes, `e = 65537`), sign/verify +/// round trip. Generated with Python (`random.seed(99)`), including `d = pow(e, -1, phi)`. +#[test] +fn genuine_toy_rsa_keypair_round_trip_l2() { + let n: [u64; 2] = [0x5cdd02d9b55c299d, 0x75acc2c4cc38005e]; + let e: [u64; 1] = [0x0000000000010001]; + let d: [u64; 2] = [0x9254c980da0d8d91, 0x27de4c6ed8b1f08d]; + let m: [u64; 2] = [0xa040024187f1a6ad, 0x624948139eab75cd]; + let expected_c: [u64; 2] = [0x0827db8b026ab9ca, 0x756a056f15b29f68]; + + for ctx in both_contexts(&n) { + // Public exponent (17 bits) padded into 2 limbs -- mod_pow processes the full 64*L width + // regardless, so a short public exponent works the same way as a full-width one. + let e_padded: [u64; 2] = [e[0], 0]; + let c = mod_pow::<2, 4, 5>(&m, &e_padded, &ctx); + assert_eq!(c, expected_c); + + let decrypted = mod_pow::<2, 4, 5>(&c, &d, &ctx); + assert_eq!(decrypted, m); + } +} + +/// `L = 32` (2048-bit modulus, RSA-shaped), via Python (`random.seed(7)`). Exercises the +/// production limb count end to end, not just small hand-checkable cases. +#[test] +fn kat_l32_2048_bit() { + let n: [u64; 32] = [ + 0xf2a74de452e6b439, 0x6513270e269e0d37, 0x0c5c7fd0a6a3a450, 0xd23f0824128b2f33, + 0x1818e811892f902b, 0x9531985d5d9dc9f8, 0xe8e25d940ed90475, 0x36f675cc81e74ef5, + 0x1600a35a099950d8, 0x6b0d549b6f03675a, 0x3d9c172411e20b8f, 0x8d116ece1738f7d9, + 0x0f21ddb66cad4a26, 0x90c192cfd3ac94af, 0xf28c105d1fb17c23, 0xa170b33839263059, + 0x953f48f1a09f76b5, 0x0fd630f1f29d0da9, 0x95e60af593bd04cf, 0x0cb1e29c658cda14, + 0x3898d190f9ebdacc, 0x8e81973e0becd7b0, 0x2217beaddbc496cb, 0x6b4cb2424a23d596, + 0x8a6a63ec24ede6a4, 0x922766581e27a1c0, 0x8f6d05584ef8aa38, 0xae97ba94d0eda82f, + 0x1a61dbe22e44158b, 0x923a736994e3bf91, 0x301850c5a38fd547, 0x98f135d25f557203, + ]; + let base: [u64; 32] = [ + 0xb64ce4228c38fb29, 0x907a70c31012f037, 0x9e7769b10f4205b4, 0x7f15052434b9b5df, + 0x881ed162ae2eb154, 0xc6f877186d76b07e, 0x7731af10506bf2ef, 0xec66a78795e761d1, + 0x5c90a9587403e430, 0x3f98e2774cbd87ad, 0x2e05319acb5c7427, 0xc7a2ea20b2f14c94, + 0x14f4733f3e7d1bfb, 0x4cdd2055930d6eaf, 0x7ebff20686734721, 0x57ee05cde00902c7, + 0x72e6cc3ababced20, 0x9be4bcfc49b64a08, 0x12bd4acefaecbd38, 0x830e07bc1e398f10, + 0x2a3af4d46b0a18e8, 0x5790f82ec1d3fcff, 0xeeeacbe226e87555, 0x6bf46c697d2caf82, + 0xf646e1f40a097c97, 0x13deef86ab1031d0, 0x8ede0d7ac3baea9e, 0xca02135e92b1d3f2, + 0xd17f9acae01f5057, 0x571242425051c1cc, 0x59a54a7bb1fee08f, 0x7f26144b98289fcd, + ]; + let exp: [u64; 32] = [ + 0xcc011cdd9474031b, 0x119a72d174c9df6a, 0x17f5e837d70820fe, 0x451abd81f1d69ed6, + 0xb2715945795e8229, 0x10a3d6b2aa05e11a, 0xbb2d420f0f88080b, 0x4f426dcbb394fb36, + 0x93f448b3a5aa3c81, 0xae658f33fe3b890b, 0x72158370d269a9a5, 0xb774eb5248db40af, + 0xe315128862c33a4f, 0x58d5563dab2cd31e, 0xf0ce583505c6af07, 0x5affb2297631a992, + 0x9c6539382b0537e6, 0x7e62aa0a1df9fd78, 0x37dc76fb0f17a300, 0x49952399c4aaeac1, + 0xbd0561e6211c70cf, 0x65dc9f503f63af83, 0xeab477d26415479c, 0x7f1b103cdf1582b0, + 0x2a96fb1a14a0f9e7, 0x66d2287672fdf202, 0x4720771f8ca81811, 0x230d977ee2257159, + 0x6e36aab0d1bc52d9, 0x8cdb305fdd2e1609, 0xb4d66a3a47469a4d, 0xfc891b4a6a50df4d, + ]; + let expected: [u64; 32] = [ + 0x6d8f5211406eb32d, 0xe8816c035e8d63d0, 0xed5ae634462e4c34, 0xf4f19888a1da251d, + 0xba38c3ca7b518263, 0x7239b204d27d070b, 0x1b1973c8ee44aa69, 0x1ec760c7d18d3043, + 0x8c8261b66b4174f1, 0xc010d589c1eff8fd, 0xdb08314101c4e5d4, 0x626777ea0d794791, + 0x2040c20118bd8914, 0x984acd5d9f9d0eea, 0x6defd175fe17fc42, 0x77ced1e2bdb17dcd, + 0xd6684e6654758d1e, 0xff9e73db6471b299, 0x7429feb8b60a1cd7, 0x9b9740637d41d13d, + 0x008061aa7796f060, 0x1ce3f7b5954e82f4, 0x1d4298d60f58dffd, 0xbcc62dca692679ec, + 0x185d509c9c6c3698, 0x423a2e0c55dec062, 0x0d1b157097b65031, 0x5a6ba1b66d5ca4d8, + 0x0f3cba5f0d7fa3a6, 0x8e6e44eaac15c7e5, 0x62bd4e9b9ccd49c3, 0x915f6c85d08df86a, + ]; + + for ctx in both_contexts(&n) { + assert_eq!(mod_pow::<32, 64, 65>(&base, &exp, &ctx), expected); + } +} + +/// The exponents the public exponentiation is tried at: the degenerate ones, RSA's 3 and +/// 65537, a 33-bit and a 56-bit value (SP 800-56B Rev. 2 allows `e` up to 256 bits, and ACVP's +/// keys have them this long), and the largest `u64`, which is odd. +const PUBLIC_EXPONENTS: [u64; 8] = + [0, 1, 2, 3, 65537, 0x0000_0001_0000_0001, 0x00c0_ffee_1234_5677, u64::MAX]; + +/// `mod_pow_public_exponent` at `L = 2`, `pow(base, e, n)` via Python for each exponent of +/// [`PUBLIC_EXPONENTS`]. +#[test] +fn public_exponent_kat_l2() { + let n: [u64; 2] = [0x9e3779b97f4a7c15, 0xd1b54a32d192ed03]; + let base: [u64; 2] = [0xfedcba9876543210, 0x0123456789abcdef]; + let expected: [[u64; 2]; 8] = [ + [0x0000000000000001, 0x0000000000000000], + [0xfedcba9876543210, 0x0123456789abcdef], + [0xde6df9bbc7a21e79, 0x7c7978d71553de08], + [0x25caa256a35cadb6, 0x4a4fabb6e4e905cd], + [0x9ad2e02ca8f65732, 0x5b513f962ca011c5], + [0x970c8e850c403f45, 0x3c0de65adfb7434b], + [0xec9a94e43e78b1d0, 0xc0944232cc57f0f8], + [0x24441fd89d3bf436, 0x7cd393f79b005ffa], + ]; + for ctx in both_contexts(&n) { + for (e, expected) in PUBLIC_EXPONENTS.iter().zip(expected) { + assert_eq!(mod_pow_public_exponent::<2, 4, 5>(&base, *e, &ctx), expected, "e = {e:#x}"); + } + } +} + +/// `mod_pow_public_exponent` gives what `mod_pow`'s ladder gives for the same exponent, at +/// one, four and thirty-two limbs (RSA-2048's modulus width) and for a base at each end of the +/// range as well as inside it. +#[test] +fn public_exponent_agrees_with_the_ladder() { + fn agree(n: &[u64; L], base: &[u64; L]) { + let mut one = [0u64; L]; + one[0] = 1; + let mut n_minus_1 = *n; + n_minus_1[0] -= 1; // n is odd + for ctx in both_contexts(n) { + for base in [&[0u64; L], &one, base, &n_minus_1] { + for e in PUBLIC_EXPONENTS { + let mut e_limbs = [0u64; L]; + e_limbs[0] = e; + assert_eq!( + mod_pow_public_exponent::(base, e, &ctx), + mod_pow::(base, &e_limbs, &ctx), + "L = {L}, e = {e:#x}" + ); + } + } + } + } + agree::<1, 2, 3>(&[0xffffffffffffffc5], &[0x00000000075bcd15]); + agree::<4, 8, 9>( + &[0xffffffffffffff43, 0xffffffffffffffff, 0xffffffffffffffff, 0xffffffffffffffff], + &[0x8899aabbccddeeff, 0x0011223344556677, 0xfedcba9876543210, 0x123456789abcdef0], + ); + // 32 limbs: an odd full-length modulus and a base below it, stepped from fixed constants. + let mut n = [0u64; 32]; + let mut base = [0u64; 32]; + for i in 0..32u64 { + n[i as usize] = 0x9e3779b97f4a7c15u64.wrapping_mul(2 * i + 1) ^ (i << 56); + base[i as usize] = 0xd1b54a32d192ed03u64.wrapping_mul(i + 7); + } + n[0] |= 1; + n[31] |= 1 << 63; + base[31] &= u64::MAX >> 1; + agree::<32, 64, 65>(&n, &base); +} + +/// An even modulus is never valid for Montgomery reduction; RSA moduli are always odd, so this +/// is purely a defensive boundary check, and the public-modulus constructor's alone: the +/// secret-modulus one takes oddness as its caller's and does not branch on it. +#[test] +fn even_modulus_is_rejected() { + let n: [u64; 1] = [4]; + assert!(MontgomeryContext::<1>::for_public_modulus(&n).is_none()); + assert!(MontgomeryContext::<1>::for_public_modulus(&[0]).is_none()); +} + +/// `RsaSize::public_exp` takes limbs and not a key, so no constructor stands in front of it: +/// an even modulus is its documented panic. +#[test] +#[should_panic(expected = "the modulus is odd")] +fn public_exp_panics_on_an_even_modulus() { + let mut n = [0u64; 32]; + n[31] = 1 << 63; + let _ = RSA2048::public_exp(&n, 65537, &[1u64; 32]); +} + +/// `reduce_wide` with `WIDE = 4 > NARROW = 2`, RSA's own use for reducing an `n`-width message +/// down to a CRT prime's width (RFC 8017 §5.2.1 step 2.b.1). Via Python's `%`. +#[test] +fn reduce_wide_wider_value() { + let value: [u64; 4] = + [0x8899aabbccddeeff, 0x0011223344556677, 0xfedcba9876543210, 0x123456789abcdef0]; + let modulus: [u64; 2] = [0xffffffffffffff61, 0xffffffffffffffff]; + let expected: [u64; 2] = [0xd3b18f6d4b290dc4, 0x4e92d71b5fa3de25]; + assert_eq!(reduce_wide::<4, 2>(&value, &modulus), expected); +} + +/// `reduce_wide` with `WIDE == NARROW`, deliberately far outside the `< 2 * modulus` bound a +/// single conditional subtraction would need: `value` is about 4.9 billion times `modulus`. RSA's +/// CRT recombination (step 2.b.3, `s2 mod p`) uses exactly this shape, and RFC 8017 does not +/// bound how large `q`'s residues can be relative to `p` (see `RsaPrivateKey`'s docs) -- this is +/// the case that matters, not the same-limb-count part of the signature. Via Python's `%`. +#[test] +fn reduce_wide_same_width_but_far_outside_double_the_modulus() { + let value: [u64; 2] = [0xfffffffffffffffd, 0xfffffffffffffffe]; + let modulus: [u64; 2] = [0x0000000000000101, 0x00000000deadbeef]; + let expected: [u64; 2] = [0xfffffed88afbe598, 0x00000000a6a2b0b3]; + assert_eq!(reduce_wide::<2, 2>(&value, &modulus), expected); +} + +/// `sub_mod` when `a < b` (the difference must wrap around by adding the modulus once). Via +/// Python's `%`. +#[test] +fn sub_mod_wraps_when_a_less_than_b() { + let a: [u64; 2] = [0x0000000000000005, 0x0000000000000000]; + let b: [u64; 2] = [0x0000000000003039, 0x0000000000000000]; + let n: [u64; 2] = [0xffffffffffffff61, 0xffffffffffffffff]; + let expected: [u64; 2] = [0xffffffffffffcf2d, 0xffffffffffffffff]; + assert_eq!(sub_mod::<2>(&a, &b, &n), expected); +} + +/// `mul_mod` with `a >= modulus` -- only `b` is required to be pre-reduced (see the function's +/// docs on why `a` need not be). Via Python's `%`. +#[test] +fn mul_mod_with_unreduced_first_operand() { + let a: [u64; 2] = [0xfffffffffffffffd, 0xfffffffffffffffe]; + let b: [u64; 2] = [0x23456789abcdef01, 0x0000000000000001]; + let n: [u64; 2] = [0xffffffffffffff61, 0xffffffffffffffff]; + let expected: [u64; 2] = [0x7e4b17e4b17da35e, 0xdcba9876543211b0]; + + for ctx in both_contexts(&n) { + assert_eq!(mul_mod::<2, 4, 5>(&a, &b, &ctx), expected); + } +} diff --git a/crypto/rsa/tests/rng_short_draw_tests.rs b/crypto/rsa/tests/rng_short_draw_tests.rs new file mode 100644 index 000000000..819af072c --- /dev/null +++ b/crypto/rsa/tests/rng_short_draw_tests.rs @@ -0,0 +1,193 @@ +//! A draw from the RNG that comes back short is an error everywhere this crate draws: the +//! contract of `RNG::next_bytes_out` is that the buffer is zeroized and the count of bytes +//! written returned, so an RNG that writes half and says so must not have its zeros used as +//! half of a prime candidate, a salt, an OAEP seed, a transported key or a secret value. + +use bouncycastle_core::errors::{KEMError, KeyTransportError, RNGError, SignatureError}; +use bouncycastle_core::kem_key::EncapsulatingKey; +use bouncycastle_core::key_material::{KeyMaterial, KeyMaterialTrait, KeyType}; +use bouncycastle_core::key_transport_key::KeyTransportEncryptingKey; +use bouncycastle_core::security_strength::SecurityStrength; +use bouncycastle_core::signature_key::{OneShotSigningKey, SigningKey}; +use bouncycastle_core::traits::RNG; +use bouncycastle_rsa::RSA2048; +use bouncycastle_rsa::keygen::is_probable_prime; +use bouncycastle_rsa::keys::RsaPrivateComponents; +use bouncycastle_rsa::rsa_2048::{RSA2048KEMPublicKey, RSASSA_PSS_SHA256}; +use bouncycastle_rsa::rsaes_oaep::OaepParams; +use bouncycastle_rsa::rsassa::sign_from_hash; +use bouncycastle_rsa::size::{KemKeyPair, RsaSigningSize, SignatureKeyPair}; +use bouncycastle_sha2::SHA256; +use core::num::NonZeroUsize; + +// A genuine RSA-2048 key: the first SHA-256 group of Wycheproof's +// `rsa_pkcs1_2048_sig_gen_test.json` (`tests/rsa_2048_pkcs1_v1_5_tests.rs` has the provenance). +const P: [u64; 16] = [ + 0x0ea36cfb3a5b18f1, 0x48a6e65332119129, 0x110ad9e7b48a1c93, 0x569156b90113e2e9, + 0xe79813a575cfad9c, 0x69d659d143ec6f17, 0xe81e6bab5ddaa783, 0xbff1c5b80a69f788, + 0x978f6c35814f50ee, 0xe6a289ad4cfbf78f, 0x34d5681e5809d415, 0xbb028bda42eeb5d2, + 0x41c56e4de086b0d5, 0x58b8d1e24f3b55d0, 0xfb5248247d98cb7d, 0xdc431050f782e894, +]; +const Q: [u64; 16] = [ + 0x669f140cfbc20f25, 0xb97bb03677207d95, 0xfd4e06f3ed7299d4, 0x160f90536abc9492, + 0xf5b131f39098f7bc, 0xae8d72c57088d7ab, 0x89b94fbde542aba9, 0x3d3f9880ec47d5e0, + 0x1378a6868af3b7a0, 0x5544070beb057c94, 0x16611debc472fac4, 0xe500ffb79f5b8868, + 0x308a5e32196603b2, 0xea5fb19eb4eabc38, 0x122273ae3222b598, 0xbd1a81e7977f9898, +]; +const D_P: [u64; 16] = [ + 0x209f33f09515d7c1, 0xb4a9b37656917205, 0x276933bb07e4efb9, 0x8c14019808e00414, + 0x289f96da220711e5, 0xfbbd2923d31532fe, 0xc06b414e61c0e1e7, 0x4c23c4588488961d, + 0x4dc48ae34514759c, 0x9c786961ae3e2c35, 0x497e8d9c650688e0, 0x18bf08472612dbe5, + 0x8885fb161870ee12, 0xf21d7c1479d99d47, 0x9121d91952ffd1c7, 0xa94b528b28f29159, +]; +const D_Q: [u64; 16] = [ + 0xf7597ffb68011d8d, 0x7b3cc538c4bab8c9, 0xa8fa480a81a925af, 0x6d6ede7251a383bf, + 0x8a63f788ce3a0f85, 0x0b920502eb478bc9, 0x7e37e755edfe70d9, 0x9cf9948422a16555, + 0x0d6d9ea1f2ef71fd, 0xf7efa32ea0cb6e00, 0x0629b114ca7f780f, 0xcf51176359654348, + 0x540cdcbd4ad35435, 0x31c02ff1a2bc437c, 0xff2503df78bafed5, 0x3af0e72a933aef09, +]; +const Q_INV: [u64; 16] = [ + 0x552fe4bfce945f7b, 0x67e50c999c67247b, 0xfb54ef17be3b2853, 0x241f5921b5ad3983, + 0x02de5eccd143cf31, 0x74e45f6fcc60f216, 0xafa5428a74f12708, 0x88d42294b6a2759b, + 0xe923e1097c0c562f, 0xc968b48a91c38b5b, 0x933e85179c0320b0, 0x7993d0445f758d51, + 0x9bfc042ee0924b1b, 0x41f956d90fa8a793, 0xee7a87b6483a66ee, 0x2640fbfbcfefb163, +]; + +/// An RNG that fills the first half of what it is asked for, leaves the rest zero, and returns +/// the count it wrote, as the trait asks. `draws` counts the calls. +struct WritesHalf { + draws: usize, +} + +impl RNG for WritesHalf { + fn add_seed_keymaterial(&mut self, _: &dyn KeyMaterialTrait) -> Result<(), RNGError> { + Err(RNGError::GenericError("not seedable")) + } + fn next_int(&mut self) -> Result { + Err(RNGError::GenericError("not used")) + } + fn next_bytes_out(&mut self, out: &mut [u8]) -> Result { + self.draws += 1; + out.fill(0); + let half = out.len() / 2; + out[..half].fill(0xA5); + Ok(half) + } + fn fill_keymaterial_out(&mut self, _: &mut dyn KeyMaterialTrait) -> Result { + Err(RNGError::GenericError("not used")) + } + fn security_strength(&self) -> SecurityStrength { + SecurityStrength::_256bit + } +} + +const SHORT: RNGError = RNGError::GenericError("the RNG wrote fewer bytes than it was asked for"); + +/// Key generation stops at the first short draw, through every generator, and the Miller-Rabin +/// test does on its own. +#[test] +fn key_generation_refuses_a_short_draw() { + let mut rng = WritesHalf { draws: 0 }; + assert_eq!(RSA2048::keygen(&mut rng).unwrap_err(), SignatureError::RNGError(SHORT)); + assert_eq!(rng.draws, 1); + assert!(matches!( + RSA2048::generate_pss_signature_key_pair::(&mut WritesHalf { draws: 0 }), + Err(SignatureError::RNGError(SHORT)) + )); + assert!(matches!( + RSA2048::generate_kem_key_pair(&mut WritesHalf { draws: 0 }), + Err(KEMError::RNGError(SHORT)) + )); + // 2^127 - 1 is prime and has no factor below the trial-division bound, so the test goes + // on to draw a base. + let w = [u64::MAX, u64::MAX >> 1]; + assert_eq!( + is_probable_prime::<2, 4, 5>( + &w, + NonZeroUsize::new(5).unwrap(), + &mut WritesHalf { draws: 0 } + ), + Err(SignatureError::RNGError(SHORT)) + ); +} + +/// RSASSA-PSS draws its salt when the signer is made: no signer, and no signature from the +/// one-shot or from the hash entry point, whose output buffer stays zero. +#[test] +fn pss_signing_refuses_a_short_salt() { + let sk = + RsaPrivateComponents::::from_crt_components(&P, &Q, &D_P, &D_Q, &Q_INV, 0x10001) + .unwrap() + .into_key::(); + assert!(matches!( + sk.create_signer(&mut WritesHalf { draws: 0 }, None), + Err(SignatureError::RNGError(SHORT)) + )); + assert_eq!( + sk.sign(&mut WritesHalf { draws: 0 }, b"message", None), + Err(SignatureError::RNGError(SHORT)) + ); + let mut sig = [0xFFu8; 256]; + assert_eq!( + sk.sign_out(&mut WritesHalf { draws: 0 }, b"message", None, &mut sig), + Err(SignatureError::RNGError(SHORT)) + ); + assert_eq!(sig, [0u8; 256]); + assert_eq!( + sign_from_hash(&sk, &[0x11; 32], &mut WritesHalf { draws: 0 }), + Err(SignatureError::RNGError(SHORT)) + ); +} + +/// RSAES-OAEP draws the key to transport (as a KEM) and the seed; a short draw of either is the +/// RNG's error, with the ciphertext and the key buffer left zeroized. +#[test] +fn oaep_refuses_a_short_key_and_a_short_seed() { + let sk = + RsaPrivateComponents::::from_crt_components(&P, &Q, &D_P, &D_Q, &Q_INV, 0x10001) + .unwrap(); + let pk = RSA2048KEMPublicKey::new(sk.n(), 65537).unwrap(); + let params = OaepParams::::new(b"label"); + + // As a KEM the first draw is the key. + let mut ct = [0xFFu8; 256]; + let mut ss = KeyMaterial::<32>::from_bytes(&[0xEE; 32]).unwrap(); + let mut rng = WritesHalf { draws: 0 }; + assert_eq!(pk.encaps_out(&mut rng, params, &mut ct, &mut ss), Err(KEMError::RNGError(SHORT))); + assert_eq!(rng.draws, 1); + assert_eq!(ct, [0u8; 256]); + assert_eq!(ss.key_type(), KeyType::Zeroized); + + // Transporting a key the caller holds, the only draw is the seed. + let key = KeyMaterial::<32>::from_bytes_as_type(&[0x42; 32], KeyType::MACKey).unwrap(); + let mut ct = [0xFFu8; 256]; + let mut rng = WritesHalf { draws: 0 }; + assert_eq!( + pk.transport_out(&mut rng, params, &key, &mut ct), + Err(KeyTransportError::RNGError(SHORT)) + ); + assert_eq!(rng.draws, 1); + assert_eq!(ct, [0u8; 256]); + assert_eq!( + pk.transport(&mut WritesHalf { draws: 0 }, params, &key), + Err(KeyTransportError::RNGError(SHORT)) + ); +} + +/// RSASVE draws the secret value: a short draw is the RNG's error at once, not a value to +/// test against the range and redraw, and both buffers are left zeroized. +#[test] +fn rsasve_refuses_a_short_secret_value() { + let sk = + RsaPrivateComponents::::from_crt_components(&P, &Q, &D_P, &D_Q, &Q_INV, 0x10001) + .unwrap(); + let pk = RSA2048KEMPublicKey::new(sk.n(), 65537).unwrap(); + let mut ct = [0xFFu8; 256]; + let mut ss = KeyMaterial::<256>::from_bytes(&[0xEE; 256]).unwrap(); + let mut rng = WritesHalf { draws: 0 }; + assert_eq!(pk.encaps_out(&mut rng, (), &mut ct, &mut ss), Err(KEMError::RNGError(SHORT))); + assert_eq!(rng.draws, 1); + assert_eq!(ct, [0u8; 256]); + assert_eq!(ss.key_type(), KeyType::Zeroized); + assert!(matches!(pk.encaps(&mut WritesHalf { draws: 0 }, ()), Err(KEMError::RNGError(SHORT)))); +} diff --git a/crypto/rsa/tests/rsa_1024_tests.rs b/crypto/rsa/tests/rsa_1024_tests.rs new file mode 100644 index 000000000..ba7ff1a0f --- /dev/null +++ b/crypto/rsa/tests/rsa_1024_tests.rs @@ -0,0 +1,189 @@ +//! RSA-1024 (verification only, see `rsa_1024.rs`'s docs) against Wycheproof's +//! `rsa_pkcs1_1024_sig_gen_test.json`. Since this crate never constructs an RSA-1024 private key, +//! there is nothing to factor here: a sig-gen file's own `privateKey.modulus`/`publicExponent` +//! fields are simultaneously valid *public* key material, so each group's `(n, e)` plus its own +//! `(msg, sig)` pairs are used directly as real, independent "valid" verify vectors -- exactly +//! what `rsa_signature_*_test.json` files provide at every other size, just recovered from a +//! differently-shaped file because Wycheproof has no dedicated `rsa_signature_1024_*.json`. + +use bouncycastle_core::errors::{KeyDecodingError, SignatureError}; +use bouncycastle_core::hex::decode as hex_decode; +use bouncycastle_core::signature_key::OneShotVerifyingKey; +use bouncycastle_core::traits::PublicKey; +use bouncycastle_rsa::RSA1024; +use bouncycastle_rsa::keys::{RsaPublicComponents, RsaPublicKey}; +use bouncycastle_rsa::rsa_1024::{PK_LEN, RSASSA_PKCS1_v1_5_SHA256, RSASSA_PKCS1_v1_5_SHA384}; +use serde_json::Value; +use std::fs; +use std::path::Path; + +const TEST_DATA_PATH_RELATIVE: &str = "../../../wycheproof/testvectors_v1"; +const TEST_DATA_PATH: &str = "../wycheproof/testvectors_v1"; + +fn get_test_data(filename: &str) -> String { + for dir in [TEST_DATA_PATH_RELATIVE, TEST_DATA_PATH] { + let path = format!("{dir}/{filename}"); + if Path::new(&path).exists() { + return fs::read_to_string(path).unwrap(); + } + } + panic!( + "wycheproof not found (looked for {filename} in {TEST_DATA_PATH_RELATIVE:?} and \ + {TEST_DATA_PATH:?}); this suite requires it rather than skipping" + ); +} + +fn limbs_from_hex(hex: &str) -> [u64; L] { + let bytes_len = 8 * L; + let mut bytes = hex_decode(hex).expect("valid hex"); + if bytes.len() == bytes_len + 1 && bytes[0] == 0 { + bytes.remove(0); + } + assert_eq!(bytes.len(), bytes_len, "expected a {}-bit value", bytes_len * 8); + let mut limbs = [0u64; L]; + for i in 0..L { + let start = bytes_len - (i + 1) * 8; + limbs[i] = u64::from_be_bytes(bytes[start..start + 8].try_into().unwrap()); + } + limbs +} + +fn run_sig_gen_group_as_verify_vectors( + sha: &str, + verify: impl Fn(&RsaPublicComponents, &[u8], &[u8; 128]) -> bool, +) { + let doc: Value = + serde_json::from_str(&get_test_data("rsa_pkcs1_1024_sig_gen_test.json")).unwrap(); + let group = doc["testGroups"] + .as_array() + .unwrap() + .iter() + .find(|g| g["sha"] == sha && g["tests"].as_array().unwrap().len() == 8) + .unwrap_or_else(|| panic!("the main {sha}/1024 group")); + + let n: [u64; 16] = limbs_from_hex(group["privateKey"]["modulus"].as_str().unwrap()); + let e = + u64::from_str_radix(group["privateKey"]["publicExponent"].as_str().unwrap(), 16).unwrap(); + let pk = RsaPublicComponents::::new(&n, e).expect("group public key must be valid"); + + let mut num_tests = 0usize; + for test in group["tests"].as_array().unwrap() { + num_tests += 1; + let tc_id = test["tcId"].as_u64().unwrap(); + let msg = hex_decode(test["msg"].as_str().unwrap()).unwrap(); + let sig_bytes = hex_decode(test["sig"].as_str().unwrap()).unwrap(); + let sig: [u8; 128] = sig_bytes.try_into().expect("sig-gen signatures are always k octets"); + assert!(verify(&pk, &msg, &sig), "tcId {tc_id}: a genuine signature must verify"); + } + assert_eq!(num_tests, 8); +} + +#[test] +fn pkcs1_v1_5_sha256_accepts_genuine_sig_gen_signatures() { + run_sig_gen_group_as_verify_vectors("SHA-256", |pk, msg, sig| { + pk.key::().verify(msg, None, sig).is_ok() + }); +} + +#[test] +fn pkcs1_v1_5_sha384_accepts_genuine_sig_gen_signatures() { + run_sig_gen_group_as_verify_vectors("SHA-384", |pk, msg, sig| { + pk.key::().verify(msg, None, sig).is_ok() + }); +} + +fn run_sig_gen_group_rejects_wrong_message( + sha: &str, + verify: impl Fn(&RsaPublicComponents, &[u8], &[u8; 128]) -> bool, +) { + let doc: Value = + serde_json::from_str(&get_test_data("rsa_pkcs1_1024_sig_gen_test.json")).unwrap(); + let group = doc["testGroups"] + .as_array() + .unwrap() + .iter() + .find(|g| g["sha"] == sha && g["tests"].as_array().unwrap().len() == 8) + .unwrap(); + let n: [u64; 16] = limbs_from_hex(group["privateKey"]["modulus"].as_str().unwrap()); + let e = + u64::from_str_radix(group["privateKey"]["publicExponent"].as_str().unwrap(), 16).unwrap(); + let pk = RsaPublicComponents::::new(&n, e).unwrap(); + let test = &group["tests"][0]; + let sig_bytes = hex_decode(test["sig"].as_str().unwrap()).unwrap(); + let sig: [u8; 128] = sig_bytes.try_into().unwrap(); + assert!(!verify(&pk, b"a message this signature was not made for", &sig)); +} + +#[test] +fn pkcs1_v1_5_sha256_rejects_wrong_message() { + run_sig_gen_group_rejects_wrong_message("SHA-256", |pk, msg, sig| { + pk.key::().verify(msg, None, sig).is_ok() + }); +} + +/// Mutation testing found that PKCS#1 v1.5/SHA-384 verification had no rejection-path test of its own +/// (only `verify_sha256`'s did) -- a whole-function-body mutant that always returned `Ok(())` +/// still passed the whole suite. +#[test] +fn pkcs1_v1_5_sha384_rejects_wrong_message() { + run_sig_gen_group_rejects_wrong_message("SHA-384", |pk, msg, sig| { + pk.key::().verify(msg, None, sig).is_ok() + }); +} + +// ---- bouncycastle_core trait conformance ------------------------------------------------------ +// +// No signing role exists at this size (see `rsa_1024.rs`'s docs and its `compile_fail` doctest), so +// `core-test-framework`'s signature suite -- which needs one -- cannot run here; the +// `VerifyingKey` and `PublicKey` impls are checked directly against the same +// genuine Wycheproof material as the tests above. + +/// RFC 8017 §8.2.2 step 1 through the trait's `&[u8]` signature: a truncated genuine signature +/// is rejected for its length, never accepted. +#[test] +fn trait_verify_rejects_truncated_signature() { + run_sig_gen_group_as_verify_vectors("SHA-256", |pk, msg, sig| { + matches!( + pk.key::().verify(msg, None, &sig[..127]), + Err(SignatureError::LengthError(_)) + ) + }); +} + +#[test] +fn public_key_trait_encoding_round_trips_and_rejects_wrong_lengths() { + let doc: Value = + serde_json::from_str(&get_test_data("rsa_pkcs1_1024_sig_gen_test.json")).unwrap(); + let group = &doc["testGroups"][0]; + let n: [u64; 16] = limbs_from_hex(group["privateKey"]["modulus"].as_str().unwrap()); + let e = + u64::from_str_radix(group["privateKey"]["publicExponent"].as_str().unwrap(), 16).unwrap(); + let pk = + RsaPublicComponents::::new(&n, e).unwrap().into_key::(); + + let bytes = pk.encode(); + assert_eq!(bytes.len(), PK_LEN); + assert_eq!(RsaPublicKey::::from_bytes(&bytes).unwrap(), pk); + assert!(matches!( + RsaPublicKey::::from_bytes(&bytes[..PK_LEN - 1]), + Err(KeyDecodingError(_)) + )); + let mut too_long = bytes.to_vec(); + too_long.push(0); + assert!(matches!( + RsaPublicKey::::from_bytes(&too_long), + Err(KeyDecodingError(_)) + )); +} + +/// RFC 8017 §8.2.2 step 1 through this size's own range check: `0xff..ff` is `2^1024 - 1 >= n` +/// for any 1024-bit `n`, an out-of-range representative, reported as an invalid signature. +#[test] +fn trait_verify_reports_out_of_range_representative_as_invalid_signature() { + run_sig_gen_group_as_verify_vectors("SHA-256", |pk, msg, _sig| { + matches!( + pk.key::().verify(msg, None, &[0xffu8; 128]), + Err(SignatureError::SignatureVerificationFailed) + ) + }); +} diff --git a/crypto/rsa/tests/rsa_1536_tests.rs b/crypto/rsa/tests/rsa_1536_tests.rs new file mode 100644 index 000000000..d1f3d98c9 --- /dev/null +++ b/crypto/rsa/tests/rsa_1536_tests.rs @@ -0,0 +1,194 @@ +//! RSA-1536 (verification only, see `rsa_1536.rs`'s docs) against Wycheproof's +//! `rsa_pkcs1_1536_sig_gen_test.json`, the same way `rsa_1024_tests.rs` uses its own sig-gen file: +//! each group's `(n, e)` plus its own `(msg, sig)` pairs, used directly as real "valid" verify +//! vectors, since a sig-gen file's private key fields are simultaneously valid public key +//! material and this crate never constructs an RSA-1536 private key at all. + +use bouncycastle_core::errors::{KeyDecodingError, SignatureError}; +use bouncycastle_core::hex::decode as hex_decode; +use bouncycastle_core::signature_key::OneShotVerifyingKey; +use bouncycastle_core::traits::PublicKey; +use bouncycastle_rsa::RSA1536; +use bouncycastle_rsa::keys::{RsaPublicComponents, RsaPublicKey}; +use bouncycastle_rsa::rsa_1536::{ + PK_LEN, RSASSA_PKCS1_v1_5_SHA256, RSASSA_PKCS1_v1_5_SHA384, RSASSA_PKCS1_v1_5_SHA512, +}; +use serde_json::Value; +use std::fs; +use std::path::Path; + +const TEST_DATA_PATH_RELATIVE: &str = "../../../wycheproof/testvectors_v1"; +const TEST_DATA_PATH: &str = "../wycheproof/testvectors_v1"; + +fn get_test_data(filename: &str) -> String { + for dir in [TEST_DATA_PATH_RELATIVE, TEST_DATA_PATH] { + let path = format!("{dir}/{filename}"); + if Path::new(&path).exists() { + return fs::read_to_string(path).unwrap(); + } + } + panic!( + "wycheproof not found (looked for {filename} in {TEST_DATA_PATH_RELATIVE:?} and \ + {TEST_DATA_PATH:?}); this suite requires it rather than skipping" + ); +} + +fn limbs_from_hex(hex: &str) -> [u64; L] { + let bytes_len = 8 * L; + let mut bytes = hex_decode(hex).expect("valid hex"); + if bytes.len() == bytes_len + 1 && bytes[0] == 0 { + bytes.remove(0); + } + assert_eq!(bytes.len(), bytes_len, "expected a {}-bit value", bytes_len * 8); + let mut limbs = [0u64; L]; + for i in 0..L { + let start = bytes_len - (i + 1) * 8; + limbs[i] = u64::from_be_bytes(bytes[start..start + 8].try_into().unwrap()); + } + limbs +} + +fn run_sig_gen_group_as_verify_vectors( + sha: &str, + verify: impl Fn(&RsaPublicComponents, &[u8], &[u8; 192]) -> bool, +) { + let doc: Value = + serde_json::from_str(&get_test_data("rsa_pkcs1_1536_sig_gen_test.json")).unwrap(); + let group = doc["testGroups"] + .as_array() + .unwrap() + .iter() + .find(|g| g["sha"] == sha) + .unwrap_or_else(|| panic!("the {sha}/1536 group")); + + let n: [u64; 24] = limbs_from_hex(group["privateKey"]["modulus"].as_str().unwrap()); + let e = + u64::from_str_radix(group["privateKey"]["publicExponent"].as_str().unwrap(), 16).unwrap(); + let pk = RsaPublicComponents::::new(&n, e).expect("group public key must be valid"); + + let mut num_tests = 0usize; + for test in group["tests"].as_array().unwrap() { + num_tests += 1; + let tc_id = test["tcId"].as_u64().unwrap(); + let msg = hex_decode(test["msg"].as_str().unwrap()).unwrap(); + let sig_bytes = hex_decode(test["sig"].as_str().unwrap()).unwrap(); + let sig: [u8; 192] = sig_bytes.try_into().expect("sig-gen signatures are always k octets"); + assert!(verify(&pk, &msg, &sig), "tcId {tc_id}: a genuine signature must verify"); + } + assert_eq!(num_tests, 8); +} + +#[test] +fn pkcs1_v1_5_sha256_accepts_genuine_sig_gen_signatures() { + run_sig_gen_group_as_verify_vectors("SHA-256", |pk, msg, sig| { + pk.key::().verify(msg, None, sig).is_ok() + }); +} + +#[test] +fn pkcs1_v1_5_sha384_accepts_genuine_sig_gen_signatures() { + run_sig_gen_group_as_verify_vectors("SHA-384", |pk, msg, sig| { + pk.key::().verify(msg, None, sig).is_ok() + }); +} + +#[test] +fn pkcs1_v1_5_sha512_accepts_genuine_sig_gen_signatures() { + run_sig_gen_group_as_verify_vectors("SHA-512", |pk, msg, sig| { + pk.key::().verify(msg, None, sig).is_ok() + }); +} + +fn run_sig_gen_group_rejects_wrong_message( + sha: &str, + verify: impl Fn(&RsaPublicComponents, &[u8], &[u8; 192]) -> bool, +) { + let doc: Value = + serde_json::from_str(&get_test_data("rsa_pkcs1_1536_sig_gen_test.json")).unwrap(); + let group = doc["testGroups"].as_array().unwrap().iter().find(|g| g["sha"] == sha).unwrap(); + let n: [u64; 24] = limbs_from_hex(group["privateKey"]["modulus"].as_str().unwrap()); + let e = + u64::from_str_radix(group["privateKey"]["publicExponent"].as_str().unwrap(), 16).unwrap(); + let pk = RsaPublicComponents::::new(&n, e).unwrap(); + let test = &group["tests"][0]; + let sig_bytes = hex_decode(test["sig"].as_str().unwrap()).unwrap(); + let sig: [u8; 192] = sig_bytes.try_into().unwrap(); + assert!(!verify(&pk, b"a message this signature was not made for", &sig)); +} + +#[test] +fn pkcs1_v1_5_sha256_rejects_wrong_message() { + run_sig_gen_group_rejects_wrong_message("SHA-256", |pk, msg, sig| { + pk.key::().verify(msg, None, sig).is_ok() + }); +} + +/// Mutation testing found that PKCS#1 v1.5/SHA-384 and /SHA-512 verification had no rejection-path test of +/// their own (only `verify_sha256`'s did) -- a whole-function-body mutant that always returned +/// `Ok(())` still passed the whole suite for either. +#[test] +fn pkcs1_v1_5_sha384_rejects_wrong_message() { + run_sig_gen_group_rejects_wrong_message("SHA-384", |pk, msg, sig| { + pk.key::().verify(msg, None, sig).is_ok() + }); +} + +#[test] +fn pkcs1_v1_5_sha512_rejects_wrong_message() { + run_sig_gen_group_rejects_wrong_message("SHA-512", |pk, msg, sig| { + pk.key::().verify(msg, None, sig).is_ok() + }); +} + +// ---- bouncycastle_core trait conformance ------------------------------------------------------ +// +// Verify-only at this size, as at RSA-1024 -- see `rsa_1024_tests.rs` for why the +// `core-test-framework` signature suite cannot run here. + +#[test] +fn trait_verify_rejects_truncated_signature() { + run_sig_gen_group_as_verify_vectors("SHA-256", |pk, msg, sig| { + matches!( + pk.key::().verify(msg, None, &sig[..191]), + Err(SignatureError::LengthError(_)) + ) + }); +} + +#[test] +fn public_key_trait_encoding_round_trips_and_rejects_wrong_lengths() { + let doc: Value = + serde_json::from_str(&get_test_data("rsa_pkcs1_1536_sig_gen_test.json")).unwrap(); + let group = &doc["testGroups"][0]; + let n: [u64; 24] = limbs_from_hex(group["privateKey"]["modulus"].as_str().unwrap()); + let e = + u64::from_str_radix(group["privateKey"]["publicExponent"].as_str().unwrap(), 16).unwrap(); + let pk = + RsaPublicComponents::::new(&n, e).unwrap().into_key::(); + + let bytes = pk.encode(); + assert_eq!(bytes.len(), PK_LEN); + assert_eq!(RsaPublicKey::::from_bytes(&bytes).unwrap(), pk); + assert!(matches!( + RsaPublicKey::::from_bytes(&bytes[..PK_LEN - 1]), + Err(KeyDecodingError(_)) + )); + let mut too_long = bytes.to_vec(); + too_long.push(0); + assert!(matches!( + RsaPublicKey::::from_bytes(&too_long), + Err(KeyDecodingError(_)) + )); +} + +/// RFC 8017 §8.2.2 step 1 through this size's own range check: `0xff..ff` is `2^1536 - 1 >= n` +/// for any 1536-bit `n`, an out-of-range representative, reported as an invalid signature. +#[test] +fn trait_verify_reports_out_of_range_representative_as_invalid_signature() { + run_sig_gen_group_as_verify_vectors("SHA-256", |pk, msg, _sig| { + matches!( + pk.key::().verify(msg, None, &[0xffu8; 192]), + Err(SignatureError::SignatureVerificationFailed) + ) + }); +} diff --git a/crypto/rsa/tests/rsa_2048_pkcs1_v1_5_sha384_sha512_tests.rs b/crypto/rsa/tests/rsa_2048_pkcs1_v1_5_sha384_sha512_tests.rs new file mode 100644 index 000000000..b11385933 --- /dev/null +++ b/crypto/rsa/tests/rsa_2048_pkcs1_v1_5_sha384_sha512_tests.rs @@ -0,0 +1,232 @@ +//! RSA-2048 RSASSA-PKCS1-v1_5 with SHA-384 and SHA-512, against Wycheproof's +//! `rsa_signature_2048_sha384_test.json`/`rsa_signature_2048_sha512_test.json`. +//! +//! Each of Wycheproof's `rsa_pkcs1_2048_sig_gen_test.json` groups (including its SHA-384 and +//! SHA-512 ones) uses a *distinct* key -- unlike the SHA-256 case +//! (`rsa_2048_pkcs1_v1_5_tests.rs`), there is no shared key to recover once and reuse across +//! hashes here, and factoring another key per hash is disproportionate to what this step needs: +//! `EMSA-PKCS1-v1_5`'s DigestInfo construction is generic over the hash (see `digest_info`'s own +//! docs) and already exercised end to end for SHA-256, and RSASP1/RSAVP1 do not depend on which +//! hash produced the message representative they are given. So the sign side here is a +//! self-consistency round trip against the SHA-256 key `rsa_2048_pkcs1_v1_5_tests.rs` already +//! recovered (a valid RSA private key signs under any hash choice; nothing about the key ties it +//! to SHA-256), while the verify side -- where the real risk is a wrong OID or digest length for +//! the hash in question -- is checked against all of Wycheproof's real vectors for both hashes. + +use bouncycastle_core::errors::SignatureError; +use bouncycastle_core::hex::decode as hex_decode; +use bouncycastle_core::signature_key::{DeterministicOneShotSigningKey, OneShotVerifyingKey}; +use bouncycastle_core_test_framework::signature::{CtxBehaviour, TestFrameworkSignature}; +use bouncycastle_rsa::RSA2048; +use bouncycastle_rsa::keys::{ + RsaPrivateComponents, RsaPrivateKey, RsaPublicComponents, RsaPublicKey, +}; +use bouncycastle_rsa::rsa_2048::{RSASSA_PKCS1_v1_5_SHA384, RSASSA_PKCS1_v1_5_SHA512, SIG_LEN}; +use serde_json::Value; +use std::fs; +use std::path::Path; + +const TEST_DATA_PATH_RELATIVE: &str = "../../../wycheproof/testvectors_v1"; +const TEST_DATA_PATH: &str = "../wycheproof/testvectors_v1"; + +fn get_test_data(filename: &str) -> String { + for dir in [TEST_DATA_PATH_RELATIVE, TEST_DATA_PATH] { + let path = format!("{dir}/{filename}"); + if Path::new(&path).exists() { + return fs::read_to_string(path).unwrap(); + } + } + panic!( + "wycheproof not found (looked for {filename} in {TEST_DATA_PATH_RELATIVE:?} and \ + {TEST_DATA_PATH:?}); this suite requires it rather than skipping" + ); +} + +fn limbs_from_hex(hex: &str) -> [u64; L] { + let bytes_len = 8 * L; + let mut bytes = hex_decode(hex).expect("valid hex"); + if bytes.len() == bytes_len + 1 && bytes[0] == 0 { + bytes.remove(0); + } + assert_eq!(bytes.len(), bytes_len, "expected a {}-bit value", bytes_len * 8); + let mut limbs = [0u64; L]; + for i in 0..L { + let start = bytes_len - (i + 1) * 8; + limbs[i] = u64::from_be_bytes(bytes[start..start + 8].try_into().unwrap()); + } + limbs +} + +/// The same genuine RSA-2048 keypair `rsa_2048_pkcs1_v1_5_tests.rs` recovers (from +/// `rsa_pkcs1_2048_sig_gen_test.json`'s SHA-256 group) -- reused here as a plain, valid RSA-2048 +/// key, not because it has anything to do with SHA-256 specifically. +fn genuine_key() -> RsaPrivateComponents { + let p: [u64; 16] = [ + 0x0ea36cfb3a5b18f1, 0x48a6e65332119129, 0x110ad9e7b48a1c93, 0x569156b90113e2e9, + 0xe79813a575cfad9c, 0x69d659d143ec6f17, 0xe81e6bab5ddaa783, 0xbff1c5b80a69f788, + 0x978f6c35814f50ee, 0xe6a289ad4cfbf78f, 0x34d5681e5809d415, 0xbb028bda42eeb5d2, + 0x41c56e4de086b0d5, 0x58b8d1e24f3b55d0, 0xfb5248247d98cb7d, 0xdc431050f782e894, + ]; + let q: [u64; 16] = [ + 0x669f140cfbc20f25, 0xb97bb03677207d95, 0xfd4e06f3ed7299d4, 0x160f90536abc9492, + 0xf5b131f39098f7bc, 0xae8d72c57088d7ab, 0x89b94fbde542aba9, 0x3d3f9880ec47d5e0, + 0x1378a6868af3b7a0, 0x5544070beb057c94, 0x16611debc472fac4, 0xe500ffb79f5b8868, + 0x308a5e32196603b2, 0xea5fb19eb4eabc38, 0x122273ae3222b598, 0xbd1a81e7977f9898, + ]; + let d_p: [u64; 16] = [ + 0x209f33f09515d7c1, 0xb4a9b37656917205, 0x276933bb07e4efb9, 0x8c14019808e00414, + 0x289f96da220711e5, 0xfbbd2923d31532fe, 0xc06b414e61c0e1e7, 0x4c23c4588488961d, + 0x4dc48ae34514759c, 0x9c786961ae3e2c35, 0x497e8d9c650688e0, 0x18bf08472612dbe5, + 0x8885fb161870ee12, 0xf21d7c1479d99d47, 0x9121d91952ffd1c7, 0xa94b528b28f29159, + ]; + let d_q: [u64; 16] = [ + 0xf7597ffb68011d8d, 0x7b3cc538c4bab8c9, 0xa8fa480a81a925af, 0x6d6ede7251a383bf, + 0x8a63f788ce3a0f85, 0x0b920502eb478bc9, 0x7e37e755edfe70d9, 0x9cf9948422a16555, + 0x0d6d9ea1f2ef71fd, 0xf7efa32ea0cb6e00, 0x0629b114ca7f780f, 0xcf51176359654348, + 0x540cdcbd4ad35435, 0x31c02ff1a2bc437c, 0xff2503df78bafed5, 0x3af0e72a933aef09, + ]; + let q_inv: [u64; 16] = [ + 0x552fe4bfce945f7b, 0x67e50c999c67247b, 0xfb54ef17be3b2853, 0x241f5921b5ad3983, + 0x02de5eccd143cf31, 0x74e45f6fcc60f216, 0xafa5428a74f12708, 0x88d42294b6a2759b, + 0xe923e1097c0c562f, 0xc968b48a91c38b5b, 0x933e85179c0320b0, 0x7993d0445f758d51, + 0x9bfc042ee0924b1b, 0x41f956d90fa8a793, 0xee7a87b6483a66ee, 0x2640fbfbcfefb163, + ]; + RsaPrivateComponents::::from_crt_components(&p, &q, &d_p, &d_q, &q_inv, 0x10001) + .expect("recovered CRT components must be accepted") +} + +#[test] +fn pkcs1_v1_5_sha384_round_trips() { + let sk = genuine_key(); + let pk = RsaPublicComponents::::new(sk.n(), 0x10001).unwrap(); + let sig = sk + .key::() + .sign_deterministic(b"hello", None) + .expect("signing must succeed"); + pk.key::().verify(b"hello", None, &sig).expect("must verify"); + assert!(pk.key::().verify(b"goodbye", None, &sig).is_err()); +} + +#[test] +fn pkcs1_v1_5_sha512_round_trips() { + let sk = genuine_key(); + let pk = RsaPublicComponents::::new(sk.n(), 0x10001).unwrap(); + let sig = sk + .key::() + .sign_deterministic(b"hello", None) + .expect("signing must succeed"); + pk.key::().verify(b"hello", None, &sig).expect("must verify"); + assert!(pk.key::().verify(b"goodbye", None, &sig).is_err()); +} + +fn run_verify_vectors( + filename: &str, + verify: impl Fn(&RsaPublicComponents, &[u8], &[u8; 256]) -> bool, + expected_sha: &str, + expected_num_tests: usize, + expected_num_valid: usize, + expected_num_invalid: usize, +) { + let doc: Value = serde_json::from_str(&get_test_data(filename)).expect("valid JSON"); + + let mut num_tests = 0usize; + let mut num_valid = 0usize; + let mut num_invalid = 0usize; + let mut num_missing_null = 0usize; + + for group in doc["testGroups"].as_array().unwrap() { + assert_eq!(group["sha"], expected_sha); + let n: [u64; 32] = limbs_from_hex(group["publicKey"]["modulus"].as_str().unwrap()); + let e = u64::from_str_radix(group["publicKey"]["publicExponent"].as_str().unwrap(), 16) + .expect("publicExponent fits in u64 for every group here"); + let pk = + RsaPublicComponents::::new(&n, e).expect("group public key must be valid"); + + for test in group["tests"].as_array().unwrap() { + num_tests += 1; + let tc_id = test["tcId"].as_u64().unwrap(); + let msg = hex_decode(test["msg"].as_str().unwrap()).unwrap(); + let sig_bytes = hex_decode(test["sig"].as_str().unwrap()).unwrap(); + let flags: Vec<&str> = + test["flags"].as_array().unwrap().iter().map(|f| f.as_str().unwrap()).collect(); + + let Ok(sig): Result<[u8; 256], _> = sig_bytes.try_into() else { + assert_ne!(test["result"], "valid", "tcId {tc_id}: wrong-length 'valid' signature"); + num_invalid += 1; + continue; + }; + + let verified = verify(&pk, &msg, &sig); + match test["result"].as_str().unwrap() { + "valid" => { + assert!(verified, "tcId {tc_id}: expected valid, got invalid"); + num_valid += 1; + } + "invalid" => { + assert!(!verified, "tcId {tc_id}: expected invalid, got valid"); + num_invalid += 1; + } + "acceptable" => { + assert_eq!( + flags, + vec!["MissingNull"], + "tcId {tc_id}: unreviewed 'acceptable' flag combination {flags:?}" + ); + assert!(verified, "tcId {tc_id}: MissingNull must be accepted"); + num_missing_null += 1; + } + other => panic!("tcId {tc_id}: unknown result {other:?}"), + } + } + } + + assert_eq!(num_tests, expected_num_tests); + assert_eq!(num_missing_null, 1); + assert_eq!(num_valid, expected_num_valid); + assert_eq!(num_invalid, expected_num_invalid); +} + +#[test] +fn rsa_signature_sha384_wycheproof_vectors() { + run_verify_vectors( + "rsa_signature_2048_sha384_test.json", + |pk, msg, sig| pk.key::().verify(msg, None, sig).is_ok(), + "SHA-384", + 258, + 7, + 250, + ); +} + +#[test] +fn rsa_signature_sha512_wycheproof_vectors() { + run_verify_vectors( + "rsa_signature_2048_sha512_test.json", + |pk, msg, sig| pk.key::().verify(msg, None, sig).is_ok(), + "SHA-512", + 259, + 8, + 250, + ); +} + +// ---- bouncycastle_core trait conformance ------------------------------------------------------ + +fn fixed_keypair() +-> Result<(RsaPublicComponents, RsaPrivateComponents), SignatureError> { + let sk = genuine_key(); + let pk = RsaPublicComponents::::new(sk.n(), 0x10001)?; + Ok((pk, sk)) +} + +/// `core-test-framework`'s conformance suite for the SHA-384 and SHA-512 pairings (deterministic, +/// `ctx` ignored). The exhaustive bit-flip pass runs in `rsa_2048_pkcs1_v1_5_tests.rs`'s SHA-256 +/// suite, over the same generic code. +#[test] +fn pkcs1_v1_5_sha384_sha512_trait_conformance_suite() { + let framework = TestFrameworkSignature::with_ctx_behaviour(CtxBehaviour::Refused); + framework.test_deterministic_signature::, RsaPrivateKey, SIG_LEN>( + || fixed_keypair().map(|(pk, sk)| (pk.into_key::(), sk.into_key::())), false); + framework.test_deterministic_signature::, RsaPrivateKey, SIG_LEN>( + || fixed_keypair().map(|(pk, sk)| (pk.into_key::(), sk.into_key::())), false); +} diff --git a/crypto/rsa/tests/rsa_2048_pkcs1_v1_5_tests.rs b/crypto/rsa/tests/rsa_2048_pkcs1_v1_5_tests.rs new file mode 100644 index 000000000..aaf45bd23 --- /dev/null +++ b/crypto/rsa/tests/rsa_2048_pkcs1_v1_5_tests.rs @@ -0,0 +1,308 @@ +//! RSA-2048/SHA-256 RSASSA-PKCS1-v1_5 against Wycheproof (`rsa_pkcs1_2048_sig_gen_test.json` and +//! `rsa_signature_2048_sha256_test.json`), following the path/lookup convention +//! `bouncycastle-ecdsa`'s `tests/wycheproof.rs` documents (symlink the clone at +//! `/tmp/wycheproof` for `cargo mutants`). +//! +//! No CAVP SigGen15/SigVer15 vectors exist in this workspace's `bc-test-data` clone at the time +//! of writing (only ECDSA/KDF material does), so Wycheproof alone carries both directions here: +//! `rsa_pkcs1_2048_sig_gen_test.json` for signing (deterministic PKCS#1 v1.5 has exactly one +//! correct signature per message, same as a CAVP SigGen KAT) and `rsa_signature_2048_sha256_test.json` +//! for verification. +//! +//! # Where the private key comes from +//! +//! Wycheproof's sig-gen vectors give `(n, e, d)`, not the CRT quintuple +//! [`RsaPrivateKey::from_crt_components`] needs. `p` and `q` were recovered from `(n, e, d)` in +//! Python via the standard randomized factoring-from-the-private-exponent method (Boneh, *Twenty +//! Years of Attacks on the RSA Cryptosystem*, 1999, §I.B; originally Miller, 1975): `e*d - 1` is a +//! multiple of `λ(n)`, which a few rounds of a Miller-Rabin-shaped search turn into a nontrivial +//! square root of `1 mod n`, and `gcd(that - 1, n)` is a factor with high probability. `dP`, `dQ`, +//! `qInv` were then computed directly from `p`, `q`, `d`, `e`. The recovered CRT key was +//! cross-checked in Python against all eight of this group's vectors (CRT recombination +//! reproducing the exact `sig` bytes) before being pasted here -- this file's own tests are the +//! same check again, in Rust, against RSASSA-PKCS1-v1_5's real API. +//! +//! This factoring step lives only in the throwaway script that produced these constants, never in +//! the crate: `bouncycastle-rsa` has no prime-generation or factoring code (see `src/lib.rs`'s +//! `# Scope`), by design. +//! +//! `p` and `q` here are both genuinely 1024 bits (this key's generator produced balanced primes, +//! as most do) -- [`RsaPrivateKey`] does not require that, see its docs, but this file cannot +//! itself demonstrate the unbalanced case: it works from a real generator's output, not a +//! constructed edge case. + +use bouncycastle_core::errors::SignatureError; +use bouncycastle_core::hex::decode as hex_decode; +use bouncycastle_core::signature_key::{ + DeterministicOneShotSigningKey, DeterministicSigningKey, OneShotVerifyingKey, +}; +use bouncycastle_core::traits::{HashOneShot, SignatureSigner}; +use bouncycastle_core_test_framework::signature::{ + CtxBehaviour, TestFrameworkSignature, TestFrameworkSignatureKeys, +}; +use bouncycastle_rsa::RSA2048; +use bouncycastle_rsa::keys::{ + RsaPrivateComponents, RsaPrivateKey, RsaPublicComponents, RsaPublicKey, +}; +use bouncycastle_rsa::rsa_2048::{PK_LEN, RSASSA_PKCS1_v1_5_SHA256, SIG_LEN, SK_LEN}; +use bouncycastle_rsa::rsassa; +use bouncycastle_rsa::rsassa_pkcs1_v1_5::RSASSA_PKCS1_v1_5; +use bouncycastle_sha2::SHA256; +use serde_json::Value; +use std::fs; +use std::path::Path; + +const TEST_DATA_PATH_RELATIVE: &str = "../../../wycheproof/testvectors_v1"; +const TEST_DATA_PATH: &str = "../wycheproof/testvectors_v1"; + +fn get_test_data(filename: &str) -> String { + for dir in [TEST_DATA_PATH_RELATIVE, TEST_DATA_PATH] { + let path = format!("{dir}/{filename}"); + if Path::new(&path).exists() { + return fs::read_to_string(path).unwrap(); + } + } + panic!( + "wycheproof not found (looked for {filename} in {TEST_DATA_PATH_RELATIVE:?} and \ + {TEST_DATA_PATH:?}); this suite requires it rather than skipping" + ); +} + +/// Big-endian hex (as Wycheproof/ASN.1 write it, with an optional leading `00` sign-avoidance +/// byte) into this crate's little-endian `[u64; L]` limb form. Duplicated in miniature from +/// `bouncycastle_rsa::codec` (crate-private) rather than exposed from it: this conversion belongs +/// to the test's own data plumbing, not to the crate's public API surface. +fn limbs_from_hex(hex: &str) -> [u64; L] { + let bytes_len = 8 * L; + let mut bytes = hex_decode(hex).expect("valid hex"); + if bytes.len() == bytes_len + 1 && bytes[0] == 0 { + bytes.remove(0); + } + assert_eq!(bytes.len(), bytes_len, "expected a {}-bit value", bytes_len * 8); + let mut limbs = [0u64; L]; + for i in 0..L { + let start = bytes_len - (i + 1) * 8; + limbs[i] = u64::from_be_bytes(bytes[start..start + 8].try_into().unwrap()); + } + limbs +} + +fn wycheproof_key() -> RsaPrivateComponents { + // Little-endian [u64; 16] limbs -- P[0] is p's *least* significant 64 bits. (An earlier + // version of this file tried to write these as a single big-endian hex string by + // concatenating the limbs in array order, which silently reverses significance at each 8-byte + // boundary and produces a different, even number; `limbs_from_hex` is for genuinely + // big-endian input, such as the JSON's own hex fields, not for re-deriving these.) + let p: [u64; 16] = [ + 0x0ea36cfb3a5b18f1, 0x48a6e65332119129, 0x110ad9e7b48a1c93, 0x569156b90113e2e9, + 0xe79813a575cfad9c, 0x69d659d143ec6f17, 0xe81e6bab5ddaa783, 0xbff1c5b80a69f788, + 0x978f6c35814f50ee, 0xe6a289ad4cfbf78f, 0x34d5681e5809d415, 0xbb028bda42eeb5d2, + 0x41c56e4de086b0d5, 0x58b8d1e24f3b55d0, 0xfb5248247d98cb7d, 0xdc431050f782e894, + ]; + let q: [u64; 16] = [ + 0x669f140cfbc20f25, 0xb97bb03677207d95, 0xfd4e06f3ed7299d4, 0x160f90536abc9492, + 0xf5b131f39098f7bc, 0xae8d72c57088d7ab, 0x89b94fbde542aba9, 0x3d3f9880ec47d5e0, + 0x1378a6868af3b7a0, 0x5544070beb057c94, 0x16611debc472fac4, 0xe500ffb79f5b8868, + 0x308a5e32196603b2, 0xea5fb19eb4eabc38, 0x122273ae3222b598, 0xbd1a81e7977f9898, + ]; + let d_p: [u64; 16] = [ + 0x209f33f09515d7c1, 0xb4a9b37656917205, 0x276933bb07e4efb9, 0x8c14019808e00414, + 0x289f96da220711e5, 0xfbbd2923d31532fe, 0xc06b414e61c0e1e7, 0x4c23c4588488961d, + 0x4dc48ae34514759c, 0x9c786961ae3e2c35, 0x497e8d9c650688e0, 0x18bf08472612dbe5, + 0x8885fb161870ee12, 0xf21d7c1479d99d47, 0x9121d91952ffd1c7, 0xa94b528b28f29159, + ]; + let d_q: [u64; 16] = [ + 0xf7597ffb68011d8d, 0x7b3cc538c4bab8c9, 0xa8fa480a81a925af, 0x6d6ede7251a383bf, + 0x8a63f788ce3a0f85, 0x0b920502eb478bc9, 0x7e37e755edfe70d9, 0x9cf9948422a16555, + 0x0d6d9ea1f2ef71fd, 0xf7efa32ea0cb6e00, 0x0629b114ca7f780f, 0xcf51176359654348, + 0x540cdcbd4ad35435, 0x31c02ff1a2bc437c, 0xff2503df78bafed5, 0x3af0e72a933aef09, + ]; + let q_inv: [u64; 16] = [ + 0x552fe4bfce945f7b, 0x67e50c999c67247b, 0xfb54ef17be3b2853, 0x241f5921b5ad3983, + 0x02de5eccd143cf31, 0x74e45f6fcc60f216, 0xafa5428a74f12708, 0x88d42294b6a2759b, + 0xe923e1097c0c562f, 0xc968b48a91c38b5b, 0x933e85179c0320b0, 0x7993d0445f758d51, + 0x9bfc042ee0924b1b, 0x41f956d90fa8a793, 0xee7a87b6483a66ee, 0x2640fbfbcfefb163, + ]; + RsaPrivateComponents::::from_crt_components(&p, &q, &d_p, &d_q, &q_inv, 0x10001) + .expect("recovered CRT components must be accepted") +} + +/// The first (257-test) group of `rsa_signature_2048_sha256_test.json` uses this exact key +/// (confirmed by comparing moduli in Python before writing this file); the other two groups use +/// unrelated keys and are covered separately by [`rsa_signature_sha256_all_groups`], which parses +/// the public key straight out of each group's JSON instead. +#[test] +fn pkcs1_v1_5_sig_gen_2048_sha256() { + let sk = wycheproof_key(); + + let doc: Value = serde_json::from_str(&get_test_data("rsa_pkcs1_2048_sig_gen_test.json")) + .expect("valid JSON"); + let group = doc["testGroups"] + .as_array() + .unwrap() + .iter() + .find(|g| g["sha"] == "SHA-256" && g["tests"].as_array().unwrap().len() == 8) + .expect("the main SHA-256/2048 group"); + + let mut num_tests = 0usize; + for test in group["tests"].as_array().unwrap() { + num_tests += 1; + let tc_id = test["tcId"].as_u64().unwrap(); + let msg = hex_decode(test["msg"].as_str().unwrap()).unwrap(); + let expected_sig = hex_decode(test["sig"].as_str().unwrap()).unwrap(); + assert_eq!(test["result"], "valid", "tcId {tc_id}: sig-gen vectors are all 'valid'"); + + let sig = sk + .key::() + .sign_deterministic(&msg, None) + .unwrap_or_else(|e| { + panic!("tcId {tc_id}: signing failed: {e:?}"); + }); + assert_eq!(sig.to_vec(), expected_sig, "tcId {tc_id}: signature mismatch"); + } + assert_eq!(num_tests, 8); +} + +// ---- bouncycastle_core trait conformance ------------------------------------------------------ + +/// The same genuine key pair as the sig-gen test above, in the `fn() -> Result<(PK, SK)>` +/// shape `core-test-framework` takes in place of a key generator (this crate has none). +fn fixed_keypair() +-> Result<(RsaPublicComponents, RsaPrivateComponents), SignatureError> { + let sk = wycheproof_key(); + let pk = RsaPublicComponents::::new(sk.n(), 0x10001)?; + Ok((pk, sk)) +} + +/// The shared signature-key conformance suite (per QUALITY_AND_STYLE's rule that +/// trait conformance lives in `core-test-framework`, not per implementation): deterministic +/// (PKCS#1 v1.5 has no randomness), `ctx` ignored (RSA has no context input), and with every bit +/// of a signature flipped in turn -- 2048 verifications, run at this size and scheme since the +/// generic `RSASSA_PKCS1_v1_5` code under test is the same at every width. +#[test] +fn pkcs1_v1_5_sha256_trait_conformance_suite() { + TestFrameworkSignature::with_ctx_behaviour(CtxBehaviour::Refused).test_deterministic_signature::, RsaPrivateKey, SIG_LEN>( + || fixed_keypair().map(|(pk, sk)| (pk.into_key::(), sk.into_key::())), true); +} + +#[test] +fn key_trait_boundary_conditions() { + TestFrameworkSignatureKeys::new() + .test_keys::, RsaPrivateKey, PK_LEN, SK_LEN>( + || fixed_keypair().map(|(pk, sk)| (pk.into_key::(), sk.into_key::())), + ); +} + +/// Streamed and one-shot signing are one computation: PKCS#1 v1.5 is deterministic, so the +/// chunked `create_signer_deterministic`/`do_update`/`do_final` path reproduces `sign_deterministic` byte for byte. +#[test] +fn streamed_signature_equals_one_shot() { + let (pk, sk) = fixed_keypair().unwrap(); + let msg = b"the same message, two ways"; + let one_shot = sk.key::().sign_deterministic(msg, None).unwrap(); + let sk_rsassa_pkcs1_v1_5_sha256 = sk.key::(); + + let mut signer = sk_rsassa_pkcs1_v1_5_sha256.create_signer_deterministic(None).unwrap(); + signer.do_update(&msg[..10]); + signer.do_update(&msg[10..]); + let streamed = signer.do_final().unwrap(); + assert_eq!(streamed, one_shot); + pk.key::().verify(msg, None, &streamed).unwrap(); +} + +/// RFC 8017 §8.2.2 step 1 ("If the length of the signature S is not k octets, output 'invalid +/// signature'"): the trait's `&[u8]` signature makes this a runtime check, reported as a +/// `LengthError` as the other signature crates do. `core-test-framework` covers the too-long +/// case; this is the too-short one. +#[test] +fn trait_verify_rejects_short_signature() { + let (pk, sk) = fixed_keypair().unwrap(); + let sig = sk.key::().sign_deterministic(b"msg", None).unwrap(); + assert!(matches!( + pk.key::().verify(b"msg", None, &sig[..SIG_LEN - 1]), + Err(SignatureError::LengthError(_)) + )); + assert!(matches!( + pk.key::().verify(b"msg", None, &[]), + Err(SignatureError::LengthError(_)) + )); +} + +/// One type serves both trait roles; finishing a state with the other role's `_final` is a +/// `GenericError`, not a silent wrong answer. +#[test] +fn rsa_signature_sha256_all_groups() { + let doc: Value = serde_json::from_str(&get_test_data("rsa_signature_2048_sha256_test.json")) + .expect("valid JSON"); + + let mut num_tests = 0usize; + let mut num_valid = 0usize; + let mut num_invalid = 0usize; + let mut num_wrong_length = 0usize; + + for group in doc["testGroups"].as_array().unwrap() { + let n: [u64; 32] = limbs_from_hex(group["publicKey"]["modulus"].as_str().unwrap()); + let e = u64::from_str_radix(group["publicKey"]["publicExponent"].as_str().unwrap(), 16) + .unwrap(); + let pk = RsaPublicComponents::::new(&n, e).unwrap(); + + for test in group["tests"].as_array().unwrap() { + num_tests += 1; + let tc_id = test["tcId"].as_u64().unwrap(); + let msg = hex_decode(test["msg"].as_str().unwrap()).unwrap(); + let sig = hex_decode(test["sig"].as_str().unwrap()).unwrap(); + let result = pk.key::().verify(&msg, None, &sig); + match test["result"].as_str().unwrap() { + // "acceptable" is only ever MissingNull in this file, accepted by policy (see above). + "valid" | "acceptable" => { + result.unwrap_or_else(|e| panic!("tcId {tc_id}: expected valid, got {e:?}")); + num_valid += 1; + } + "invalid" => { + assert!(result.is_err(), "tcId {tc_id}: expected invalid, got valid"); + if sig.len() != SIG_LEN { + assert!( + matches!(result, Err(SignatureError::LengthError(_))), + "tcId {tc_id}: a {}-byte signature must fail step 1's length check \ + as a LengthError, got {result:?}", + sig.len() + ); + num_wrong_length += 1; + } + num_invalid += 1; + } + other => panic!("tcId {tc_id}: unknown result {other:?}"), + } + } + } + + assert_eq!(num_tests, 259); + assert_eq!(num_valid, 10); + assert_eq!(num_invalid, 249); + assert!(num_wrong_length > 0, "the file must contain wrong-length signatures to exercise"); +} + +/// RFC 8017 §8.2.2 step 2.b: RSAVP1's "signature representative out of range" is "invalid +/// signature" through the trait (whose contract, like the RFC's, has one answer for every way a +/// signature can fail), while the generic `rsassa_pkcs1_v1_5::verify_from_hash` deliberately +/// surfaces RSAVP1's own `DecodingError` so vector-driven callers can tell malformed from wrong +/// -- see its docs. `0xff..ff` is `2^2048 - 1 >= n` for any 2048-bit `n`. +#[test] +fn trait_verify_reports_out_of_range_representative_as_invalid_signature() { + let (pk, _) = fixed_keypair().unwrap(); + let too_big = [0xffu8; SIG_LEN]; + let mut digest = [0u8; 32]; + SHA256::hash_out(b"msg", &mut digest); + assert!(matches!( + rsassa::verify_from_hash::, SIG_LEN>( + &pk.key::>(), + &digest, + &too_big + ), + Err(SignatureError::DecodingError(_)) + )); + assert!(matches!( + pk.key::().verify(b"msg", None, &too_big), + Err(SignatureError::SignatureVerificationFailed) + )); +} diff --git a/crypto/rsa/tests/rsa_2048_pss_params_tests.rs b/crypto/rsa/tests/rsa_2048_pss_params_tests.rs new file mode 100644 index 000000000..169029a69 --- /dev/null +++ b/crypto/rsa/tests/rsa_2048_pss_params_tests.rs @@ -0,0 +1,310 @@ +//! RSASSA-PSS under spelled parameters, the forms RFC 8017 allows beyond the conventional +//! pairing: MGF1 over a hash other than the message hash with a shorter salt +//! (`Mgf1` under SHA-512, Wycheproof's `rsa_pss_2048_sha512_mgf1sha256_32_params`), +//! and no salt at all (`NoSalt`, Wycheproof's `rsa_pss_2048_sha256_mgf1_0`), which is +//! deterministic and so signs through `DeterministicSigningKey`. A key is for one set of +//! parameters, so the other set's signatures are invalid under it. + +use bouncycastle_core::hazmat::WithoutCollisionResistance; +use bouncycastle_core::hex::decode as hex_decode; +use bouncycastle_core::security_strength::SecurityStrength; +use bouncycastle_core::signature_key::{ + DeterministicOneShotSigningKey, DeterministicSigningKey, OneShotSigningKey, + OneShotVerifyingKey, SigningKey, +}; +use bouncycastle_core::traits::{Algorithm, AlgorithmInfo, SignatureSigner, XOF}; +use bouncycastle_digest::sha1::SHA1; +use bouncycastle_rng::DefaultRNG; +use bouncycastle_rsa::RSA2048; +use bouncycastle_rsa::keys::{RsaPrivateComponents, RsaPublicComponents}; +use bouncycastle_rsa::rsa_2048::RSASSA_PSS_SHA256; +use bouncycastle_rsa::rsassa::RsaSignatureAlgorithm; +use bouncycastle_rsa::rsassa_pkcs1_v1_5::RSASSA_PKCS1_v1_5; +use bouncycastle_rsa::rsassa_pss::{Conventional, Mgf1, NoSalt, PssHash, RSASSA_PSS}; +use bouncycastle_rsa::size::{RsaSize, SignatureKeyPair}; +use bouncycastle_rsa::{RSA3072, RSA8192}; +use bouncycastle_sha2::{SHA224, SHA256, SHA512}; +use bouncycastle_sha3::{SHA3_256, SHAKE128, SHAKE256}; +use serde_json::Value; +use std::fs; +use std::path::Path; + +const TEST_DATA_PATH_RELATIVE: &str = "../../../wycheproof/testvectors_v1"; +const TEST_DATA_PATH: &str = "../wycheproof/testvectors_v1"; + +fn get_test_data(filename: &str) -> String { + for dir in [TEST_DATA_PATH_RELATIVE, TEST_DATA_PATH] { + let path = format!("{dir}/{filename}"); + if Path::new(&path).exists() { + return fs::read_to_string(path).unwrap(); + } + } + panic!( + "wycheproof not found (looked for {filename} in {TEST_DATA_PATH_RELATIVE:?} and \ + {TEST_DATA_PATH:?}); this suite requires it rather than skipping" + ); +} + +fn limbs_from_hex(hex: &str) -> [u64; L] { + let bytes_len = 8 * L; + let mut bytes = hex_decode(hex).expect("valid hex"); + if bytes.len() == bytes_len + 1 && bytes[0] == 0 { + bytes.remove(0); + } + assert_eq!(bytes.len(), bytes_len, "expected a {}-bit value", bytes_len * 8); + let mut limbs = [0u64; L]; + for i in 0..L { + let start = bytes_len - (i + 1) * 8; + limbs[i] = u64::from_be_bytes(bytes[start..start + 8].try_into().unwrap()); + } + limbs +} + +/// The same genuine RSA-2048 keypair `rsa_2048_pkcs1_v1_5_tests.rs` recovers from +/// `rsa_pkcs1_2048_sig_gen_test.json` -- see that file for the full, sourced provenance (p/q +/// recovered from Wycheproof's own `(n, e, d)` via the standard factoring-from-d method). + +/// One Wycheproof RSASSA-PSS verify file under the key type `A`, checking every vector's +/// verdict and the counts (valid, invalid). +fn wycheproof>( + file: &str, + sha: &str, + mgf_sha: &str, + s_len: u64, + expected: (usize, usize, usize), +) { + let doc: Value = serde_json::from_str(&get_test_data(file)).expect("valid JSON"); + let (mut num_tests, mut num_valid, mut num_invalid) = (0usize, 0usize, 0usize); + for group in doc["testGroups"].as_array().unwrap() { + assert_eq!(group["sha"], sha); + assert_eq!(group["mgfSha"], mgf_sha); + assert_eq!(group["sLen"], s_len); + let n: [u64; 32] = limbs_from_hex(group["publicKey"]["modulus"].as_str().unwrap()); + let e = u64::from_str_radix(group["publicKey"]["publicExponent"].as_str().unwrap(), 16) + .unwrap(); + let pk = RsaPublicComponents::::new(&n, e).unwrap().into_key::(); + for test in group["tests"].as_array().unwrap() { + num_tests += 1; + let tc_id = test["tcId"].as_u64().unwrap(); + let msg = hex_decode(test["msg"].as_str().unwrap()).unwrap(); + let sig = hex_decode(test["sig"].as_str().unwrap()).unwrap(); + let verified = pk.verify(&msg, None, &sig).is_ok(); + match test["result"].as_str().unwrap() { + "valid" => { + assert!(verified, "tcId {tc_id}: expected valid, got invalid"); + num_valid += 1; + } + "invalid" => { + assert!(!verified, "tcId {tc_id}: expected invalid, got valid"); + num_invalid += 1; + } + other => panic!("tcId {tc_id}: unknown result {other:?}"), + } + } + } + assert_eq!((num_tests, num_valid, num_invalid), expected); +} + +/// SHA-512 as the message hash, MGF1 over SHA-256 and a 32-byte salt: the parameters the +/// RSASSA-PSS-params structure of RFC 8017 Appendix A.2.3 can carry, which §8.1 allows. +#[test] +fn sha512_with_mgf1_sha256_and_a_32_byte_salt_wycheproof_vectors() { + wycheproof::>>( + "rsa_pss_2048_sha512_mgf1sha256_32_params_test.json", + "SHA-512", + "SHA-256", + 32, + (178, 132, 46), + ); +} + +/// The zero salt of RFC 8017 §9.1 note 4. +#[test] +fn sha256_with_no_salt_wycheproof_vectors() { + wycheproof::>>( + "rsa_pss_2048_sha256_mgf1_0_test.json", + "SHA-256", + "SHA-256", + 0, + (103, 61, 42), + ); +} + +/// SHA-1 throughout: a signature over it is still verified. +#[test] +fn sha1_wycheproof_vectors_verify() { + wycheproof::>>( + "rsa_pss_2048_sha1_mgf1_20_test.json", + "SHA-1", + "SHA-1", + 20, + (88, 42, 46), + ); +} + +#[test] +fn names_and_strengths() { + assert_eq!(RSASSA_PSS::::ALG_NAME, "RSASSA-PSS-SHA256"); + assert_eq!(RSASSA_PSS::::ALG_NAME, "RSASSA-PSS-SHA256"); + assert_eq!(RSASSA_PSS::::ALG_NAME, "RSASSA-PSS-SHAKE128"); + assert_eq!( + RSASSA_PSS::>::ALG_NAME, + "RSASSA-PSS-SHA512-MGF1-SHA256-32" + ); + assert_eq!( + RSASSA_PSS::>::ALG_NAME, + "RSASSA-PSS-SHA256-MGF1-SHA256-0" + ); + // The lesser of the size's and the hash's; the mask's hash does not enter (RFC 8017 §8.1). + assert_eq!(RSA2048::STRENGTH, SecurityStrength::_112bit); + assert_eq!(RSASSA_PSS::::MAX_SECURITY_STRENGTH, SecurityStrength::_112bit); + assert_eq!(RSASSA_PSS::::MAX_SECURITY_STRENGTH, SecurityStrength::_112bit); + assert_eq!(RSASSA_PSS::::MAX_SECURITY_STRENGTH, RSA3072::STRENGTH); + assert_eq!( + RSASSA_PSS::>::MAX_SECURITY_STRENGTH, + RSASSA_PSS::::MAX_SECURITY_STRENGTH + ); +} + +/// Each hash family's conventional mask and salt length: MGF1 output for SHA-2 and SHA-3, +/// which differs by hash and is never the seed or zero; the XOF itself for SHAKE. +#[test] +fn pss_hash_conventional_mask_and_salt_length_per_family() { + let seed = [0x5au8; 32]; + let mut sha256 = [0u8; 48]; + let mut sha512 = [0u8; 48]; + let mut sha3 = [0u8; 48]; + ::mask(&seed, &mut sha256); + ::mask(&seed, &mut sha512); + ::mask(&seed, &mut sha3); + assert_ne!(sha256, [0u8; 48]); + assert_ne!(sha512, [0u8; 48]); + assert_ne!(sha3, [0u8; 48]); + assert_ne!(sha256, sha512); + assert_ne!(sha256, sha3); + assert_ne!(sha512, sha3); + assert_ne!(&sha256[..32], &seed); + assert_eq!(::SALT_LEN, 28); + assert_eq!(::SALT_LEN, 64); + assert_eq!(::SALT_LEN, 32); + + let mut shake = [0u8; 48]; + let mut xof = [0u8; 48]; + ::mask(&seed, &mut shake); + SHAKE256::default().xof_out(&seed, &mut xof); + assert_ne!(shake, [0u8; 48]); + assert_eq!(shake, xof); + assert_eq!(::SALT_LEN, 32); + assert_eq!(::SALT_LEN, 64); +} + +// The crate docs' example key (Wycheproof's rsa_pkcs1_2048_sig_gen_test.json first SHA-256 group). +const P: [u64; 16] = [ + 0x0ea36cfb3a5b18f1, 0x48a6e65332119129, 0x110ad9e7b48a1c93, 0x569156b90113e2e9, + 0xe79813a575cfad9c, 0x69d659d143ec6f17, 0xe81e6bab5ddaa783, 0xbff1c5b80a69f788, + 0x978f6c35814f50ee, 0xe6a289ad4cfbf78f, 0x34d5681e5809d415, 0xbb028bda42eeb5d2, + 0x41c56e4de086b0d5, 0x58b8d1e24f3b55d0, 0xfb5248247d98cb7d, 0xdc431050f782e894, +]; +const Q: [u64; 16] = [ + 0x669f140cfbc20f25, 0xb97bb03677207d95, 0xfd4e06f3ed7299d4, 0x160f90536abc9492, + 0xf5b131f39098f7bc, 0xae8d72c57088d7ab, 0x89b94fbde542aba9, 0x3d3f9880ec47d5e0, + 0x1378a6868af3b7a0, 0x5544070beb057c94, 0x16611debc472fac4, 0xe500ffb79f5b8868, + 0x308a5e32196603b2, 0xea5fb19eb4eabc38, 0x122273ae3222b598, 0xbd1a81e7977f9898, +]; +const D_P: [u64; 16] = [ + 0x209f33f09515d7c1, 0xb4a9b37656917205, 0x276933bb07e4efb9, 0x8c14019808e00414, + 0x289f96da220711e5, 0xfbbd2923d31532fe, 0xc06b414e61c0e1e7, 0x4c23c4588488961d, + 0x4dc48ae34514759c, 0x9c786961ae3e2c35, 0x497e8d9c650688e0, 0x18bf08472612dbe5, + 0x8885fb161870ee12, 0xf21d7c1479d99d47, 0x9121d91952ffd1c7, 0xa94b528b28f29159, +]; +const D_Q: [u64; 16] = [ + 0xf7597ffb68011d8d, 0x7b3cc538c4bab8c9, 0xa8fa480a81a925af, 0x6d6ede7251a383bf, + 0x8a63f788ce3a0f85, 0x0b920502eb478bc9, 0x7e37e755edfe70d9, 0x9cf9948422a16555, + 0x0d6d9ea1f2ef71fd, 0xf7efa32ea0cb6e00, 0x0629b114ca7f780f, 0xcf51176359654348, + 0x540cdcbd4ad35435, 0x31c02ff1a2bc437c, 0xff2503df78bafed5, 0x3af0e72a933aef09, +]; +const Q_INV: [u64; 16] = [ + 0x552fe4bfce945f7b, 0x67e50c999c67247b, 0xfb54ef17be3b2853, 0x241f5921b5ad3983, + 0x02de5eccd143cf31, 0x74e45f6fcc60f216, 0xafa5428a74f12708, 0x88d42294b6a2759b, + 0xe923e1097c0c562f, 0xc968b48a91c38b5b, 0x933e85179c0320b0, 0x7993d0445f758d51, + 0x9bfc042ee0924b1b, 0x41f956d90fa8a793, 0xee7a87b6483a66ee, 0x2640fbfbcfefb163, +]; + +/// No salt signs through the deterministic role and reproduces; a key under other parameters +/// rejects what it did not make; a spelled salt length is drawn and pinned at that length; the +/// generator with spelled parameters gives the spelled type. +#[test] +fn no_salt_is_deterministic_and_parameters_do_not_mix() { + let sk = + RsaPrivateComponents::::from_crt_components(&P, &Q, &D_P, &D_Q, &Q_INV, 0x10001) + .unwrap(); + let pk = RsaPublicComponents::::new(sk.n(), 0x10001).unwrap(); + let msg = b"the message to sign"; + + let sk_none = sk.key::>>(); + let pk_none = pk.key::>>(); + let a = sk_none.sign_deterministic(msg, None).unwrap(); + let b = sk_none.sign_deterministic(msg, None).unwrap(); + assert_eq!(a, b, "no salt, no randomness"); + pk_none.verify(msg, None, &a).unwrap(); + let mut signer = sk_none.create_signer_deterministic(None).unwrap(); + assert_eq!(signer.alg_name(), "RSASSA-PSS-SHA256-MGF1-SHA256-0"); + signer.do_update(msg); + assert_eq!(signer.do_final().unwrap(), a); + + let sk_conv = sk.key::(); + let pk_conv = pk.key::(); + let c = sk_conv.sign(&mut DefaultRNG::default(), msg, None).unwrap(); + assert!(pk_conv.verify(msg, None, &a).is_err()); + assert!(pk_none.verify(msg, None, &c).is_err()); + let pk_16 = pk.key::>>(); + assert!(pk_16.verify(msg, None, &a).is_err()); + assert!(pk_16.verify(msg, None, &c).is_err()); + + let sk_16 = sk.key::>>(); + let mut signer = sk_16.create_signer(&mut DefaultRNG::default(), None).unwrap(); + signer.set_salt([0x42u8; 16]); + signer.do_update(msg); + let d = signer.do_final().unwrap(); + pk_16.verify(msg, None, &d).unwrap(); + let mut signer = sk_16.create_signer(&mut DefaultRNG::default(), None).unwrap(); + signer.set_salt([0x42u8; 16]); + signer.do_update(msg); + assert_eq!(signer.do_final().unwrap(), d); + assert!(pk_conv.verify(msg, None, &d).is_err()); + + let (pk_g, sk_g) = RSA2048::generate_pss_signature_key_pair_with::>( + &mut DefaultRNG::default(), + ) + .unwrap(); + let e = sk_g.sign_deterministic(msg, None).unwrap(); + assert_eq!(e, sk_g.sign_deterministic(msg, None).unwrap()); + pk_g.verify(msg, None, &e).unwrap(); +} + +/// A key over SHA-1 does not sign (the `compile_fail` examples on the algorithm types); one over +/// `WithoutCollisionResistance` does, and it is the same algorithm: the key over the bare +/// hash verifies what it made, under PKCS#1 v1.5 and under PSS, salted and not. +#[test] +fn sha1_signs_only_through_the_hazmat_wrapper() { + type Sha1 = WithoutCollisionResistance; + let sk = + RsaPrivateComponents::::from_crt_components(&P, &Q, &D_P, &D_Q, &Q_INV, 0x10001) + .unwrap(); + let pk = RsaPublicComponents::::new(sk.n(), 0x10001).unwrap(); + let msg = b"the message to sign"; + + let signer = sk.key::>(); + assert_eq!( as Algorithm>::ALG_NAME, "RSASSA-PKCS1-v1_5-SHA1"); + let sig = signer.sign_deterministic(msg, None).unwrap(); + pk.key::>().verify(msg, None, &sig).unwrap(); + assert!(pk.key::>().verify(msg, None, &sig).is_err()); + + let signer = sk.key::>>(); + let sig = signer.sign(&mut DefaultRNG::default(), msg, None).unwrap(); + pk.key::>>().verify(msg, None, &sig).unwrap(); + + let signer = sk.key::>>(); + let sig = signer.sign_deterministic(msg, None).unwrap(); + pk.key::>>().verify(msg, None, &sig).unwrap(); +} diff --git a/crypto/rsa/tests/rsa_2048_pss_sha384_sha512_tests.rs b/crypto/rsa/tests/rsa_2048_pss_sha384_sha512_tests.rs new file mode 100644 index 000000000..501e1cc9a --- /dev/null +++ b/crypto/rsa/tests/rsa_2048_pss_sha384_sha512_tests.rs @@ -0,0 +1,253 @@ +//! RSA-2048 RSASSA-PSS with SHA-384 and SHA-512, against Wycheproof's +//! `rsa_pss_2048_sha384_mgf1_48_test.json` for SHA-384. No matching-hash-and-MGF SHA-512 PSS +//! vector file exists in this Wycheproof checkout (only the SHA-512/224 and SHA-512/256 variants, +//! and a mixed SHA-512-hash/MGF1-SHA-256 "params" file, neither of which this crate's SHA-512 +//! wiring is), so SHA-512 is covered by self-consistency round trips only, the same as SHA-384's +//! sign side -- see `rsa_2048_pkcs1_v1_5_sha384_sha512_tests.rs` for why reusing the SHA-256 +//! sig-gen key here (rather than factoring a fresh one) is the right tradeoff. + +use bouncycastle_core::errors::SignatureError; +use bouncycastle_core::hex::decode as hex_decode; +use bouncycastle_core::signature_key::{OneShotSigningKey, OneShotVerifyingKey, SigningKey}; +use bouncycastle_core::traits::SignatureSigner; +use bouncycastle_core_test_framework::signature::{CtxBehaviour, TestFrameworkSignature}; +use bouncycastle_rng::DefaultRNG; +use bouncycastle_rsa::RSA2048; +use bouncycastle_rsa::keys::{ + RsaPrivateComponents, RsaPrivateKey, RsaPublicComponents, RsaPublicKey, +}; +use bouncycastle_rsa::rsa_2048::{RSASSA_PSS_SHA384, RSASSA_PSS_SHA512, SIG_LEN}; +use serde_json::Value; +use std::fs; +use std::path::Path; + +/// Signs through the streaming trait path with a fixed salt (`set_salt`) -- the +/// deterministic PSS mode, for tests against a known salt. Returns `do_sign_final`'s `Result`. +macro_rules! sign_with_salt { + ($ty:ty, $sk:expr, $msg:expr, $salt:expr) => {{ + let sk_typed_ty = $sk.key::<$ty>(); + let mut signer = sk_typed_ty.create_signer(&mut DefaultRNG::default(), None).unwrap(); + signer.set_salt($salt); + signer.do_update($msg); + signer.do_final() + }}; +} + +const TEST_DATA_PATH_RELATIVE: &str = "../../../wycheproof/testvectors_v1"; +const TEST_DATA_PATH: &str = "../wycheproof/testvectors_v1"; + +fn get_test_data(filename: &str) -> String { + for dir in [TEST_DATA_PATH_RELATIVE, TEST_DATA_PATH] { + let path = format!("{dir}/{filename}"); + if Path::new(&path).exists() { + return fs::read_to_string(path).unwrap(); + } + } + panic!( + "wycheproof not found (looked for {filename} in {TEST_DATA_PATH_RELATIVE:?} and \ + {TEST_DATA_PATH:?}); this suite requires it rather than skipping" + ); +} + +fn limbs_from_hex(hex: &str) -> [u64; L] { + let bytes_len = 8 * L; + let mut bytes = hex_decode(hex).expect("valid hex"); + if bytes.len() == bytes_len + 1 && bytes[0] == 0 { + bytes.remove(0); + } + assert_eq!(bytes.len(), bytes_len, "expected a {}-bit value", bytes_len * 8); + let mut limbs = [0u64; L]; + for i in 0..L { + let start = bytes_len - (i + 1) * 8; + limbs[i] = u64::from_be_bytes(bytes[start..start + 8].try_into().unwrap()); + } + limbs +} + +/// The same genuine RSA-2048 keypair used throughout this crate's other test files -- see +/// `rsa_2048_pkcs1_v1_5_tests.rs` for the full, sourced provenance. +fn genuine_key() -> RsaPrivateComponents { + let p: [u64; 16] = [ + 0x0ea36cfb3a5b18f1, 0x48a6e65332119129, 0x110ad9e7b48a1c93, 0x569156b90113e2e9, + 0xe79813a575cfad9c, 0x69d659d143ec6f17, 0xe81e6bab5ddaa783, 0xbff1c5b80a69f788, + 0x978f6c35814f50ee, 0xe6a289ad4cfbf78f, 0x34d5681e5809d415, 0xbb028bda42eeb5d2, + 0x41c56e4de086b0d5, 0x58b8d1e24f3b55d0, 0xfb5248247d98cb7d, 0xdc431050f782e894, + ]; + let q: [u64; 16] = [ + 0x669f140cfbc20f25, 0xb97bb03677207d95, 0xfd4e06f3ed7299d4, 0x160f90536abc9492, + 0xf5b131f39098f7bc, 0xae8d72c57088d7ab, 0x89b94fbde542aba9, 0x3d3f9880ec47d5e0, + 0x1378a6868af3b7a0, 0x5544070beb057c94, 0x16611debc472fac4, 0xe500ffb79f5b8868, + 0x308a5e32196603b2, 0xea5fb19eb4eabc38, 0x122273ae3222b598, 0xbd1a81e7977f9898, + ]; + let d_p: [u64; 16] = [ + 0x209f33f09515d7c1, 0xb4a9b37656917205, 0x276933bb07e4efb9, 0x8c14019808e00414, + 0x289f96da220711e5, 0xfbbd2923d31532fe, 0xc06b414e61c0e1e7, 0x4c23c4588488961d, + 0x4dc48ae34514759c, 0x9c786961ae3e2c35, 0x497e8d9c650688e0, 0x18bf08472612dbe5, + 0x8885fb161870ee12, 0xf21d7c1479d99d47, 0x9121d91952ffd1c7, 0xa94b528b28f29159, + ]; + let d_q: [u64; 16] = [ + 0xf7597ffb68011d8d, 0x7b3cc538c4bab8c9, 0xa8fa480a81a925af, 0x6d6ede7251a383bf, + 0x8a63f788ce3a0f85, 0x0b920502eb478bc9, 0x7e37e755edfe70d9, 0x9cf9948422a16555, + 0x0d6d9ea1f2ef71fd, 0xf7efa32ea0cb6e00, 0x0629b114ca7f780f, 0xcf51176359654348, + 0x540cdcbd4ad35435, 0x31c02ff1a2bc437c, 0xff2503df78bafed5, 0x3af0e72a933aef09, + ]; + let q_inv: [u64; 16] = [ + 0x552fe4bfce945f7b, 0x67e50c999c67247b, 0xfb54ef17be3b2853, 0x241f5921b5ad3983, + 0x02de5eccd143cf31, 0x74e45f6fcc60f216, 0xafa5428a74f12708, 0x88d42294b6a2759b, + 0xe923e1097c0c562f, 0xc968b48a91c38b5b, 0x933e85179c0320b0, 0x7993d0445f758d51, + 0x9bfc042ee0924b1b, 0x41f956d90fa8a793, 0xee7a87b6483a66ee, 0x2640fbfbcfefb163, + ]; + RsaPrivateComponents::::from_crt_components(&p, &q, &d_p, &d_q, &q_inv, 0x10001) + .expect("recovered CRT components must be accepted") +} + +#[test] +fn pss_sha384_fixed_salt_round_trips() { + let sk = genuine_key(); + let pk = RsaPublicComponents::::new(sk.n(), 0x10001).unwrap(); + let salt = [0x42u8; 48]; + let sig = + sign_with_salt!(RSASSA_PSS_SHA384, &sk, b"hello", salt).expect("signing must succeed"); + pk.key::().verify(b"hello", None, &sig).expect("must verify"); + assert!(pk.key::().verify(b"goodbye", None, &sig).is_err()); +} + +#[test] +fn pss_sha384_rng_produces_fresh_salts_that_both_verify() { + let sk = genuine_key(); + let pk = RsaPublicComponents::::new(sk.n(), 0x10001).unwrap(); + let mut rng = DefaultRNG::default(); + let sig_a = + sk.key::().sign(&mut rng, b"hello", None).expect("signing must succeed"); + let sig_b = + sk.key::().sign(&mut rng, b"hello", None).expect("signing must succeed"); + assert_ne!(sig_a, sig_b); + pk.key::().verify(b"hello", None, &sig_a).expect("sig_a must verify"); + pk.key::().verify(b"hello", None, &sig_b).expect("sig_b must verify"); +} + +#[test] +fn pss_sha512_fixed_salt_round_trips() { + let sk = genuine_key(); + let pk = RsaPublicComponents::::new(sk.n(), 0x10001).unwrap(); + let salt = [0x42u8; 64]; + let sig = + sign_with_salt!(RSASSA_PSS_SHA512, &sk, b"hello", salt).expect("signing must succeed"); + pk.key::().verify(b"hello", None, &sig).expect("must verify"); + assert!(pk.key::().verify(b"goodbye", None, &sig).is_err()); +} + +#[test] +fn pss_sha512_rng_produces_fresh_salts_that_both_verify() { + let sk = genuine_key(); + let pk = RsaPublicComponents::::new(sk.n(), 0x10001).unwrap(); + let mut rng = DefaultRNG::default(); + let sig_a = + sk.key::().sign(&mut rng, b"hello", None).expect("signing must succeed"); + let sig_b = + sk.key::().sign(&mut rng, b"hello", None).expect("signing must succeed"); + assert_ne!(sig_a, sig_b); + pk.key::().verify(b"hello", None, &sig_a).expect("sig_a must verify"); + pk.key::().verify(b"hello", None, &sig_b).expect("sig_b must verify"); +} + +#[test] +fn rsa_pss_sha384_mgf1_48_wycheproof_vectors() { + let doc: Value = serde_json::from_str(&get_test_data("rsa_pss_2048_sha384_mgf1_48_test.json")) + .expect("valid JSON"); + + let mut num_tests = 0usize; + let mut num_valid = 0usize; + let mut num_invalid = 0usize; + + for group in doc["testGroups"].as_array().unwrap() { + assert_eq!(group["sha"], "SHA-384"); + assert_eq!(group["mgfSha"], "SHA-384"); + assert_eq!(group["sLen"], 48); + let n: [u64; 32] = limbs_from_hex(group["publicKey"]["modulus"].as_str().unwrap()); + let e = u64::from_str_radix(group["publicKey"]["publicExponent"].as_str().unwrap(), 16) + .expect("publicExponent fits in u64 for every group here"); + let pk = + RsaPublicComponents::::new(&n, e).expect("group public key must be valid"); + + for test in group["tests"].as_array().unwrap() { + num_tests += 1; + let tc_id = test["tcId"].as_u64().unwrap(); + let msg = hex_decode(test["msg"].as_str().unwrap()).unwrap(); + let sig_bytes = hex_decode(test["sig"].as_str().unwrap()).unwrap(); + + let Ok(sig): Result<[u8; 256], _> = sig_bytes.try_into() else { + assert_ne!(test["result"], "valid", "tcId {tc_id}: wrong-length 'valid' signature"); + num_invalid += 1; + continue; + }; + + let verified = pk.key::().verify(&msg, None, &sig).is_ok(); + match test["result"].as_str().unwrap() { + "valid" => { + assert!(verified, "tcId {tc_id}: expected valid, got invalid"); + num_valid += 1; + } + "invalid" => { + assert!(!verified, "tcId {tc_id}: expected invalid, got valid"); + num_invalid += 1; + } + other => panic!("tcId {tc_id}: unknown result {other:?}"), + } + } + } + + assert_eq!(num_tests, 141); + assert_eq!(num_valid, 95); + assert_eq!(num_invalid, 46); +} + +// ---- bouncycastle_core trait conformance ------------------------------------------------------ + +fn fixed_keypair() +-> Result<(RsaPublicComponents, RsaPrivateComponents), SignatureError> { + let sk = genuine_key(); + let pk = RsaPublicComponents::::new(sk.n(), 0x10001)?; + Ok((pk, sk)) +} + +/// `core-test-framework`'s conformance suite for the SHA-384/SHA-512 PSS pairings (randomized, +/// `ctx` ignored); the bit-flip pass runs in `rsa_2048_pss_tests.rs`'s SHA-256 suite. +#[test] +fn pss_sha384_sha512_trait_conformance_suite() { + let framework = TestFrameworkSignature::with_ctx_behaviour(CtxBehaviour::Refused); + framework.test_signature::, RsaPrivateKey, SIG_LEN>( + || fixed_keypair().map(|(pk, sk)| (pk.into_key::(), sk.into_key::())), false, + ); + framework.test_signature::, RsaPrivateKey, SIG_LEN>( + || fixed_keypair().map(|(pk, sk)| (pk.into_key::(), sk.into_key::())), false, + ); +} + +#[test] +fn pss_sha384_and_sha512_reject_each_others_signatures() { + let (pk, sk) = fixed_keypair().unwrap(); + let msg = b"PSS across both APIs"; + pk.key::() + .verify( + msg, + None, + &sk.key::().sign(&mut DefaultRNG::default(), msg, None).unwrap(), + ) + .unwrap(); + pk.key::() + .verify( + msg, + None, + &sk.key::().sign(&mut DefaultRNG::default(), msg, None).unwrap(), + ) + .unwrap(); + let mut rng = DefaultRNG::default(); + let free_384 = sk.key::().sign(&mut rng, msg, None).unwrap(); + let free_512 = sk.key::().sign(&mut rng, msg, None).unwrap(); + pk.key::().verify(msg, None, &free_384).unwrap(); + pk.key::().verify(msg, None, &free_512).unwrap(); + // The two hash pairings are distinct encodings: neither accepts the other's signature. + assert!(pk.key::().verify(msg, None, &free_512).is_err()); + assert!(pk.key::().verify(msg, None, &free_384).is_err()); +} diff --git a/crypto/rsa/tests/rsa_2048_pss_shake128_tests.rs b/crypto/rsa/tests/rsa_2048_pss_shake128_tests.rs new file mode 100644 index 000000000..96a50b2f9 --- /dev/null +++ b/crypto/rsa/tests/rsa_2048_pss_shake128_tests.rs @@ -0,0 +1,308 @@ +//! RSA-2048 RSASSA-PSS-SHAKE128 (`id-RSASSA-PSS-SHAKE128`, RFC 8702 §3.2.1) against Wycheproof's +//! `rsa_pss_2048_shake128_test.json`, following the same split as `rsa_2048_pss_tests.rs`: no PSS +//! sig-gen vectors exist (PSS is randomized), so the sign side is a self-consistency round trip +//! against the genuine RSA-2048 key `rsa_2048_pkcs1_v1_5_tests.rs` recovered (a valid RSA private +//! key signs under any hash/MGF choice; nothing ties it to SHA-256), and the verify side is +//! checked against all of Wycheproof's real vectors. + +use bouncycastle_core::errors::SignatureError; +use bouncycastle_core::hex::decode as hex_decode; +use bouncycastle_core::signature_key::{ + OneShotSigningKey, OneShotVerifyingKey, SigningKey, VerifyingKey, +}; +use bouncycastle_core::traits::RNG; +use bouncycastle_core::traits::{HashOneShot, SignatureSigner, SignatureVerifier}; +use bouncycastle_core_test_framework::signature::{CtxBehaviour, TestFrameworkSignature}; +use bouncycastle_rng::DefaultRNG; +use bouncycastle_rsa::RSA2048; +use bouncycastle_rsa::keys::{ + RsaPrivateComponents, RsaPrivateKey, RsaPublicComponents, RsaPublicKey, +}; +use bouncycastle_rsa::rsa_2048::{RSASSA_PSS_SHAKE128, SIG_LEN}; +use bouncycastle_rsa::rsassa; +use bouncycastle_sha3::SHAKE128; +use serde_json::Value; +use std::fs; +use std::path::Path; + +/// Signs through the streaming trait path with a fixed salt (`set_salt`) -- the +/// deterministic PSS mode, for tests against a known salt. Returns `do_sign_final`'s `Result`. +macro_rules! sign_with_salt { + ($ty:ty, $sk:expr, $msg:expr, $salt:expr) => {{ + let sk_typed_ty = $sk.key::<$ty>(); + let mut signer = sk_typed_ty.create_signer(&mut DefaultRNG::default(), None).unwrap(); + signer.set_salt($salt); + signer.do_update($msg); + signer.do_final() + }}; +} + +const TEST_DATA_PATH_RELATIVE: &str = "../../../wycheproof/testvectors_v1"; +const TEST_DATA_PATH: &str = "../wycheproof/testvectors_v1"; + +fn get_test_data(filename: &str) -> String { + for dir in [TEST_DATA_PATH_RELATIVE, TEST_DATA_PATH] { + let path = format!("{dir}/{filename}"); + if Path::new(&path).exists() { + return fs::read_to_string(path).unwrap(); + } + } + panic!( + "wycheproof not found (looked for {filename} in {TEST_DATA_PATH_RELATIVE:?} and \ + {TEST_DATA_PATH:?}); this suite requires it rather than skipping" + ); +} + +fn limbs_from_hex(hex: &str) -> [u64; L] { + let bytes_len = 8 * L; + let mut bytes = hex_decode(hex).expect("valid hex"); + if bytes.len() == bytes_len + 1 && bytes[0] == 0 { + bytes.remove(0); + } + assert_eq!(bytes.len(), bytes_len, "expected a {}-bit value", bytes_len * 8); + let mut limbs = [0u64; L]; + for i in 0..L { + let start = bytes_len - (i + 1) * 8; + limbs[i] = u64::from_be_bytes(bytes[start..start + 8].try_into().unwrap()); + } + limbs +} + +/// The same genuine RSA-2048 keypair `rsa_2048_pkcs1_v1_5_tests.rs` recovers (from +/// `rsa_pkcs1_2048_sig_gen_test.json`'s SHA-256 group) -- reused here as a plain, valid RSA-2048 +/// key, not because it has anything to do with SHA-256/MGF1 specifically. +fn genuine_key() -> RsaPrivateComponents { + let p: [u64; 16] = [ + 0x0ea36cfb3a5b18f1, 0x48a6e65332119129, 0x110ad9e7b48a1c93, 0x569156b90113e2e9, + 0xe79813a575cfad9c, 0x69d659d143ec6f17, 0xe81e6bab5ddaa783, 0xbff1c5b80a69f788, + 0x978f6c35814f50ee, 0xe6a289ad4cfbf78f, 0x34d5681e5809d415, 0xbb028bda42eeb5d2, + 0x41c56e4de086b0d5, 0x58b8d1e24f3b55d0, 0xfb5248247d98cb7d, 0xdc431050f782e894, + ]; + let q: [u64; 16] = [ + 0x669f140cfbc20f25, 0xb97bb03677207d95, 0xfd4e06f3ed7299d4, 0x160f90536abc9492, + 0xf5b131f39098f7bc, 0xae8d72c57088d7ab, 0x89b94fbde542aba9, 0x3d3f9880ec47d5e0, + 0x1378a6868af3b7a0, 0x5544070beb057c94, 0x16611debc472fac4, 0xe500ffb79f5b8868, + 0x308a5e32196603b2, 0xea5fb19eb4eabc38, 0x122273ae3222b598, 0xbd1a81e7977f9898, + ]; + let d_p: [u64; 16] = [ + 0x209f33f09515d7c1, 0xb4a9b37656917205, 0x276933bb07e4efb9, 0x8c14019808e00414, + 0x289f96da220711e5, 0xfbbd2923d31532fe, 0xc06b414e61c0e1e7, 0x4c23c4588488961d, + 0x4dc48ae34514759c, 0x9c786961ae3e2c35, 0x497e8d9c650688e0, 0x18bf08472612dbe5, + 0x8885fb161870ee12, 0xf21d7c1479d99d47, 0x9121d91952ffd1c7, 0xa94b528b28f29159, + ]; + let d_q: [u64; 16] = [ + 0xf7597ffb68011d8d, 0x7b3cc538c4bab8c9, 0xa8fa480a81a925af, 0x6d6ede7251a383bf, + 0x8a63f788ce3a0f85, 0x0b920502eb478bc9, 0x7e37e755edfe70d9, 0x9cf9948422a16555, + 0x0d6d9ea1f2ef71fd, 0xf7efa32ea0cb6e00, 0x0629b114ca7f780f, 0xcf51176359654348, + 0x540cdcbd4ad35435, 0x31c02ff1a2bc437c, 0xff2503df78bafed5, 0x3af0e72a933aef09, + ]; + let q_inv: [u64; 16] = [ + 0x552fe4bfce945f7b, 0x67e50c999c67247b, 0xfb54ef17be3b2853, 0x241f5921b5ad3983, + 0x02de5eccd143cf31, 0x74e45f6fcc60f216, 0xafa5428a74f12708, 0x88d42294b6a2759b, + 0xe923e1097c0c562f, 0xc968b48a91c38b5b, 0x933e85179c0320b0, 0x7993d0445f758d51, + 0x9bfc042ee0924b1b, 0x41f956d90fa8a793, 0xee7a87b6483a66ee, 0x2640fbfbcfefb163, + ]; + RsaPrivateComponents::::from_crt_components(&p, &q, &d_p, &d_q, &q_inv, 0x10001) + .expect("recovered CRT components must be accepted") +} + +#[test] +fn pss_shake128_sign_with_fixed_salt_round_trips() { + let sk = genuine_key(); + let pk = RsaPublicComponents::::new(sk.n(), 0x10001).unwrap(); + + let salt = [0x42u8; 32]; + let sig = sign_with_salt!(RSASSA_PSS_SHAKE128, &sk, b"the message to sign", salt) + .expect("signing must succeed"); + pk.key::() + .verify(b"the message to sign", None, &sig) + .expect("must verify"); + + // Deterministic given the same salt. + let sig2 = sign_with_salt!(RSASSA_PSS_SHAKE128, &sk, b"the message to sign", salt).unwrap(); + assert_eq!(sig, sig2); + + assert!(pk.key::().verify(b"a different message", None, &sig).is_err()); +} + +#[test] +fn pss_shake128_sign_with_rng_produces_fresh_salts_that_both_verify() { + let sk = genuine_key(); + let pk = RsaPublicComponents::::new(sk.n(), 0x10001).unwrap(); + let mut rng = DefaultRNG::default(); + + let sig_a = sk + .key::() + .sign(&mut rng, b"hello", None) + .expect("signing must succeed"); + let sig_b = sk + .key::() + .sign(&mut rng, b"hello", None) + .expect("signing must succeed"); + assert_ne!(sig_a, sig_b, "PSS is randomized: two signatures of the same message must differ"); + pk.key::().verify(b"hello", None, &sig_a).expect("sig_a must verify"); + pk.key::().verify(b"hello", None, &sig_b).expect("sig_b must verify"); +} + +#[test] +fn rsa_pss_2048_shake128_wycheproof_vectors() { + let doc: Value = serde_json::from_str(&get_test_data("rsa_pss_2048_shake128_test.json")) + .expect("valid JSON"); + + let mut num_tests = 0usize; + let mut num_valid = 0usize; + let mut num_invalid = 0usize; + + for group in doc["testGroups"].as_array().unwrap() { + assert_eq!(group["sha"], "SHAKE128"); + assert_eq!(group["mgf"], "SHAKE128"); + assert_eq!(group["sLen"], 32); + let n: [u64; 32] = limbs_from_hex(group["publicKey"]["modulus"].as_str().unwrap()); + let e = u64::from_str_radix(group["publicKey"]["publicExponent"].as_str().unwrap(), 16) + .expect("publicExponent fits in u64 for every group here"); + let pk = + RsaPublicComponents::::new(&n, e).expect("group public key must be valid"); + + for test in group["tests"].as_array().unwrap() { + num_tests += 1; + let tc_id = test["tcId"].as_u64().unwrap(); + let msg = hex_decode(test["msg"].as_str().unwrap()).unwrap(); + let sig_bytes = hex_decode(test["sig"].as_str().unwrap()).unwrap(); + + let Ok(sig): Result<[u8; 256], _> = sig_bytes.try_into() else { + assert_ne!(test["result"], "valid", "tcId {tc_id}: wrong-length 'valid' signature"); + num_invalid += 1; + continue; + }; + + let verified = pk.key::().verify(&msg, None, &sig).is_ok(); + match test["result"].as_str().unwrap() { + "valid" => { + assert!(verified, "tcId {tc_id}: expected valid, got invalid"); + num_valid += 1; + } + "invalid" => { + assert!(!verified, "tcId {tc_id}: expected invalid, got valid"); + num_invalid += 1; + } + other => panic!("tcId {tc_id}: unknown result {other:?}"), + } + } + } + + assert_eq!(num_tests, 114); + assert_eq!(num_valid, 69); + assert_eq!(num_invalid, 45); +} + +// ---- bouncycastle_core trait conformance ------------------------------------------------------ + +fn fixed_keypair() +-> Result<(RsaPublicComponents, RsaPrivateComponents), SignatureError> { + let sk = genuine_key(); + let pk = RsaPublicComponents::::new(sk.n(), 0x10001)?; + Ok((pk, sk)) +} + +/// `core-test-framework`'s conformance suite for the SHAKE-native PSS path (randomized, `ctx` +/// ignored), with every signature bit flipped: `RSASSA_PSS_SHAKE` is its own generic type, so it +/// gets the exhaustive pass once, here. +#[test] +fn pss_shake128_trait_conformance_suite() { + TestFrameworkSignature::with_ctx_behaviour(CtxBehaviour::Refused) + .test_signature::, RsaPrivateKey, SIG_LEN>( + || fixed_keypair().map(|(pk, sk)| (pk.into_key::(), sk.into_key::())), true, + ); +} + +/// A fixed-output RNG (all-`0x42` bytes), as `bouncycastle-ecdsa`'s tests use: pins that +/// `SigningKey::sign` takes its salt from the caller's RNG and nowhere else. +struct FixedRng; +impl RNG for FixedRng { + fn add_seed_keymaterial( + &mut self, + _additional_seed: &dyn bouncycastle_core::key_material::KeyMaterialTrait, + ) -> Result<(), bouncycastle_core::errors::RNGError> { + Ok(()) + } + fn next_int(&mut self) -> Result { + Ok(0x42424242) + } + fn next_bytes_out( + &mut self, + out: &mut [u8], + ) -> Result { + out.fill(0x42); + Ok(out.len()) + } + fn fill_keymaterial_out( + &mut self, + _out: &mut dyn bouncycastle_core::key_material::KeyMaterialTrait, + ) -> Result { + unimplemented!() + } + fn security_strength(&self) -> bouncycastle_core::security_strength::SecurityStrength { + bouncycastle_core::security_strength::SecurityStrength::_256bit + } +} + +/// `set_salt` fixes the salt on the streaming path (the counterpart of ML-DSA's +/// `set_signer_rnd`): the result is deterministic and byte-identical to the generic +/// `rsassa::sign_from_hash_with_salt` over the same digest and salt, while an unfixed +/// streamed signature is fresh. +#[test] +fn set_salt_fixes_the_salt_on_the_streaming_path() { + let (pk, sk) = fixed_keypair().unwrap(); + let msg = b"fixed salt, streamed in two chunks"; + let salt = [0x42u8; 32]; + + let sk_rsassa_pss_shake128 = sk.key::(); + let mut signer = + sk_rsassa_pss_shake128.create_signer(&mut DefaultRNG::default(), None).unwrap(); + signer.set_salt(salt); + signer.do_update(&msg[..11]); + signer.do_update(&msg[11..]); + let sig = signer.do_final().unwrap(); + let mut digest = [0u8; 32]; + SHAKE128::hash_out(msg, &mut digest); + let expected = rsassa::sign_from_hash_with_salt::( + &sk_rsassa_pss_shake128, &digest, &salt, + ) + .unwrap(); + assert_eq!(sig, expected); + pk.key::().verify(msg, None, &sig).unwrap(); + + let sk_rsassa_pss_shake128 = sk.key::(); + let mut fresh = sk_rsassa_pss_shake128.create_signer(&mut DefaultRNG::default(), None).unwrap(); + fresh.do_update(msg); + assert_ne!(fresh.do_final().unwrap(), sig, "without set_salt the salt is fresh"); + + // On a verify-initialised state it has no effect. + let pk_rsassa_pss_shake128 = pk.key::(); + + let mut verifier = pk_rsassa_pss_shake128.create_verifier(None).unwrap(); + verifier.do_update(msg); + verifier.do_verify_final(&sig).unwrap(); +} + +/// `SigningKey::sign` draws the salt from the caller's RNG (the ECDSA/SM2 shape): with a +/// fixed-output RNG it equals the fixed-salt path over that same output, and with a real RNG it +/// is fresh per call and verifies. +#[test] +fn sign_takes_the_salt_from_the_callers_rng() { + let (pk, sk) = fixed_keypair().unwrap(); + let msg = b"caller-supplied RNG"; + let from_fixed_rng = sk.key::().sign(&mut FixedRng, msg, None).unwrap(); + assert_eq!( + from_fixed_rng, + sign_with_salt!(RSASSA_PSS_SHAKE128, &sk, msg, [0x42u8; 32]).unwrap() + ); + + let mut rng = DefaultRNG::default(); + let a = sk.key::().sign(&mut rng, msg, None).unwrap(); + let b = sk.key::().sign(&mut rng, msg, None).unwrap(); + assert_ne!(a, b); + pk.key::().verify(msg, None, &a).unwrap(); + pk.key::().verify(msg, None, &b).unwrap(); + assert!(pk.key::().verify(b"other", None, &a).is_err()); +} diff --git a/crypto/rsa/tests/rsa_2048_pss_tests.rs b/crypto/rsa/tests/rsa_2048_pss_tests.rs new file mode 100644 index 000000000..42208aedd --- /dev/null +++ b/crypto/rsa/tests/rsa_2048_pss_tests.rs @@ -0,0 +1,307 @@ +//! RSA-2048/SHA-256/MGF1-SHA-256/32-byte-salt RSASSA-PSS against Wycheproof +//! (`rsa_pss_2048_sha256_mgf1_32_test.json`), following the same lookup convention as +//! `rsa_2048_pkcs1_v1_5_tests.rs`. +//! +//! Wycheproof carries no PSS sig-gen vectors (PSS is randomized, so there is no single "the" +//! correct signature per message the way PKCS#1 v1.5's deterministic encoding gives one): the +//! sign side is exercised here by a self-consistency round trip (sign then verify) against the +//! same genuine CRT key `rsa_2048_pkcs1_v1_5_tests.rs` recovered from +//! `rsa_pkcs1_2048_sig_gen_test.json`, and the verify side by all 108 real vectors in +//! `rsa_pss_2048_sha256_mgf1_32_test.json` -- the same public key as that sig-gen key (confirmed +//! by comparing moduli in Python before writing this file). + +use bouncycastle_core::errors::SignatureError; +use bouncycastle_core::hex::decode as hex_decode; +use bouncycastle_core::signature_key::{ + OneShotSigningKey, OneShotVerifyingKey, SigningKey, VerifyingKey, +}; +use bouncycastle_core::traits::RNG; +use bouncycastle_core::traits::{HashOneShot, SignatureSigner, SignatureVerifier}; +use bouncycastle_core_test_framework::signature::{CtxBehaviour, TestFrameworkSignature}; +use bouncycastle_rng::DefaultRNG; +use bouncycastle_rsa::RSA2048; +use bouncycastle_rsa::keys::{ + RsaPrivateComponents, RsaPrivateKey, RsaPublicComponents, RsaPublicKey, +}; +use bouncycastle_rsa::rsa_2048::{RSASSA_PSS_SHA256, SIG_LEN}; +use bouncycastle_rsa::rsassa; +use bouncycastle_rsa::rsassa_pss::RSASSA_PSS; +use bouncycastle_sha2::SHA256; +use serde_json::Value; +use std::fs; +use std::path::Path; + +/// Signs through the streaming trait path with a fixed salt (`set_salt`) -- the +/// deterministic PSS mode, for tests against a known salt. Returns `do_sign_final`'s `Result`. +macro_rules! sign_with_salt { + ($ty:ty, $sk:expr, $msg:expr, $salt:expr) => {{ + let sk_typed_ty = $sk.key::<$ty>(); + let mut signer = sk_typed_ty.create_signer(&mut DefaultRNG::default(), None).unwrap(); + signer.set_salt($salt); + signer.do_update($msg); + signer.do_final() + }}; +} + +const TEST_DATA_PATH_RELATIVE: &str = "../../../wycheproof/testvectors_v1"; +const TEST_DATA_PATH: &str = "../wycheproof/testvectors_v1"; + +fn get_test_data(filename: &str) -> String { + for dir in [TEST_DATA_PATH_RELATIVE, TEST_DATA_PATH] { + let path = format!("{dir}/{filename}"); + if Path::new(&path).exists() { + return fs::read_to_string(path).unwrap(); + } + } + panic!( + "wycheproof not found (looked for {filename} in {TEST_DATA_PATH_RELATIVE:?} and \ + {TEST_DATA_PATH:?}); this suite requires it rather than skipping" + ); +} + +fn limbs_from_hex(hex: &str) -> [u64; L] { + let bytes_len = 8 * L; + let mut bytes = hex_decode(hex).expect("valid hex"); + if bytes.len() == bytes_len + 1 && bytes[0] == 0 { + bytes.remove(0); + } + assert_eq!(bytes.len(), bytes_len, "expected a {}-bit value", bytes_len * 8); + let mut limbs = [0u64; L]; + for i in 0..L { + let start = bytes_len - (i + 1) * 8; + limbs[i] = u64::from_be_bytes(bytes[start..start + 8].try_into().unwrap()); + } + limbs +} + +/// The same genuine RSA-2048 keypair `rsa_2048_pkcs1_v1_5_tests.rs` recovers from +/// `rsa_pkcs1_2048_sig_gen_test.json` -- see that file for the full, sourced provenance (p/q +/// recovered from Wycheproof's own `(n, e, d)` via the standard factoring-from-d method). +fn wycheproof_key() -> RsaPrivateComponents { + let p: [u64; 16] = [ + 0x0ea36cfb3a5b18f1, 0x48a6e65332119129, 0x110ad9e7b48a1c93, 0x569156b90113e2e9, + 0xe79813a575cfad9c, 0x69d659d143ec6f17, 0xe81e6bab5ddaa783, 0xbff1c5b80a69f788, + 0x978f6c35814f50ee, 0xe6a289ad4cfbf78f, 0x34d5681e5809d415, 0xbb028bda42eeb5d2, + 0x41c56e4de086b0d5, 0x58b8d1e24f3b55d0, 0xfb5248247d98cb7d, 0xdc431050f782e894, + ]; + let q: [u64; 16] = [ + 0x669f140cfbc20f25, 0xb97bb03677207d95, 0xfd4e06f3ed7299d4, 0x160f90536abc9492, + 0xf5b131f39098f7bc, 0xae8d72c57088d7ab, 0x89b94fbde542aba9, 0x3d3f9880ec47d5e0, + 0x1378a6868af3b7a0, 0x5544070beb057c94, 0x16611debc472fac4, 0xe500ffb79f5b8868, + 0x308a5e32196603b2, 0xea5fb19eb4eabc38, 0x122273ae3222b598, 0xbd1a81e7977f9898, + ]; + let d_p: [u64; 16] = [ + 0x209f33f09515d7c1, 0xb4a9b37656917205, 0x276933bb07e4efb9, 0x8c14019808e00414, + 0x289f96da220711e5, 0xfbbd2923d31532fe, 0xc06b414e61c0e1e7, 0x4c23c4588488961d, + 0x4dc48ae34514759c, 0x9c786961ae3e2c35, 0x497e8d9c650688e0, 0x18bf08472612dbe5, + 0x8885fb161870ee12, 0xf21d7c1479d99d47, 0x9121d91952ffd1c7, 0xa94b528b28f29159, + ]; + let d_q: [u64; 16] = [ + 0xf7597ffb68011d8d, 0x7b3cc538c4bab8c9, 0xa8fa480a81a925af, 0x6d6ede7251a383bf, + 0x8a63f788ce3a0f85, 0x0b920502eb478bc9, 0x7e37e755edfe70d9, 0x9cf9948422a16555, + 0x0d6d9ea1f2ef71fd, 0xf7efa32ea0cb6e00, 0x0629b114ca7f780f, 0xcf51176359654348, + 0x540cdcbd4ad35435, 0x31c02ff1a2bc437c, 0xff2503df78bafed5, 0x3af0e72a933aef09, + ]; + let q_inv: [u64; 16] = [ + 0x552fe4bfce945f7b, 0x67e50c999c67247b, 0xfb54ef17be3b2853, 0x241f5921b5ad3983, + 0x02de5eccd143cf31, 0x74e45f6fcc60f216, 0xafa5428a74f12708, 0x88d42294b6a2759b, + 0xe923e1097c0c562f, 0xc968b48a91c38b5b, 0x933e85179c0320b0, 0x7993d0445f758d51, + 0x9bfc042ee0924b1b, 0x41f956d90fa8a793, 0xee7a87b6483a66ee, 0x2640fbfbcfefb163, + ]; + RsaPrivateComponents::::from_crt_components(&p, &q, &d_p, &d_q, &q_inv, 0x10001) + .expect("recovered CRT components must be accepted") +} + +#[test] +fn pss_sign_with_fixed_salt_round_trips() { + let sk = wycheproof_key(); + let pk = RsaPublicComponents::::new(sk.n(), 0x10001).unwrap(); + + let salt = [0x42u8; 32]; + let sig = sign_with_salt!(RSASSA_PSS_SHA256, &sk, b"the message to sign", salt) + .expect("signing must succeed"); + pk.key::().verify(b"the message to sign", None, &sig).expect("must verify"); + + // Deterministic given the same salt. + let sig2 = sign_with_salt!(RSASSA_PSS_SHA256, &sk, b"the message to sign", salt).unwrap(); + assert_eq!(sig, sig2); + + assert!(pk.key::().verify(b"a different message", None, &sig).is_err()); +} + +#[test] +fn pss_sign_with_rng_produces_fresh_salts_that_both_verify() { + let sk = wycheproof_key(); + let pk = RsaPublicComponents::::new(sk.n(), 0x10001).unwrap(); + let mut rng = DefaultRNG::default(); + + let sig_a = + sk.key::().sign(&mut rng, b"hello", None).expect("signing must succeed"); + let sig_b = + sk.key::().sign(&mut rng, b"hello", None).expect("signing must succeed"); + assert_ne!(sig_a, sig_b, "PSS is randomized: two signatures of the same message must differ"); + pk.key::().verify(b"hello", None, &sig_a).expect("sig_a must verify"); + pk.key::().verify(b"hello", None, &sig_b).expect("sig_b must verify"); +} + +#[test] +fn rsa_pss_sha256_mgf1_32_wycheproof_vectors() { + let doc: Value = serde_json::from_str(&get_test_data("rsa_pss_2048_sha256_mgf1_32_test.json")) + .expect("valid JSON"); + + let mut num_tests = 0usize; + let mut num_valid = 0usize; + let mut num_invalid = 0usize; + + for group in doc["testGroups"].as_array().unwrap() { + assert_eq!(group["sha"], "SHA-256"); + assert_eq!(group["mgfSha"], "SHA-256"); + assert_eq!(group["sLen"], 32); + let n: [u64; 32] = limbs_from_hex(group["publicKey"]["modulus"].as_str().unwrap()); + let e = u64::from_str_radix(group["publicKey"]["publicExponent"].as_str().unwrap(), 16) + .expect("publicExponent fits in u64 for every group here"); + let pk = + RsaPublicComponents::::new(&n, e).expect("group public key must be valid"); + + for test in group["tests"].as_array().unwrap() { + num_tests += 1; + let tc_id = test["tcId"].as_u64().unwrap(); + let msg = hex_decode(test["msg"].as_str().unwrap()).unwrap(); + let sig_bytes = hex_decode(test["sig"].as_str().unwrap()).unwrap(); + + let Ok(sig): Result<[u8; 256], _> = sig_bytes.try_into() else { + assert_ne!(test["result"], "valid", "tcId {tc_id}: wrong-length 'valid' signature"); + num_invalid += 1; + continue; + }; + + let verified = pk.key::().verify(&msg, None, &sig).is_ok(); + match test["result"].as_str().unwrap() { + "valid" => { + assert!(verified, "tcId {tc_id}: expected valid, got invalid"); + num_valid += 1; + } + "invalid" => { + assert!(!verified, "tcId {tc_id}: expected invalid, got valid"); + num_invalid += 1; + } + other => panic!("tcId {tc_id}: unknown result {other:?}"), + } + } + } + + assert_eq!(num_tests, 108); + assert_eq!(num_valid, 63); + assert_eq!(num_invalid, 45); +} + +// ---- bouncycastle_core trait conformance ------------------------------------------------------ + +fn fixed_keypair() +-> Result<(RsaPublicComponents, RsaPrivateComponents), SignatureError> { + let sk = wycheproof_key(); + let pk = RsaPublicComponents::::new(sk.n(), 0x10001)?; + Ok((pk, sk)) +} + +/// `core-test-framework`'s conformance suite: randomized (`SigningKey::sign` draws a fresh salt from +/// the default RNG, so two signatures of one message differ), `ctx` ignored, every signature bit +/// flipped in turn -- run here since the generic `RSASSA_PSS` code is the same at every width. +#[test] +fn pss_sha256_trait_conformance_suite() { + TestFrameworkSignature::with_ctx_behaviour(CtxBehaviour::Refused) + .test_signature::, RsaPrivateKey, SIG_LEN>( + || fixed_keypair().map(|(pk, sk)| (pk.into_key::(), sk.into_key::())), true, + ); +} + +/// A fixed-output RNG (all-`0x42` bytes), as `bouncycastle-ecdsa`'s tests use: pins that +/// `SigningKey::sign` takes its salt from the caller's RNG and nowhere else. +struct FixedRng; +impl RNG for FixedRng { + fn add_seed_keymaterial( + &mut self, + _additional_seed: &dyn bouncycastle_core::key_material::KeyMaterialTrait, + ) -> Result<(), bouncycastle_core::errors::RNGError> { + Ok(()) + } + fn next_int(&mut self) -> Result { + Ok(0x42424242) + } + fn next_bytes_out( + &mut self, + out: &mut [u8], + ) -> Result { + out.fill(0x42); + Ok(out.len()) + } + fn fill_keymaterial_out( + &mut self, + _out: &mut dyn bouncycastle_core::key_material::KeyMaterialTrait, + ) -> Result { + unimplemented!() + } + fn security_strength(&self) -> bouncycastle_core::security_strength::SecurityStrength { + bouncycastle_core::security_strength::SecurityStrength::_256bit + } +} + +/// `set_salt` fixes the salt on the streaming path (the counterpart of ML-DSA's +/// `set_signer_rnd`): the result is deterministic and byte-identical to the generic +/// `rsassa_pss::sign_from_hash_with_salt` over the same digest and salt, while an unfixed +/// streamed signature is fresh. +#[test] +fn set_salt_fixes_the_salt_on_the_streaming_path() { + let (pk, sk) = fixed_keypair().unwrap(); + let msg = b"fixed salt, streamed in two chunks"; + let salt = [0x42u8; 32]; + + let sk_rsassa_pss_sha256 = sk.key::(); + + let mut signer = sk_rsassa_pss_sha256.create_signer(&mut DefaultRNG::default(), None).unwrap(); + signer.set_salt(salt); + signer.do_update(&msg[..11]); + signer.do_update(&msg[11..]); + let sig = signer.do_final().unwrap(); + let mut digest = [0u8; 32]; + SHA256::hash_out(msg, &mut digest); + let expected = rsassa::sign_from_hash_with_salt::, 256>( + &sk.key::>(), + &digest, + &salt, + ) + .unwrap(); + assert_eq!(sig, expected); + pk.key::().verify(msg, None, &sig).unwrap(); + + let sk_rsassa_pss_sha256 = sk.key::(); + + let mut fresh = sk_rsassa_pss_sha256.create_signer(&mut DefaultRNG::default(), None).unwrap(); + fresh.do_update(msg); + assert_ne!(fresh.do_final().unwrap(), sig, "without set_salt the salt is fresh"); + + // On a verify-initialised state it has no effect. + let pk_rsassa_pss_sha256 = pk.key::(); + let mut verifier = pk_rsassa_pss_sha256.create_verifier(None).unwrap(); + verifier.do_update(msg); + verifier.do_verify_final(&sig).unwrap(); +} + +/// `SigningKey::sign` draws the salt from the caller's RNG (the ECDSA/SM2 shape): with a +/// fixed-output RNG it equals the fixed-salt path over that same output, and with a real RNG it +/// is fresh per call and verifies. +#[test] +fn sign_takes_the_salt_from_the_callers_rng() { + let (pk, sk) = fixed_keypair().unwrap(); + let msg = b"caller-supplied RNG"; + let from_fixed_rng = sk.key::().sign(&mut FixedRng, msg, None).unwrap(); + assert_eq!(from_fixed_rng, sign_with_salt!(RSASSA_PSS_SHA256, &sk, msg, [0x42u8; 32]).unwrap()); + + let mut rng = DefaultRNG::default(); + let a = sk.key::().sign(&mut rng, msg, None).unwrap(); + let b = sk.key::().sign(&mut rng, msg, None).unwrap(); + assert_ne!(a, b); + pk.key::().verify(msg, None, &a).unwrap(); + pk.key::().verify(msg, None, &b).unwrap(); + assert!(pk.key::().verify(b"other", None, &a).is_err()); +} diff --git a/crypto/rsa/tests/rsa_3072_pss_shake128_tests.rs b/crypto/rsa/tests/rsa_3072_pss_shake128_tests.rs new file mode 100644 index 000000000..516d21653 --- /dev/null +++ b/crypto/rsa/tests/rsa_3072_pss_shake128_tests.rs @@ -0,0 +1,215 @@ +//! RSA-3072 RSASSA-PSS-SHAKE128 (RFC 8702 §3.2.1) against Wycheproof's +//! `rsa_pss_3072_shake128_test.json`, following `rsa_2048_pss_shake128_tests.rs`'s split: a +//! self-consistency round trip for signing (reusing the genuine RSA-3072 key +//! `rsa_3072_tests.rs` recovered), and all of Wycheproof's real vectors for verification. + +use bouncycastle_core::errors::SignatureError; +use bouncycastle_core::hex::decode as hex_decode; +use bouncycastle_core::signature_key::{OneShotSigningKey, OneShotVerifyingKey, SigningKey}; +use bouncycastle_core::traits::SignatureSigner; +use bouncycastle_core_test_framework::signature::{CtxBehaviour, TestFrameworkSignature}; +use bouncycastle_rng::DefaultRNG; +use bouncycastle_rsa::RSA3072; +use bouncycastle_rsa::keys::{ + RsaPrivateComponents, RsaPrivateKey, RsaPublicComponents, RsaPublicKey, +}; +use bouncycastle_rsa::rsa_3072::{RSASSA_PSS_SHAKE128, SIG_LEN}; +use serde_json::Value; +use std::fs; +use std::path::Path; + +/// Signs through the streaming trait path with a fixed salt (`set_salt`) -- the +/// deterministic PSS mode, for tests against a known salt. Returns `do_sign_final`'s `Result`. +macro_rules! sign_with_salt { + ($ty:ty, $sk:expr, $msg:expr, $salt:expr) => {{ + let sk_typed_ty = $sk.key::<$ty>(); + let mut signer = sk_typed_ty.create_signer(&mut DefaultRNG::default(), None).unwrap(); + signer.set_salt($salt); + signer.do_update($msg); + signer.do_final() + }}; +} + +const TEST_DATA_PATH_RELATIVE: &str = "../../../wycheproof/testvectors_v1"; +const TEST_DATA_PATH: &str = "../wycheproof/testvectors_v1"; + +fn get_test_data(filename: &str) -> String { + for dir in [TEST_DATA_PATH_RELATIVE, TEST_DATA_PATH] { + let path = format!("{dir}/{filename}"); + if Path::new(&path).exists() { + return fs::read_to_string(path).unwrap(); + } + } + panic!( + "wycheproof not found (looked for {filename} in {TEST_DATA_PATH_RELATIVE:?} and \ + {TEST_DATA_PATH:?}); this suite requires it rather than skipping" + ); +} + +fn limbs_from_hex(hex: &str) -> [u64; L] { + let bytes_len = 8 * L; + let mut bytes = hex_decode(hex).expect("valid hex"); + if bytes.len() == bytes_len + 1 && bytes[0] == 0 { + bytes.remove(0); + } + assert_eq!(bytes.len(), bytes_len, "expected a {}-bit value", bytes_len * 8); + let mut limbs = [0u64; L]; + for i in 0..L { + let start = bytes_len - (i + 1) * 8; + limbs[i] = u64::from_be_bytes(bytes[start..start + 8].try_into().unwrap()); + } + limbs +} + +/// The same genuine RSA-3072 keypair `rsa_3072_tests.rs` recovers (from +/// `rsa_pkcs1_3072_sig_gen_test.json`'s SHA-256 group) -- reused here as a plain, valid RSA-3072 +/// key, not because it has anything to do with SHA-256/MGF1 specifically. +fn genuine_key() -> RsaPrivateComponents { + let p: [u64; 24] = [ + 0xb26d973345bc4c5f, 0x23251a1d29962ca9, 0x554fc3f23d6c9046, 0x89ffe73b1401e9b8, + 0xe0b448b454670aca, 0xa73ea5c2413d1da2, 0xe9539bc7a8d3b351, 0x357984fc116af9cb, + 0xa93e40aac908e4e3, 0xae586c1e7f5c52cd, 0x80deaeaab651c7a9, 0xe261a4f7f4505580, + 0xc5a703b2fc28bfcf, 0x14521a6893f3f3c5, 0x0f08d649107f449a, 0xd96ceabb7ee83ce5, + 0x1b2e8a9b2bb69525, 0x383ead851fac07ad, 0x939deb88dff68550, 0xce9fa16a1cc92120, + 0x43604a7f2be2860f, 0xba55f20a964c4e63, 0x0ed9ac8a812545da, 0xf5eca16e0e83696b, + ]; + let q: [u64; 24] = [ + 0x7981610848c55cdd, 0x8bce03c5d339b975, 0xb8227d7b5d76ce8b, 0x6edee1e9d17781db, + 0x1c127ac3c4d0bd59, 0xb8b28f38951d7bee, 0x496086fa1300249a, 0x790e5c34729a8efb, + 0x9bdb81968f4a6d7c, 0x6018fd4ed9a3545f, 0x6ccb168d5b510dbe, 0xe1d845c6553c0a54, + 0x73ec1d97f669e298, 0x8b898025ef470e43, 0x160deb327e8ace01, 0x640191099b355611, + 0xe0ec501ccc94b2b0, 0x4f98c9ee4fdae41b, 0x0082a3bc42af1a14, 0x510a623c2b47a522, + 0x32057f9da6dbefc4, 0x95ad92b6f295d610, 0x19ddbfcfa2d96704, 0xcf25446f59cf5129, + ]; + let d_p: [u64; 24] = [ + 0xeeb10a8531c470ed, 0xbcd9be04cdc9d65c, 0xb684b458e4ab3854, 0x6a2dafd0d3b23a21, + 0xc812cbd3dccc8b35, 0x3e67363a947405c6, 0xa3ce9c7d391bdbb2, 0xf8bd10156b4bd580, + 0x3c1ce3ae99eb37da, 0xcfa5f4771567cc23, 0x35e0be9a437021c1, 0x8a527b7b967be52e, + 0xc649435b483585d6, 0x1dc154ddadf6bc20, 0x69105ecfc1144838, 0x3dad9bdd05d4f6d4, + 0xf95601b3d122be79, 0x92f1eed27a0ada46, 0x152e93f904cfe6e6, 0x5a6e6d9c19e8bdb3, + 0x6c0437d3cb7c843f, 0x370e84e9f5f0f931, 0x514c6940c20eb67b, 0x6357a59679d26801, + ]; + let d_q: [u64; 24] = [ + 0x1a4dbeba87772d29, 0xe51861bbb4e73e73, 0x9e86b2483e9bf22c, 0xc9ebcf4d7c2d6c9f, + 0xbe8fe9def6b7a62c, 0x4e8805a755ac2904, 0x734f44f3e4e88d18, 0x7626602fc90ae694, + 0xde97c88d40fa1ac4, 0x4eeaf1aafe2e1ba5, 0x25cd66f5205b038b, 0x8fa6bb6ae73b182d, + 0x0c85ab03068cbfee, 0x96f0ae48529b490f, 0xbb4cc906ba283d18, 0x4bf60c135a264919, + 0x4c2cf95ce74fe42c, 0xf4a5e8eed2a70c7a, 0x14ecee22e846a7d3, 0xd2a4139a39cec9df, + 0x4ba0e0801d31cbf5, 0x088a7986f6c2b8c0, 0x8bdc0f566f876191, 0x0004dadabfc15b1a, + ]; + let q_inv: [u64; 24] = [ + 0x45b268741fca195c, 0x94eacf955ae5dacd, 0x3ad1a334fd85aa87, 0xe8b01c83f2aec93e, + 0xd05fdc78929fa0cf, 0x0745ab95edda215b, 0xe5c81a2189f11467, 0xeded3f90e0ba4a97, + 0xfbf69baed9510be5, 0x6bee976c25dbaff8, 0x6ad65e9fe6c28038, 0xef6613dd6bf885c1, + 0x594990da705ebdf7, 0x8ee8b716f19429fb, 0x2662db8c85318de4, 0x22481fc74a7a3d62, + 0xfe6c3600d9b8e9a9, 0x744fac4daabf5488, 0xfbee6ec24b75fbf0, 0x8be552c8be44f139, + 0xfb0da96bd423759d, 0xb3443d93e7e8ca62, 0x36fe01b950885ecd, 0x214a1f73130e48b3, + ]; + RsaPrivateComponents::::from_crt_components(&p, &q, &d_p, &d_q, &q_inv, 0x10001) + .expect("recovered CRT components must be accepted") +} + +#[test] +fn pss_shake128_sign_with_fixed_salt_round_trips() { + let sk = genuine_key(); + let pk = RsaPublicComponents::::new(sk.n(), 0x10001).unwrap(); + + let salt = [0x42u8; 32]; + let sig = sign_with_salt!(RSASSA_PSS_SHAKE128, &sk, b"the message to sign", salt) + .expect("signing must succeed"); + pk.key::() + .verify(b"the message to sign", None, &sig) + .expect("must verify"); + + let sig2 = sign_with_salt!(RSASSA_PSS_SHAKE128, &sk, b"the message to sign", salt).unwrap(); + assert_eq!(sig, sig2); + + assert!(pk.key::().verify(b"a different message", None, &sig).is_err()); +} + +#[test] +fn pss_shake128_sign_with_rng_produces_fresh_salts_that_both_verify() { + let sk = genuine_key(); + let pk = RsaPublicComponents::::new(sk.n(), 0x10001).unwrap(); + let mut rng = DefaultRNG::default(); + + let sig_a = sk + .key::() + .sign(&mut rng, b"hello", None) + .expect("signing must succeed"); + let sig_b = sk + .key::() + .sign(&mut rng, b"hello", None) + .expect("signing must succeed"); + assert_ne!(sig_a, sig_b, "PSS is randomized: two signatures of the same message must differ"); + pk.key::().verify(b"hello", None, &sig_a).expect("sig_a must verify"); + pk.key::().verify(b"hello", None, &sig_b).expect("sig_b must verify"); +} + +#[test] +fn rsa_pss_3072_shake128_wycheproof_vectors() { + let doc: Value = serde_json::from_str(&get_test_data("rsa_pss_3072_shake128_test.json")) + .expect("valid JSON"); + + let mut num_tests = 0usize; + let mut num_valid = 0usize; + let mut num_invalid = 0usize; + + for group in doc["testGroups"].as_array().unwrap() { + assert_eq!(group["sha"], "SHAKE128"); + assert_eq!(group["mgf"], "SHAKE128"); + assert_eq!(group["sLen"], 32); + let n: [u64; 48] = limbs_from_hex(group["publicKey"]["modulus"].as_str().unwrap()); + let e = u64::from_str_radix(group["publicKey"]["publicExponent"].as_str().unwrap(), 16) + .expect("publicExponent fits in u64 for every group here"); + let pk = + RsaPublicComponents::::new(&n, e).expect("group public key must be valid"); + + for test in group["tests"].as_array().unwrap() { + num_tests += 1; + let tc_id = test["tcId"].as_u64().unwrap(); + let msg = hex_decode(test["msg"].as_str().unwrap()).unwrap(); + let sig_bytes = hex_decode(test["sig"].as_str().unwrap()).unwrap(); + + let Ok(sig): Result<[u8; 384], _> = sig_bytes.try_into() else { + assert_ne!(test["result"], "valid", "tcId {tc_id}: wrong-length 'valid' signature"); + num_invalid += 1; + continue; + }; + + let verified = pk.key::().verify(&msg, None, &sig).is_ok(); + match test["result"].as_str().unwrap() { + "valid" => { + assert!(verified, "tcId {tc_id}: expected valid, got invalid"); + num_valid += 1; + } + "invalid" => { + assert!(!verified, "tcId {tc_id}: expected invalid, got valid"); + num_invalid += 1; + } + other => panic!("tcId {tc_id}: unknown result {other:?}"), + } + } + } + + assert_eq!(num_tests, 114); + assert_eq!(num_valid, 69); + assert_eq!(num_invalid, 45); +} + +// ---- bouncycastle_core trait conformance ------------------------------------------------------ + +fn fixed_keypair() +-> Result<(RsaPublicComponents, RsaPrivateComponents), SignatureError> { + let sk = genuine_key(); + let pk = RsaPublicComponents::::new(sk.n(), 0x10001)?; + Ok((pk, sk)) +} + +#[test] +fn pss_shake128_trait_conformance_suite() { + TestFrameworkSignature::with_ctx_behaviour(CtxBehaviour::Refused) + .test_signature::, RsaPrivateKey, SIG_LEN>( + || fixed_keypair().map(|(pk, sk)| (pk.into_key::(), sk.into_key::())), false, + ); +} diff --git a/crypto/rsa/tests/rsa_3072_tests.rs b/crypto/rsa/tests/rsa_3072_tests.rs new file mode 100644 index 000000000..b3ff1e828 --- /dev/null +++ b/crypto/rsa/tests/rsa_3072_tests.rs @@ -0,0 +1,425 @@ +//! RSA-3072 against Wycheproof: `rsa_pkcs1_3072_sig_gen_test.json` (sign), `rsa_signature_3072_ +//! sha{256,384,512}_test.json` (verify, all three hashes), and `rsa_pss_3072_sha256_mgf1_32_test.json` +//! (PSS verify; no matching-hash-and-MGF PSS vector file exists for SHA-384/512 at this size, so +//! those are self-consistency only, following `rsa_2048_pss_sha384_sha512_tests.rs`'s precedent -- +//! including its fixed-salt-round-trip-plus-rejection and RNG-freshness test shape, so every +//! PSS signing path (three hashes, RNG-drawn or fixed salt) is actually exercised at least once). +//! +//! `p`/`q`/`dP`/`dQ`/`qInv` were recovered from `rsa_pkcs1_3072_sig_gen_test.json`'s SHA-256 +//! group's `(n, e, d)` via the same factoring-from-d method as RSA-2048's key (see +//! `rsa_2048_pkcs1_v1_5_tests.rs`), cross-checked against all 8 of that group's real signatures +//! before being pasted here. + +use bouncycastle_core::errors::SignatureError; +use bouncycastle_core::hex::decode as hex_decode; +use bouncycastle_core::signature_key::{ + DeterministicOneShotSigningKey, OneShotSigningKey, OneShotVerifyingKey, SigningKey, +}; +use bouncycastle_core::traits::SignatureSigner; +use bouncycastle_core_test_framework::signature::{ + CtxBehaviour, TestFrameworkSignature, TestFrameworkSignatureKeys, +}; +use bouncycastle_rng::DefaultRNG; +use bouncycastle_rsa::RSA3072; +use bouncycastle_rsa::keys::{ + RsaPrivateComponents, RsaPrivateKey, RsaPublicComponents, RsaPublicKey, +}; +use bouncycastle_rsa::rsa_3072::{ + PK_LEN, RSASSA_PKCS1_v1_5_SHA256, RSASSA_PKCS1_v1_5_SHA384, RSASSA_PKCS1_v1_5_SHA512, + RSASSA_PSS_SHA256, RSASSA_PSS_SHA384, RSASSA_PSS_SHA512, SIG_LEN, SK_LEN, +}; +use serde_json::Value; +use std::fs; +use std::path::Path; + +/// Signs through the streaming trait path with a fixed salt (`set_salt`) -- the +/// deterministic PSS mode, for tests against a known salt. Returns `do_sign_final`'s `Result`. +macro_rules! sign_with_salt { + ($ty:ty, $sk:expr, $msg:expr, $salt:expr) => {{ + let sk_typed_ty = $sk.key::<$ty>(); + let mut signer = sk_typed_ty.create_signer(&mut DefaultRNG::default(), None).unwrap(); + signer.set_salt($salt); + signer.do_update($msg); + signer.do_final() + }}; +} + +const TEST_DATA_PATH_RELATIVE: &str = "../../../wycheproof/testvectors_v1"; +const TEST_DATA_PATH: &str = "../wycheproof/testvectors_v1"; + +fn get_test_data(filename: &str) -> String { + for dir in [TEST_DATA_PATH_RELATIVE, TEST_DATA_PATH] { + let path = format!("{dir}/{filename}"); + if Path::new(&path).exists() { + return fs::read_to_string(path).unwrap(); + } + } + panic!( + "wycheproof not found (looked for {filename} in {TEST_DATA_PATH_RELATIVE:?} and \ + {TEST_DATA_PATH:?}); this suite requires it rather than skipping" + ); +} + +fn limbs_from_hex(hex: &str) -> [u64; L] { + let bytes_len = 8 * L; + let mut bytes = hex_decode(hex).expect("valid hex"); + if bytes.len() == bytes_len + 1 && bytes[0] == 0 { + bytes.remove(0); + } + assert_eq!(bytes.len(), bytes_len, "expected a {}-bit value", bytes_len * 8); + let mut limbs = [0u64; L]; + for i in 0..L { + let start = bytes_len - (i + 1) * 8; + limbs[i] = u64::from_be_bytes(bytes[start..start + 8].try_into().unwrap()); + } + limbs +} + +fn genuine_key() -> RsaPrivateComponents { + let p: [u64; 24] = [ + 0xb26d973345bc4c5f, 0x23251a1d29962ca9, 0x554fc3f23d6c9046, 0x89ffe73b1401e9b8, + 0xe0b448b454670aca, 0xa73ea5c2413d1da2, 0xe9539bc7a8d3b351, 0x357984fc116af9cb, + 0xa93e40aac908e4e3, 0xae586c1e7f5c52cd, 0x80deaeaab651c7a9, 0xe261a4f7f4505580, + 0xc5a703b2fc28bfcf, 0x14521a6893f3f3c5, 0x0f08d649107f449a, 0xd96ceabb7ee83ce5, + 0x1b2e8a9b2bb69525, 0x383ead851fac07ad, 0x939deb88dff68550, 0xce9fa16a1cc92120, + 0x43604a7f2be2860f, 0xba55f20a964c4e63, 0x0ed9ac8a812545da, 0xf5eca16e0e83696b, + ]; + let q: [u64; 24] = [ + 0x7981610848c55cdd, 0x8bce03c5d339b975, 0xb8227d7b5d76ce8b, 0x6edee1e9d17781db, + 0x1c127ac3c4d0bd59, 0xb8b28f38951d7bee, 0x496086fa1300249a, 0x790e5c34729a8efb, + 0x9bdb81968f4a6d7c, 0x6018fd4ed9a3545f, 0x6ccb168d5b510dbe, 0xe1d845c6553c0a54, + 0x73ec1d97f669e298, 0x8b898025ef470e43, 0x160deb327e8ace01, 0x640191099b355611, + 0xe0ec501ccc94b2b0, 0x4f98c9ee4fdae41b, 0x0082a3bc42af1a14, 0x510a623c2b47a522, + 0x32057f9da6dbefc4, 0x95ad92b6f295d610, 0x19ddbfcfa2d96704, 0xcf25446f59cf5129, + ]; + let d_p: [u64; 24] = [ + 0xeeb10a8531c470ed, 0xbcd9be04cdc9d65c, 0xb684b458e4ab3854, 0x6a2dafd0d3b23a21, + 0xc812cbd3dccc8b35, 0x3e67363a947405c6, 0xa3ce9c7d391bdbb2, 0xf8bd10156b4bd580, + 0x3c1ce3ae99eb37da, 0xcfa5f4771567cc23, 0x35e0be9a437021c1, 0x8a527b7b967be52e, + 0xc649435b483585d6, 0x1dc154ddadf6bc20, 0x69105ecfc1144838, 0x3dad9bdd05d4f6d4, + 0xf95601b3d122be79, 0x92f1eed27a0ada46, 0x152e93f904cfe6e6, 0x5a6e6d9c19e8bdb3, + 0x6c0437d3cb7c843f, 0x370e84e9f5f0f931, 0x514c6940c20eb67b, 0x6357a59679d26801, + ]; + let d_q: [u64; 24] = [ + 0x1a4dbeba87772d29, 0xe51861bbb4e73e73, 0x9e86b2483e9bf22c, 0xc9ebcf4d7c2d6c9f, + 0xbe8fe9def6b7a62c, 0x4e8805a755ac2904, 0x734f44f3e4e88d18, 0x7626602fc90ae694, + 0xde97c88d40fa1ac4, 0x4eeaf1aafe2e1ba5, 0x25cd66f5205b038b, 0x8fa6bb6ae73b182d, + 0x0c85ab03068cbfee, 0x96f0ae48529b490f, 0xbb4cc906ba283d18, 0x4bf60c135a264919, + 0x4c2cf95ce74fe42c, 0xf4a5e8eed2a70c7a, 0x14ecee22e846a7d3, 0xd2a4139a39cec9df, + 0x4ba0e0801d31cbf5, 0x088a7986f6c2b8c0, 0x8bdc0f566f876191, 0x0004dadabfc15b1a, + ]; + let q_inv: [u64; 24] = [ + 0x45b268741fca195c, 0x94eacf955ae5dacd, 0x3ad1a334fd85aa87, 0xe8b01c83f2aec93e, + 0xd05fdc78929fa0cf, 0x0745ab95edda215b, 0xe5c81a2189f11467, 0xeded3f90e0ba4a97, + 0xfbf69baed9510be5, 0x6bee976c25dbaff8, 0x6ad65e9fe6c28038, 0xef6613dd6bf885c1, + 0x594990da705ebdf7, 0x8ee8b716f19429fb, 0x2662db8c85318de4, 0x22481fc74a7a3d62, + 0xfe6c3600d9b8e9a9, 0x744fac4daabf5488, 0xfbee6ec24b75fbf0, 0x8be552c8be44f139, + 0xfb0da96bd423759d, 0xb3443d93e7e8ca62, 0x36fe01b950885ecd, 0x214a1f73130e48b3, + ]; + RsaPrivateComponents::::from_crt_components(&p, &q, &d_p, &d_q, &q_inv, 0x10001) + .expect("recovered CRT components must be accepted") +} + +#[test] +fn pkcs1_v1_5_sig_gen_3072_sha256() { + let sk = genuine_key(); + let doc: Value = + serde_json::from_str(&get_test_data("rsa_pkcs1_3072_sig_gen_test.json")).unwrap(); + let group = doc["testGroups"] + .as_array() + .unwrap() + .iter() + .find(|g| g["sha"] == "SHA-256" && g["tests"].as_array().unwrap().len() == 8) + .expect("the main SHA-256/3072 group"); + + let mut num_tests = 0usize; + for test in group["tests"].as_array().unwrap() { + num_tests += 1; + let tc_id = test["tcId"].as_u64().unwrap(); + let msg = hex_decode(test["msg"].as_str().unwrap()).unwrap(); + let expected_sig = hex_decode(test["sig"].as_str().unwrap()).unwrap(); + let sig = sk + .key::() + .sign_deterministic(&msg, None) + .unwrap_or_else(|e| { + panic!("tcId {tc_id}: signing failed: {e:?}"); + }); + assert_eq!(sig.to_vec(), expected_sig, "tcId {tc_id}: signature mismatch"); + } + assert_eq!(num_tests, 8); +} + +#[test] +fn pkcs1_v1_5_sha384_and_sha512_round_trip() { + let sk = genuine_key(); + let pk = RsaPublicComponents::::new(sk.n(), 0x10001).unwrap(); + let sig384 = sk.key::().sign_deterministic(b"hello", None).unwrap(); + pk.key::().verify(b"hello", None, &sig384).unwrap(); + let sig512 = sk.key::().sign_deterministic(b"hello", None).unwrap(); + pk.key::().verify(b"hello", None, &sig512).unwrap(); +} + +/// Mutation testing found that fixed-salt PSS/SHA-256 signing, RNG-salted PSS/SHA-384 signing, +/// fixed-salt PSS/SHA-512 signing, and PSS/SHA-384 and /SHA-512 verification's rejection paths were +/// never exercised at this modulus size (only the RNG or `_with_salt` half of each hash was +/// called, and no test asserted a wrong message is rejected for SHA-384/512): a +/// whole-function-body mutant replacing any of them with a constant still passed the whole suite. +/// Split into six tests, one per (hash, salt source) pairing, matching +/// `rsa_2048_pss_sha384_sha512_tests.rs`'s own shape so every function is called and every +/// rejection path is checked. +#[test] +fn pss_sha256_fixed_salt_round_trips() { + let sk = genuine_key(); + let pk = RsaPublicComponents::::new(sk.n(), 0x10001).unwrap(); + let salt = [0x22u8; 32]; + let sig = + sign_with_salt!(RSASSA_PSS_SHA256, &sk, b"hello", salt).expect("signing must succeed"); + pk.key::().verify(b"hello", None, &sig).expect("must verify"); + assert!(pk.key::().verify(b"goodbye", None, &sig).is_err()); +} + +#[test] +fn pss_sha256_rng_produces_fresh_salts_that_both_verify() { + let sk = genuine_key(); + let pk = RsaPublicComponents::::new(sk.n(), 0x10001).unwrap(); + let mut rng = DefaultRNG::default(); + let sig_a = + sk.key::().sign(&mut rng, b"hello", None).expect("signing must succeed"); + let sig_b = + sk.key::().sign(&mut rng, b"hello", None).expect("signing must succeed"); + assert_ne!(sig_a, sig_b, "PSS is randomized: two signatures of the same message must differ"); + pk.key::().verify(b"hello", None, &sig_a).expect("sig_a must verify"); + pk.key::().verify(b"hello", None, &sig_b).expect("sig_b must verify"); +} + +#[test] +fn pss_sha384_fixed_salt_round_trips() { + let sk = genuine_key(); + let pk = RsaPublicComponents::::new(sk.n(), 0x10001).unwrap(); + let salt = [0x11u8; 48]; + let sig = + sign_with_salt!(RSASSA_PSS_SHA384, &sk, b"hello", salt).expect("signing must succeed"); + pk.key::().verify(b"hello", None, &sig).expect("must verify"); + assert!(pk.key::().verify(b"goodbye", None, &sig).is_err()); +} + +#[test] +fn pss_sha384_rng_produces_fresh_salts_that_both_verify() { + let sk = genuine_key(); + let pk = RsaPublicComponents::::new(sk.n(), 0x10001).unwrap(); + let mut rng = DefaultRNG::default(); + let sig_a = + sk.key::().sign(&mut rng, b"hello", None).expect("signing must succeed"); + let sig_b = + sk.key::().sign(&mut rng, b"hello", None).expect("signing must succeed"); + assert_ne!(sig_a, sig_b, "PSS is randomized: two signatures of the same message must differ"); + pk.key::().verify(b"hello", None, &sig_a).expect("sig_a must verify"); + pk.key::().verify(b"hello", None, &sig_b).expect("sig_b must verify"); +} + +#[test] +fn pss_sha512_fixed_salt_round_trips() { + let sk = genuine_key(); + let pk = RsaPublicComponents::::new(sk.n(), 0x10001).unwrap(); + let salt = [0x33u8; 64]; + let sig = + sign_with_salt!(RSASSA_PSS_SHA512, &sk, b"hello", salt).expect("signing must succeed"); + pk.key::().verify(b"hello", None, &sig).expect("must verify"); + assert!(pk.key::().verify(b"goodbye", None, &sig).is_err()); +} + +#[test] +fn pss_sha512_rng_produces_fresh_salts_that_both_verify() { + let sk = genuine_key(); + let pk = RsaPublicComponents::::new(sk.n(), 0x10001).unwrap(); + let mut rng = DefaultRNG::default(); + let sig_a = + sk.key::().sign(&mut rng, b"hello", None).expect("signing must succeed"); + let sig_b = + sk.key::().sign(&mut rng, b"hello", None).expect("signing must succeed"); + assert_ne!(sig_a, sig_b, "PSS is randomized: two signatures of the same message must differ"); + pk.key::().verify(b"hello", None, &sig_a).expect("sig_a must verify"); + pk.key::().verify(b"hello", None, &sig_b).expect("sig_b must verify"); +} + +fn run_pkcs1_v1_5_verify_vectors( + filename: &str, + verify: impl Fn(&RsaPublicComponents, &[u8], &[u8; 384]) -> bool, + expected_sha: &str, + expected_valid: usize, + expected_invalid: usize, +) { + let doc: Value = serde_json::from_str(&get_test_data(filename)).expect("valid JSON"); + let mut num_valid = 0usize; + let mut num_invalid = 0usize; + let mut num_missing_null = 0usize; + + for group in doc["testGroups"].as_array().unwrap() { + assert_eq!(group["sha"], expected_sha); + let n: [u64; 48] = limbs_from_hex(group["publicKey"]["modulus"].as_str().unwrap()); + let e = u64::from_str_radix(group["publicKey"]["publicExponent"].as_str().unwrap(), 16) + .unwrap(); + let pk = RsaPublicComponents::::new(&n, e).unwrap(); + + for test in group["tests"].as_array().unwrap() { + let tc_id = test["tcId"].as_u64().unwrap(); + let msg = hex_decode(test["msg"].as_str().unwrap()).unwrap(); + let sig_bytes = hex_decode(test["sig"].as_str().unwrap()).unwrap(); + let flags: Vec<&str> = + test["flags"].as_array().unwrap().iter().map(|f| f.as_str().unwrap()).collect(); + + let Ok(sig): Result<[u8; 384], _> = sig_bytes.try_into() else { + assert_ne!(test["result"], "valid"); + num_invalid += 1; + continue; + }; + let verified = verify(&pk, &msg, &sig); + match test["result"].as_str().unwrap() { + "valid" => { + assert!(verified, "tcId {tc_id}: expected valid, got invalid"); + num_valid += 1; + } + "invalid" => { + assert!(!verified, "tcId {tc_id}: expected invalid, got valid"); + num_invalid += 1; + } + "acceptable" => { + assert_eq!(flags, vec!["MissingNull"], "tcId {tc_id}: unreviewed acceptable"); + assert!(verified); + num_missing_null += 1; + } + other => panic!("tcId {tc_id}: unknown result {other:?}"), + } + } + } + assert_eq!(num_missing_null, 1); + assert_eq!(num_valid, expected_valid, "for {filename}"); + assert_eq!(num_invalid, expected_invalid, "for {filename}"); +} + +#[test] +fn rsa_signature_3072_sha256_wycheproof_vectors() { + run_pkcs1_v1_5_verify_vectors( + "rsa_signature_3072_sha256_test.json", + |pk, msg, sig| pk.key::().verify(msg, None, sig).is_ok(), + "SHA-256", + 8, + 250, + ); +} + +/// Mutation testing found PKCS#1 v1.5/SHA-384 verification had no rejection-path coverage at this +/// modulus size (only SHA-256's real vector file was wired up, despite this file's own module +/// docs already claiming all three hashes): a whole-function-body mutant that always returned +/// `Ok(())` still passed the whole suite. +#[test] +fn rsa_signature_3072_sha384_wycheproof_vectors() { + run_pkcs1_v1_5_verify_vectors( + "rsa_signature_3072_sha384_test.json", + |pk, msg, sig| pk.key::().verify(msg, None, sig).is_ok(), + "SHA-384", + 7, + 251, + ); +} + +/// As [`rsa_signature_3072_sha384_wycheproof_vectors`], for PKCS#1 v1.5/SHA-512. This +/// file's `rsa_signature_3072_sha512_test.json` has a second, one-test group (a `SmallSignature`/ +/// `SmallPublicKey` edge case under its own key), which `run_pkcs1_v1_5_verify_vectors` already +/// handles by deriving `pk` fresh per group -- hence one more `valid` than SHA-384's file. +#[test] +fn rsa_signature_3072_sha512_wycheproof_vectors() { + run_pkcs1_v1_5_verify_vectors( + "rsa_signature_3072_sha512_test.json", + |pk, msg, sig| pk.key::().verify(msg, None, sig).is_ok(), + "SHA-512", + 8, + 251, + ); +} + +#[test] +fn rsa_pss_3072_sha256_mgf1_32_wycheproof_vectors() { + let doc: Value = + serde_json::from_str(&get_test_data("rsa_pss_3072_sha256_mgf1_32_test.json")).unwrap(); + let mut num_valid = 0usize; + let mut num_invalid = 0usize; + + for group in doc["testGroups"].as_array().unwrap() { + assert_eq!(group["sha"], "SHA-256"); + assert_eq!(group["sLen"], 32); + let n: [u64; 48] = limbs_from_hex(group["publicKey"]["modulus"].as_str().unwrap()); + let e = u64::from_str_radix(group["publicKey"]["publicExponent"].as_str().unwrap(), 16) + .unwrap(); + let pk = RsaPublicComponents::::new(&n, e).unwrap(); + + for test in group["tests"].as_array().unwrap() { + let tc_id = test["tcId"].as_u64().unwrap(); + let msg = hex_decode(test["msg"].as_str().unwrap()).unwrap(); + let sig_bytes = hex_decode(test["sig"].as_str().unwrap()).unwrap(); + let Ok(sig): Result<[u8; 384], _> = sig_bytes.try_into() else { + assert_ne!(test["result"], "valid"); + num_invalid += 1; + continue; + }; + let verified = pk.key::().verify(&msg, None, &sig).is_ok(); + match test["result"].as_str().unwrap() { + "valid" => { + assert!(verified, "tcId {tc_id}: expected valid"); + num_valid += 1; + } + "invalid" => { + assert!(!verified, "tcId {tc_id}: expected invalid"); + num_invalid += 1; + } + other => panic!("unknown result {other:?}"), + } + } + } + assert_eq!(num_valid, 63); + assert_eq!(num_invalid, 45); +} + +// ---- bouncycastle_core trait conformance ------------------------------------------------------ + +fn fixed_keypair() +-> Result<(RsaPublicComponents, RsaPrivateComponents), SignatureError> { + let sk = genuine_key(); + let pk = RsaPublicComponents::::new(sk.n(), 0x10001)?; + Ok((pk, sk)) +} + +/// `core-test-framework`'s conformance suite for every RSA-3072 pairing (the exhaustive bit-flip +/// pass over the shared generic code runs at RSA-2048). +#[test] +fn pkcs1_v1_5_trait_conformance_suites() { + let framework = TestFrameworkSignature::with_ctx_behaviour(CtxBehaviour::Refused); + framework.test_deterministic_signature::, RsaPrivateKey, SIG_LEN>( + || fixed_keypair().map(|(pk, sk)| (pk.into_key::(), sk.into_key::())), false); + framework.test_deterministic_signature::, RsaPrivateKey, SIG_LEN>( + || fixed_keypair().map(|(pk, sk)| (pk.into_key::(), sk.into_key::())), false); + framework.test_deterministic_signature::, RsaPrivateKey, SIG_LEN>( + || fixed_keypair().map(|(pk, sk)| (pk.into_key::(), sk.into_key::())), false); +} + +#[test] +fn pss_trait_conformance_suites() { + let framework = TestFrameworkSignature::with_ctx_behaviour(CtxBehaviour::Refused); + framework.test_signature::, RsaPrivateKey, SIG_LEN>( + || fixed_keypair().map(|(pk, sk)| (pk.into_key::(), sk.into_key::())), false, + ); + framework.test_signature::, RsaPrivateKey, SIG_LEN>( + || fixed_keypair().map(|(pk, sk)| (pk.into_key::(), sk.into_key::())), false, + ); + framework.test_signature::, RsaPrivateKey, SIG_LEN>( + || fixed_keypair().map(|(pk, sk)| (pk.into_key::(), sk.into_key::())), false, + ); +} + +#[test] +fn key_trait_boundary_conditions() { + TestFrameworkSignatureKeys::new() + .test_keys::, RsaPrivateKey, PK_LEN, SK_LEN>( + || fixed_keypair().map(|(pk, sk)| (pk.into_key::(), sk.into_key::())), + ); +} diff --git a/crypto/rsa/tests/rsa_4096_pss_shake256_tests.rs b/crypto/rsa/tests/rsa_4096_pss_shake256_tests.rs new file mode 100644 index 000000000..620a5145e --- /dev/null +++ b/crypto/rsa/tests/rsa_4096_pss_shake256_tests.rs @@ -0,0 +1,224 @@ +//! RSA-4096 RSASSA-PSS-SHAKE256 (RFC 8702 §3.2.1) against Wycheproof's +//! `rsa_pss_4096_shake256_test.json`, following `rsa_2048_pss_shake128_tests.rs`'s split: a +//! self-consistency round trip for signing (reusing the genuine RSA-4096 key `rsa_4096_tests.rs` +//! recovered), and all of Wycheproof's real vectors for verification. + +use bouncycastle_core::hex::decode as hex_decode; +use bouncycastle_core::signature_key::{OneShotSigningKey, OneShotVerifyingKey, SigningKey}; +use bouncycastle_core::traits::SignatureSigner; +use bouncycastle_rng::DefaultRNG; +use bouncycastle_rsa::RSA4096; +use bouncycastle_rsa::keys::{RsaPrivateComponents, RsaPublicComponents}; +use bouncycastle_rsa::rsa_4096::RSASSA_PSS_SHAKE256; +use serde_json::Value; +use std::fs; +use std::path::Path; + +/// Signs through the streaming trait path with a fixed salt (`set_salt`) -- the +/// deterministic PSS mode, for tests against a known salt. Returns `do_sign_final`'s `Result`. +macro_rules! sign_with_salt { + ($ty:ty, $sk:expr, $msg:expr, $salt:expr) => {{ + let sk_typed_ty = $sk.key::<$ty>(); + let mut signer = sk_typed_ty.create_signer(&mut DefaultRNG::default(), None).unwrap(); + signer.set_salt($salt); + signer.do_update($msg); + signer.do_final() + }}; +} + +const TEST_DATA_PATH_RELATIVE: &str = "../../../wycheproof/testvectors_v1"; +const TEST_DATA_PATH: &str = "../wycheproof/testvectors_v1"; + +fn get_test_data(filename: &str) -> String { + for dir in [TEST_DATA_PATH_RELATIVE, TEST_DATA_PATH] { + let path = format!("{dir}/{filename}"); + if Path::new(&path).exists() { + return fs::read_to_string(path).unwrap(); + } + } + panic!( + "wycheproof not found (looked for {filename} in {TEST_DATA_PATH_RELATIVE:?} and \ + {TEST_DATA_PATH:?}); this suite requires it rather than skipping" + ); +} + +fn limbs_from_hex(hex: &str) -> [u64; L] { + let bytes_len = 8 * L; + let mut bytes = hex_decode(hex).expect("valid hex"); + if bytes.len() == bytes_len + 1 && bytes[0] == 0 { + bytes.remove(0); + } + assert_eq!(bytes.len(), bytes_len, "expected a {}-bit value", bytes_len * 8); + let mut limbs = [0u64; L]; + for i in 0..L { + let start = bytes_len - (i + 1) * 8; + limbs[i] = u64::from_be_bytes(bytes[start..start + 8].try_into().unwrap()); + } + limbs +} + +/// The same genuine RSA-4096 keypair `rsa_4096_tests.rs` recovers (from +/// `rsa_pkcs1_4096_sig_gen_test.json`'s SHA-256 group) -- reused here as a plain, valid RSA-4096 +/// key, not because it has anything to do with SHA-256/MGF1 specifically. +fn genuine_key() -> RsaPrivateComponents { + let p: [u64; 32] = [ + 0x5141acd4afd4771f, 0x5857742b7e4032dc, 0xb7a9b97fe5371396, 0x4b1783c5bc91a6dc, + 0xaf5d0c912d97b728, 0xeb265a7f28b88976, 0x5e993302aa72f11d, 0xc007ad09d76ae22a, + 0x44cbb87b8bec8fd3, 0xf152f15c73b95ac5, 0x8dbdad655fbbad20, 0x59855d0de1c794ac, + 0x4c6060926d878a20, 0xf38860474e44993d, 0x177a91caeef98b13, 0xd1676123544d3def, + 0xc1673063d8487390, 0xfedd55ba2e233a6d, 0x016a5735b883c639, 0xbd813f9fb752805b, + 0x923a7b775b5ffaff, 0xb174e55ca6a12c21, 0x0373077895a6934a, 0x6b725388f54ffea3, + 0x953c09104e1fd2d3, 0x9114f39017871528, 0x33918eb72b786b3c, 0xf43b8626af13d14a, + 0x886a0904eb486140, 0x0037409b81f3a5b3, 0x19e44e26140d2ede, 0xc3c677495c2bd566, + ]; + let q: [u64; 32] = [ + 0xee0745546a6a1c73, 0x8b1050436d882425, 0xdc2e7872ce6fb2b7, 0xf98671ee4899050b, + 0x796a5dd847400804, 0x9ba1f51132355792, 0xc39066a9fc27985b, 0x81f4bca5d15e0962, + 0x6a46cf6dbb6d2ad9, 0xdf3d085ae7693b7e, 0xf58e3c750b6d978a, 0xb52b9000d3a7aab1, + 0xdbb07e23bce1960c, 0x4e291b5c8ddaa6a7, 0x0544a7a7cb3f0792, 0xc695e324fbb11beb, + 0xbded418507f2f175, 0x49fe5f47737ff436, 0xeb37f85b7554d7ad, 0x724d042aef25cea2, + 0xeadbd11dcd2fec7b, 0xb50812705b379f5d, 0xfc50fa98fb67b746, 0x16f2bdf5964b26c7, + 0xcc1c817507859246, 0x6810c2136ad81b16, 0xd7bc78d637e17e0e, 0x6882825347455782, + 0xcdb615d921f5e705, 0x0a982efbe6658e6b, 0x59e96686f7b8752f, 0xc357cf685f9b8d4e, + ]; + let d_p: [u64; 32] = [ + 0x3cd8e91fee6bcdd3, 0x074fdc015ab1c45f, 0x34135987a2288907, 0xf6961d44dfb7505c, + 0x251be32315a85b75, 0xe8982e8493a2ae78, 0xc268493861002977, 0x140fb5806735814e, + 0x35d426d719b12c41, 0xa5f194dbbf374226, 0xa0a6c5314c1a2375, 0x66899d59c04b60c4, + 0x5158d7867dbfec94, 0xec1dde997c00125e, 0x62e5a19b2a71decf, 0x310291892c37e8a2, + 0x223e06c9521f4a45, 0xe4f08e1d5543ed74, 0xcf4dc8de58b9e9ad, 0x9167ad4f122b3263, + 0xf110dbac286712f6, 0x2db237d0f39cda5f, 0xa54b67367c857476, 0x138b37b7b1ed2219, + 0x950d9f4e82aab9bc, 0x90943e671e928e23, 0x44791809c9fcf19f, 0xc70396da054ba478, + 0x77248f6fe00e31bd, 0xf3731b1415d5f2ee, 0xf5242aa6657760cd, 0xa6bbb5460638d2b2, + ]; + let d_q: [u64; 32] = [ + 0xfa935bd36284ea6b, 0x9c255a57d6b3ac0f, 0x35b350881ec52e99, 0xf48d35dd11598957, + 0x61fee5d3763b8cfb, 0xf86f5d1936a161ae, 0x3a8b852507264ae2, 0xe558f90950a572a2, + 0x205aeb15029c95a6, 0x0fa8cf020e960c3b, 0x6a793c66abfb0963, 0xa9c7d7b391d0cbee, + 0x6310f31421e85c6b, 0xc0de89d2edb32796, 0x1cf37af6eab4ed97, 0x1533eacf819c878e, + 0xc700fc7e2a482abe, 0x4d1c62a63d917682, 0x89141558095c3228, 0x029bb05df0b8f121, + 0xa239e00b24ba9b5b, 0x74c3c55d5051f35f, 0x2f45200123860c7d, 0x4fabf224d27abaf1, + 0x0acb80fbf7ed2d86, 0x87db455a8bee03ce, 0x980bbbd1afa8fac6, 0x9d9ee6515ded4930, + 0x4c62a05dae0f744b, 0x69ff90e2839348c9, 0xda141e6d351e42da, 0x178cd58f72bf5118, + ]; + let q_inv: [u64; 32] = [ + 0x5792505b857d3e8d, 0x8a13922b1240c0d2, 0xb5fcb8bf3df1f936, 0x74483606c2cd7ed8, + 0xd40f33bbfd9be093, 0xb5f40ed6632989f5, 0x7f2cc0cd8c8a0661, 0x87630c6b25dddeb5, + 0x7032a5af6ef7c20f, 0x90331600142e6cb9, 0x67b92645b68c6d8f, 0xb63517c7c39843cf, + 0xd50712bf8fc35882, 0x3c421e2447b1a989, 0x7a251afa7aaa6908, 0x43b4de11f99b2654, + 0x1e02735920ef48a3, 0x218fc24da34ce8f0, 0x280446e49b3b9b15, 0x8d96f07411c882bf, + 0x66e283f5d5fb0e6e, 0x0844efd28d853446, 0x5eb4def8dba57b99, 0x474111f92d19f3ab, + 0x748d7b5d94cacd4d, 0xcf634f3a07cea4b7, 0x8dbcca51f4da4379, 0x80774236a54ec9dc, + 0x6a1ef00ee582d3d1, 0xdecfb14ca1e80c8e, 0xc78af5f6c807cc99, 0x484ad86e79415ea3, + ]; + RsaPrivateComponents::::from_crt_components(&p, &q, &d_p, &d_q, &q_inv, 0x10001) + .expect("recovered CRT components must be accepted") +} + +#[test] +fn pss_shake256_sign_with_fixed_salt_round_trips() { + let sk = genuine_key(); + let pk = RsaPublicComponents::::new(sk.n(), 0x10001).unwrap(); + + let salt = [0x42u8; 64]; + let sig = sign_with_salt!(RSASSA_PSS_SHAKE256, &sk, b"the message to sign", salt) + .expect("signing must succeed"); + pk.key::() + .verify(b"the message to sign", None, &sig) + .expect("must verify"); + + let sig2 = sign_with_salt!(RSASSA_PSS_SHAKE256, &sk, b"the message to sign", salt).unwrap(); + assert_eq!(sig, sig2); + + assert!(pk.key::().verify(b"a different message", None, &sig).is_err()); +} + +#[test] +fn pss_shake256_sign_with_rng_produces_fresh_salts_that_both_verify() { + let sk = genuine_key(); + let pk = RsaPublicComponents::::new(sk.n(), 0x10001).unwrap(); + let mut rng = DefaultRNG::default(); + + let sig_a = sk + .key::() + .sign(&mut rng, b"hello", None) + .expect("signing must succeed"); + let sig_b = sk + .key::() + .sign(&mut rng, b"hello", None) + .expect("signing must succeed"); + assert_ne!(sig_a, sig_b, "PSS is randomized: two signatures of the same message must differ"); + pk.key::().verify(b"hello", None, &sig_a).expect("sig_a must verify"); + pk.key::().verify(b"hello", None, &sig_b).expect("sig_b must verify"); +} + +#[test] +fn rsa_pss_4096_shake256_wycheproof_vectors() { + let doc: Value = serde_json::from_str(&get_test_data("rsa_pss_4096_shake256_test.json")) + .expect("valid JSON"); + + let mut num_tests = 0usize; + let mut num_valid = 0usize; + let mut num_invalid = 0usize; + + for group in doc["testGroups"].as_array().unwrap() { + assert_eq!(group["sha"], "SHAKE256"); + assert_eq!(group["mgf"], "SHAKE256"); + assert_eq!(group["sLen"], 64); + let n: [u64; 64] = limbs_from_hex(group["publicKey"]["modulus"].as_str().unwrap()); + let e = u64::from_str_radix(group["publicKey"]["publicExponent"].as_str().unwrap(), 16) + .expect("publicExponent fits in u64 for every group here"); + let pk = + RsaPublicComponents::::new(&n, e).expect("group public key must be valid"); + + for test in group["tests"].as_array().unwrap() { + num_tests += 1; + let tc_id = test["tcId"].as_u64().unwrap(); + let msg = hex_decode(test["msg"].as_str().unwrap()).unwrap(); + let sig_bytes = hex_decode(test["sig"].as_str().unwrap()).unwrap(); + + let Ok(sig): Result<[u8; 512], _> = sig_bytes.try_into() else { + assert_ne!(test["result"], "valid", "tcId {tc_id}: wrong-length 'valid' signature"); + num_invalid += 1; + continue; + }; + + let verified = pk.key::().verify(&msg, None, &sig).is_ok(); + match test["result"].as_str().unwrap() { + "valid" => { + assert!(verified, "tcId {tc_id}: expected valid, got invalid"); + num_valid += 1; + } + "invalid" => { + assert!(!verified, "tcId {tc_id}: expected invalid, got valid"); + num_invalid += 1; + } + other => panic!("tcId {tc_id}: unknown result {other:?}"), + } + } + } + + assert_eq!(num_tests, 184); + assert_eq!(num_valid, 138); + assert_eq!(num_invalid, 46); +} + +// ---- bouncycastle_core trait conformance ------------------------------------------------------ + +/// The SHAKE-native generic type has had `core-test-framework`'s full suite at RSA-2048/3072 +/// (`RSASSA_PSS_SHAKE128`); this checks the RSA-4096/SHAKE256 alias's width constants by round +/// trips through `SigningKey::sign`. +#[test] +fn pss_shake256_trait_round_trips() { + let sk = genuine_key(); + let pk = RsaPublicComponents::::new(sk.n(), 0x10001).unwrap(); + let msg = b"PSS-SHAKE256 at RSA-4096, both APIs"; + let from_trait = + sk.key::().sign(&mut DefaultRNG::default(), msg, None).unwrap(); + pk.key::().verify(msg, None, &from_trait).unwrap(); + pk.key::().verify(msg, None, &from_trait).unwrap(); + let from_free = + sk.key::().sign(&mut DefaultRNG::default(), msg, None).unwrap(); + pk.key::().verify(msg, None, &from_free).unwrap(); + assert!(pk.key::().verify(b"other", None, &from_free).is_err()); +} diff --git a/crypto/rsa/tests/rsa_4096_tests.rs b/crypto/rsa/tests/rsa_4096_tests.rs new file mode 100644 index 000000000..0492cebfa --- /dev/null +++ b/crypto/rsa/tests/rsa_4096_tests.rs @@ -0,0 +1,507 @@ +//! RSA-4096 against Wycheproof: `rsa_pkcs1_4096_sig_gen_test.json` (sign), `rsa_signature_4096_ +//! sha{256,384,512}_test.json` (verify, all three hashes), and `rsa_pss_4096_sha{256,384,512} +//! _mgf1_*_test.json` (PSS verify, all three hashes -- unlike every other size in this crate, +//! Wycheproof has matching-hash-and-MGF PSS vectors for all three at 4096 bits). Only SHA-256 has +//! sig-gen key material to check signing against a known-correct output, so every other sign +//! pairing (PKCS#1 v1.5/SHA-384 and /SHA-512 signing, and PSS signing under all three hashes +//! with both an RNG-drawn and a fixed salt) is exercised by a self-consistency round trip instead, following +//! `rsa_3072_tests.rs`'s own precedent. +//! +//! `p`/`q`/`dP`/`dQ`/`qInv` were recovered from `rsa_pkcs1_4096_sig_gen_test.json`'s SHA-256 +//! group's `(n, e, d)` via the same factoring-from-d method as RSA-2048's key, cross-checked +//! against all 8 of that group's real signatures before being pasted here. + +use bouncycastle_core::errors::SignatureError; +use bouncycastle_core::hex::decode as hex_decode; +use bouncycastle_core::signature_key::{ + DeterministicOneShotSigningKey, DeterministicSigningKey, OneShotSigningKey, + OneShotVerifyingKey, SigningKey, +}; +use bouncycastle_core::traits::SignatureSigner; +use bouncycastle_core_test_framework::signature::{ + CtxBehaviour, TestFrameworkSignature, TestFrameworkSignatureKeys, +}; +use bouncycastle_rng::DefaultRNG; +use bouncycastle_rsa::RSA4096; +use bouncycastle_rsa::keys::{ + RsaPrivateComponents, RsaPrivateKey, RsaPublicComponents, RsaPublicKey, +}; +use bouncycastle_rsa::rsa_4096::{ + PK_LEN, RSASSA_PKCS1_v1_5_SHA256, RSASSA_PKCS1_v1_5_SHA384, RSASSA_PKCS1_v1_5_SHA512, + RSASSA_PSS_SHA256, RSASSA_PSS_SHA384, RSASSA_PSS_SHA512, SIG_LEN, SK_LEN, +}; +use bouncycastle_rsa::rsassa::{ + RsaDeterministicSignatureAlgorithm, RsaRandomizedSignatureAlgorithm, +}; +use serde_json::Value; +use std::fs; +use std::path::Path; + +/// Signs through the streaming trait path with a fixed salt (`set_salt`) -- the +/// deterministic PSS mode, for tests against a known salt. Returns `do_sign_final`'s `Result`. +macro_rules! sign_with_salt { + ($ty:ty, $sk:expr, $msg:expr, $salt:expr) => {{ + let sk_typed_ty = $sk.key::<$ty>(); + let mut signer = sk_typed_ty.create_signer(&mut DefaultRNG::default(), None).unwrap(); + signer.set_salt($salt); + signer.do_update($msg); + signer.do_final() + }}; +} + +const TEST_DATA_PATH_RELATIVE: &str = "../../../wycheproof/testvectors_v1"; +const TEST_DATA_PATH: &str = "../wycheproof/testvectors_v1"; + +fn get_test_data(filename: &str) -> String { + for dir in [TEST_DATA_PATH_RELATIVE, TEST_DATA_PATH] { + let path = format!("{dir}/{filename}"); + if Path::new(&path).exists() { + return fs::read_to_string(path).unwrap(); + } + } + panic!( + "wycheproof not found (looked for {filename} in {TEST_DATA_PATH_RELATIVE:?} and \ + {TEST_DATA_PATH:?}); this suite requires it rather than skipping" + ); +} + +fn limbs_from_hex(hex: &str) -> [u64; L] { + let bytes_len = 8 * L; + let mut bytes = hex_decode(hex).expect("valid hex"); + if bytes.len() == bytes_len + 1 && bytes[0] == 0 { + bytes.remove(0); + } + assert_eq!(bytes.len(), bytes_len, "expected a {}-bit value", bytes_len * 8); + let mut limbs = [0u64; L]; + for i in 0..L { + let start = bytes_len - (i + 1) * 8; + limbs[i] = u64::from_be_bytes(bytes[start..start + 8].try_into().unwrap()); + } + limbs +} + +fn genuine_key() -> RsaPrivateComponents { + let p: [u64; 32] = [ + 0x5141acd4afd4771f, 0x5857742b7e4032dc, 0xb7a9b97fe5371396, 0x4b1783c5bc91a6dc, + 0xaf5d0c912d97b728, 0xeb265a7f28b88976, 0x5e993302aa72f11d, 0xc007ad09d76ae22a, + 0x44cbb87b8bec8fd3, 0xf152f15c73b95ac5, 0x8dbdad655fbbad20, 0x59855d0de1c794ac, + 0x4c6060926d878a20, 0xf38860474e44993d, 0x177a91caeef98b13, 0xd1676123544d3def, + 0xc1673063d8487390, 0xfedd55ba2e233a6d, 0x016a5735b883c639, 0xbd813f9fb752805b, + 0x923a7b775b5ffaff, 0xb174e55ca6a12c21, 0x0373077895a6934a, 0x6b725388f54ffea3, + 0x953c09104e1fd2d3, 0x9114f39017871528, 0x33918eb72b786b3c, 0xf43b8626af13d14a, + 0x886a0904eb486140, 0x0037409b81f3a5b3, 0x19e44e26140d2ede, 0xc3c677495c2bd566, + ]; + let q: [u64; 32] = [ + 0xee0745546a6a1c73, 0x8b1050436d882425, 0xdc2e7872ce6fb2b7, 0xf98671ee4899050b, + 0x796a5dd847400804, 0x9ba1f51132355792, 0xc39066a9fc27985b, 0x81f4bca5d15e0962, + 0x6a46cf6dbb6d2ad9, 0xdf3d085ae7693b7e, 0xf58e3c750b6d978a, 0xb52b9000d3a7aab1, + 0xdbb07e23bce1960c, 0x4e291b5c8ddaa6a7, 0x0544a7a7cb3f0792, 0xc695e324fbb11beb, + 0xbded418507f2f175, 0x49fe5f47737ff436, 0xeb37f85b7554d7ad, 0x724d042aef25cea2, + 0xeadbd11dcd2fec7b, 0xb50812705b379f5d, 0xfc50fa98fb67b746, 0x16f2bdf5964b26c7, + 0xcc1c817507859246, 0x6810c2136ad81b16, 0xd7bc78d637e17e0e, 0x6882825347455782, + 0xcdb615d921f5e705, 0x0a982efbe6658e6b, 0x59e96686f7b8752f, 0xc357cf685f9b8d4e, + ]; + let d_p: [u64; 32] = [ + 0x3cd8e91fee6bcdd3, 0x074fdc015ab1c45f, 0x34135987a2288907, 0xf6961d44dfb7505c, + 0x251be32315a85b75, 0xe8982e8493a2ae78, 0xc268493861002977, 0x140fb5806735814e, + 0x35d426d719b12c41, 0xa5f194dbbf374226, 0xa0a6c5314c1a2375, 0x66899d59c04b60c4, + 0x5158d7867dbfec94, 0xec1dde997c00125e, 0x62e5a19b2a71decf, 0x310291892c37e8a2, + 0x223e06c9521f4a45, 0xe4f08e1d5543ed74, 0xcf4dc8de58b9e9ad, 0x9167ad4f122b3263, + 0xf110dbac286712f6, 0x2db237d0f39cda5f, 0xa54b67367c857476, 0x138b37b7b1ed2219, + 0x950d9f4e82aab9bc, 0x90943e671e928e23, 0x44791809c9fcf19f, 0xc70396da054ba478, + 0x77248f6fe00e31bd, 0xf3731b1415d5f2ee, 0xf5242aa6657760cd, 0xa6bbb5460638d2b2, + ]; + let d_q: [u64; 32] = [ + 0xfa935bd36284ea6b, 0x9c255a57d6b3ac0f, 0x35b350881ec52e99, 0xf48d35dd11598957, + 0x61fee5d3763b8cfb, 0xf86f5d1936a161ae, 0x3a8b852507264ae2, 0xe558f90950a572a2, + 0x205aeb15029c95a6, 0x0fa8cf020e960c3b, 0x6a793c66abfb0963, 0xa9c7d7b391d0cbee, + 0x6310f31421e85c6b, 0xc0de89d2edb32796, 0x1cf37af6eab4ed97, 0x1533eacf819c878e, + 0xc700fc7e2a482abe, 0x4d1c62a63d917682, 0x89141558095c3228, 0x029bb05df0b8f121, + 0xa239e00b24ba9b5b, 0x74c3c55d5051f35f, 0x2f45200123860c7d, 0x4fabf224d27abaf1, + 0x0acb80fbf7ed2d86, 0x87db455a8bee03ce, 0x980bbbd1afa8fac6, 0x9d9ee6515ded4930, + 0x4c62a05dae0f744b, 0x69ff90e2839348c9, 0xda141e6d351e42da, 0x178cd58f72bf5118, + ]; + let q_inv: [u64; 32] = [ + 0x5792505b857d3e8d, 0x8a13922b1240c0d2, 0xb5fcb8bf3df1f936, 0x74483606c2cd7ed8, + 0xd40f33bbfd9be093, 0xb5f40ed6632989f5, 0x7f2cc0cd8c8a0661, 0x87630c6b25dddeb5, + 0x7032a5af6ef7c20f, 0x90331600142e6cb9, 0x67b92645b68c6d8f, 0xb63517c7c39843cf, + 0xd50712bf8fc35882, 0x3c421e2447b1a989, 0x7a251afa7aaa6908, 0x43b4de11f99b2654, + 0x1e02735920ef48a3, 0x218fc24da34ce8f0, 0x280446e49b3b9b15, 0x8d96f07411c882bf, + 0x66e283f5d5fb0e6e, 0x0844efd28d853446, 0x5eb4def8dba57b99, 0x474111f92d19f3ab, + 0x748d7b5d94cacd4d, 0xcf634f3a07cea4b7, 0x8dbcca51f4da4379, 0x80774236a54ec9dc, + 0x6a1ef00ee582d3d1, 0xdecfb14ca1e80c8e, 0xc78af5f6c807cc99, 0x484ad86e79415ea3, + ]; + RsaPrivateComponents::::from_crt_components(&p, &q, &d_p, &d_q, &q_inv, 0x10001) + .expect("recovered CRT components must be accepted") +} + +#[test] +fn pkcs1_v1_5_sig_gen_4096_sha256() { + let sk = genuine_key(); + let doc: Value = + serde_json::from_str(&get_test_data("rsa_pkcs1_4096_sig_gen_test.json")).unwrap(); + let group = doc["testGroups"] + .as_array() + .unwrap() + .iter() + .find(|g| g["sha"] == "SHA-256") + .expect("the SHA-256/4096 group"); + + let mut num_tests = 0usize; + for test in group["tests"].as_array().unwrap() { + num_tests += 1; + let tc_id = test["tcId"].as_u64().unwrap(); + let msg = hex_decode(test["msg"].as_str().unwrap()).unwrap(); + let expected_sig = hex_decode(test["sig"].as_str().unwrap()).unwrap(); + let sig = sk + .key::() + .sign_deterministic(&msg, None) + .unwrap_or_else(|e| { + panic!("tcId {tc_id}: signing failed: {e:?}"); + }); + assert_eq!(sig.to_vec(), expected_sig, "tcId {tc_id}: signature mismatch"); + } + assert_eq!(num_tests, 8); +} + +/// Mutation testing found that PKCS#1 v1.5/SHA-384 and /SHA-512 signing were never called by any test at +/// this modulus size (the real Wycheproof verify vectors below only exercise `verify`, and only +/// SHA-256 has a sig-gen file to sign against): a whole-function-body mutant replacing either sign +/// function with a constant still passed the whole suite. +#[test] +fn pkcs1_v1_5_sha384_and_sha512_round_trip() { + let sk = genuine_key(); + let pk = RsaPublicComponents::::new(sk.n(), 0x10001).unwrap(); + let sig384 = sk.key::().sign_deterministic(b"hello", None).unwrap(); + pk.key::().verify(b"hello", None, &sig384).unwrap(); + let sig512 = sk.key::().sign_deterministic(b"hello", None).unwrap(); + pk.key::().verify(b"hello", None, &sig512).unwrap(); +} + +fn run_pkcs1_v1_5_verify_vectors( + filename: &str, + verify: impl Fn(&RsaPublicComponents, &[u8], &[u8; 512]) -> bool, + expected_sha: &str, + expected_valid: usize, + expected_invalid: usize, +) { + let doc: Value = serde_json::from_str(&get_test_data(filename)).expect("valid JSON"); + let mut num_valid = 0usize; + let mut num_invalid = 0usize; + let mut num_missing_null = 0usize; + + for group in doc["testGroups"].as_array().unwrap() { + assert_eq!(group["sha"], expected_sha); + let n: [u64; 64] = limbs_from_hex(group["publicKey"]["modulus"].as_str().unwrap()); + let e = u64::from_str_radix(group["publicKey"]["publicExponent"].as_str().unwrap(), 16) + .unwrap(); + let pk = RsaPublicComponents::::new(&n, e).unwrap(); + + for test in group["tests"].as_array().unwrap() { + let tc_id = test["tcId"].as_u64().unwrap(); + let msg = hex_decode(test["msg"].as_str().unwrap()).unwrap(); + let sig_bytes = hex_decode(test["sig"].as_str().unwrap()).unwrap(); + let flags: Vec<&str> = + test["flags"].as_array().unwrap().iter().map(|f| f.as_str().unwrap()).collect(); + + let Ok(sig): Result<[u8; 512], _> = sig_bytes.try_into() else { + assert_ne!(test["result"], "valid"); + num_invalid += 1; + continue; + }; + let verified = verify(&pk, &msg, &sig); + match test["result"].as_str().unwrap() { + "valid" => { + assert!(verified, "tcId {tc_id}: expected valid, got invalid"); + num_valid += 1; + } + "invalid" => { + assert!(!verified, "tcId {tc_id}: expected invalid, got valid"); + num_invalid += 1; + } + "acceptable" => { + assert_eq!(flags, vec!["MissingNull"], "tcId {tc_id}: unreviewed acceptable"); + assert!(verified); + num_missing_null += 1; + } + other => panic!("tcId {tc_id}: unknown result {other:?}"), + } + } + } + assert_eq!(num_missing_null, 1); + assert_eq!(num_valid, expected_valid, "for {filename}"); + assert_eq!(num_invalid, expected_invalid, "for {filename}"); +} + +#[test] +fn rsa_signature_4096_sha256_wycheproof_vectors() { + run_pkcs1_v1_5_verify_vectors( + "rsa_signature_4096_sha256_test.json", + |pk, msg, sig| pk.key::().verify(msg, None, sig).is_ok(), + "SHA-256", + 7, + 250, + ); +} + +#[test] +fn rsa_signature_4096_sha384_wycheproof_vectors() { + run_pkcs1_v1_5_verify_vectors( + "rsa_signature_4096_sha384_test.json", + |pk, msg, sig| pk.key::().verify(msg, None, sig).is_ok(), + "SHA-384", + 7, + 251, + ); +} + +#[test] +fn rsa_signature_4096_sha512_wycheproof_vectors() { + run_pkcs1_v1_5_verify_vectors( + "rsa_signature_4096_sha512_test.json", + |pk, msg, sig| pk.key::().verify(msg, None, sig).is_ok(), + "SHA-512", + 7, + 251, + ); +} + +fn run_pss_verify_vectors( + filename: &str, + verify: impl Fn(&RsaPublicComponents, &[u8], &[u8; 512]) -> bool, + expected_sha: &str, + expected_slen: u64, + expected_valid: usize, + expected_invalid: usize, +) { + let doc: Value = serde_json::from_str(&get_test_data(filename)).expect("valid JSON"); + let mut num_valid = 0usize; + let mut num_invalid = 0usize; + + for group in doc["testGroups"].as_array().unwrap() { + assert_eq!(group["sha"], expected_sha); + assert_eq!(group["mgfSha"], expected_sha); + assert_eq!(group["sLen"], expected_slen); + let n: [u64; 64] = limbs_from_hex(group["publicKey"]["modulus"].as_str().unwrap()); + let e = u64::from_str_radix(group["publicKey"]["publicExponent"].as_str().unwrap(), 16) + .unwrap(); + let pk = RsaPublicComponents::::new(&n, e).unwrap(); + + for test in group["tests"].as_array().unwrap() { + let tc_id = test["tcId"].as_u64().unwrap(); + let msg = hex_decode(test["msg"].as_str().unwrap()).unwrap(); + let sig_bytes = hex_decode(test["sig"].as_str().unwrap()).unwrap(); + let Ok(sig): Result<[u8; 512], _> = sig_bytes.try_into() else { + assert_ne!(test["result"], "valid"); + num_invalid += 1; + continue; + }; + let verified = verify(&pk, &msg, &sig); + match test["result"].as_str().unwrap() { + "valid" => { + assert!(verified, "tcId {tc_id}: expected valid"); + num_valid += 1; + } + "invalid" => { + assert!(!verified, "tcId {tc_id}: expected invalid"); + num_invalid += 1; + } + other => panic!("unknown result {other:?}"), + } + } + } + assert_eq!(num_valid, expected_valid, "for {filename}"); + assert_eq!(num_invalid, expected_invalid, "for {filename}"); +} + +#[test] +fn rsa_pss_4096_sha256_mgf1_32_wycheproof_vectors() { + run_pss_verify_vectors( + "rsa_pss_4096_sha256_mgf1_32_test.json", + |pk, msg, sig| pk.key::().verify(msg, None, sig).is_ok(), + "SHA-256", + 32, + 63, + 45, + ); +} + +#[test] +fn rsa_pss_4096_sha384_mgf1_48_wycheproof_vectors() { + run_pss_verify_vectors( + "rsa_pss_4096_sha384_mgf1_48_test.json", + |pk, msg, sig| pk.key::().verify(msg, None, sig).is_ok(), + "SHA-384", + 48, + 95, + 46, + ); +} + +#[test] +fn rsa_pss_4096_sha512_mgf1_64_wycheproof_vectors() { + run_pss_verify_vectors( + "rsa_pss_4096_sha512_mgf1_64_test.json", + |pk, msg, sig| pk.key::().verify(msg, None, sig).is_ok(), + "SHA-512", + 64, + 132, + 47, + ); +} + +/// Mutation testing found that none of the six PSS signing paths (three hashes, RNG-drawn or fixed salt) +/// were ever called at this modulus size: the real Wycheproof PSS vectors above only exercise +/// `verify` (against externally-sourced signatures), so a whole-function-body mutant replacing any +/// sign function with a constant still passed the whole suite. One fixed-salt-round-trip-plus- +/// rejection test and one RNG-freshness test per hash, matching +/// `rsa_2048_pss_sha384_sha512_tests.rs`'s shape, calls each function at least once. +#[test] +fn pss_sha256_fixed_salt_round_trips() { + let sk = genuine_key(); + let pk = RsaPublicComponents::::new(sk.n(), 0x10001).unwrap(); + let salt = [0x22u8; 32]; + let sig = + sign_with_salt!(RSASSA_PSS_SHA256, &sk, b"hello", salt).expect("signing must succeed"); + pk.key::().verify(b"hello", None, &sig).expect("must verify"); + assert!(pk.key::().verify(b"goodbye", None, &sig).is_err()); +} + +#[test] +fn pss_sha256_rng_produces_fresh_salts_that_both_verify() { + let sk = genuine_key(); + let pk = RsaPublicComponents::::new(sk.n(), 0x10001).unwrap(); + let mut rng = DefaultRNG::default(); + let sig_a = + sk.key::().sign(&mut rng, b"hello", None).expect("signing must succeed"); + let sig_b = + sk.key::().sign(&mut rng, b"hello", None).expect("signing must succeed"); + assert_ne!(sig_a, sig_b, "PSS is randomized: two signatures of the same message must differ"); + pk.key::().verify(b"hello", None, &sig_a).expect("sig_a must verify"); + pk.key::().verify(b"hello", None, &sig_b).expect("sig_b must verify"); +} + +#[test] +fn pss_sha384_fixed_salt_round_trips() { + let sk = genuine_key(); + let pk = RsaPublicComponents::::new(sk.n(), 0x10001).unwrap(); + let salt = [0x11u8; 48]; + let sig = + sign_with_salt!(RSASSA_PSS_SHA384, &sk, b"hello", salt).expect("signing must succeed"); + pk.key::().verify(b"hello", None, &sig).expect("must verify"); + assert!(pk.key::().verify(b"goodbye", None, &sig).is_err()); +} + +#[test] +fn pss_sha384_rng_produces_fresh_salts_that_both_verify() { + let sk = genuine_key(); + let pk = RsaPublicComponents::::new(sk.n(), 0x10001).unwrap(); + let mut rng = DefaultRNG::default(); + let sig_a = + sk.key::().sign(&mut rng, b"hello", None).expect("signing must succeed"); + let sig_b = + sk.key::().sign(&mut rng, b"hello", None).expect("signing must succeed"); + assert_ne!(sig_a, sig_b, "PSS is randomized: two signatures of the same message must differ"); + pk.key::().verify(b"hello", None, &sig_a).expect("sig_a must verify"); + pk.key::().verify(b"hello", None, &sig_b).expect("sig_b must verify"); +} + +#[test] +fn pss_sha512_fixed_salt_round_trips() { + let sk = genuine_key(); + let pk = RsaPublicComponents::::new(sk.n(), 0x10001).unwrap(); + let salt = [0x33u8; 64]; + let sig = + sign_with_salt!(RSASSA_PSS_SHA512, &sk, b"hello", salt).expect("signing must succeed"); + pk.key::().verify(b"hello", None, &sig).expect("must verify"); + assert!(pk.key::().verify(b"goodbye", None, &sig).is_err()); +} + +#[test] +fn pss_sha512_rng_produces_fresh_salts_that_both_verify() { + let sk = genuine_key(); + let pk = RsaPublicComponents::::new(sk.n(), 0x10001).unwrap(); + let mut rng = DefaultRNG::default(); + let sig_a = + sk.key::().sign(&mut rng, b"hello", None).expect("signing must succeed"); + let sig_b = + sk.key::().sign(&mut rng, b"hello", None).expect("signing must succeed"); + assert_ne!(sig_a, sig_b, "PSS is randomized: two signatures of the same message must differ"); + pk.key::().verify(b"hello", None, &sig_a).expect("sig_a must verify"); + pk.key::().verify(b"hello", None, &sig_b).expect("sig_b must verify"); +} + +// ---- bouncycastle_core trait conformance ------------------------------------------------------ + +fn fixed_keypair() +-> Result<(RsaPublicComponents, RsaPrivateComponents), SignatureError> { + let sk = genuine_key(); + let pk = RsaPublicComponents::::new(sk.n(), 0x10001)?; + Ok((pk, sk)) +} + +/// `core-test-framework`'s full conformance suite for one deterministic and one randomized +/// pairing at this width. An RSA-4096 private-key operation is slow enough in a debug build that +/// the suite's dozen signatures per pairing add up, so the remaining pairings get +/// [`trait_round_trip`] instead: the generic code they share has already had the full suite at +/// RSA-2048 and RSA-3072, and only this size's width constants are new. +#[test] +fn sha256_trait_conformance_suites() { + TestFrameworkSignature::with_ctx_behaviour(CtxBehaviour::Refused).test_deterministic_signature::, RsaPrivateKey, SIG_LEN>( + || fixed_keypair().map(|(pk, sk)| (pk.into_key::(), sk.into_key::())), false); + TestFrameworkSignature::with_ctx_behaviour(CtxBehaviour::Refused) + .test_signature::, RsaPrivateKey, SIG_LEN>( + || fixed_keypair().map(|(pk, sk)| (pk.into_key::(), sk.into_key::())), false, + ); +} + +#[test] +fn key_trait_boundary_conditions() { + TestFrameworkSignatureKeys::new() + .test_keys::, RsaPrivateKey, PK_LEN, SK_LEN>( + || fixed_keypair().map(|(pk, sk)| (pk.into_key::(), sk.into_key::())), + ); +} + +/// Sign one-shot and streamed, verify both, and reject a different message -- what a wrong width +/// constant in this size's aliases would break. PSS, through `SigningKey`. +fn pss_round_trip>( + pk: &RsaPublicComponents, + sk: &RsaPrivateComponents, +) { + let msg = b"RSA-4096 trait round trip"; + let mut rng = DefaultRNG::default(); + let sig = sk.key::().sign(&mut rng, msg, None).unwrap(); + pk.key::().verify(msg, None, &sig).unwrap(); + let sk_typed_a = sk.key::(); + let mut signer = sk_typed_a.create_signer(&mut rng, None).unwrap(); + signer.do_update(&msg[..8]); + signer.do_update(&msg[8..]); + pk.key::().verify(msg, None, &signer.do_final().unwrap()).unwrap(); + assert!(pk.key::().verify(b"a different message", None, &sig).is_err()); +} + +/// As [`pss_round_trip`], for PKCS#1 v1.5 through `DeterministicSigningKey`. +fn pkcs1_round_trip>( + pk: &RsaPublicComponents, + sk: &RsaPrivateComponents, +) { + let msg = b"RSA-4096 trait round trip"; + let sig = sk.key::().sign_deterministic(msg, None).unwrap(); + pk.key::().verify(msg, None, &sig).unwrap(); + let sk_typed_a = sk.key::(); + let mut signer = sk_typed_a.create_signer_deterministic(None).unwrap(); + signer.do_update(&msg[..8]); + signer.do_update(&msg[8..]); + assert_eq!(signer.do_final().unwrap(), sig); + assert!(pk.key::().verify(b"a different message", None, &sig).is_err()); +} + +#[test] +fn remaining_pairings_trait_round_trips() { + let (pk, sk) = fixed_keypair().unwrap(); + pkcs1_round_trip::(&pk, &sk); + pkcs1_round_trip::(&pk, &sk); + pss_round_trip::(&pk, &sk); + pss_round_trip::(&pk, &sk); +} diff --git a/crypto/rsa/tests/rsa_8192_tests.rs b/crypto/rsa/tests/rsa_8192_tests.rs new file mode 100644 index 000000000..51f437775 --- /dev/null +++ b/crypto/rsa/tests/rsa_8192_tests.rs @@ -0,0 +1,478 @@ +//! RSA-8192. Wycheproof has no `rsa_pkcs1_8192_sig_gen_test.json` and no matching-hash-and-MGF +//! PSS vector file at this size, so there is no real key to recover the way every smaller size in +//! this crate uses. Two independent checks stand in for that: +//! +//! 1. **BC Java cross-check.** A fresh 8192-bit keypair (two independently generated, +//! Miller-Rabin-tested 4096-bit primes, `e = 65537`) was fed to BC Java's own RSA +//! (`java.security.Signature` via the `BC` provider, `SHA{256,384,512}withRSA` and +//! `SHA{256,384,512}withRSAandMGF1`) as an `RSAPrivateCrtKeySpec`, signing the UTF-8 bytes of +//! `"hello"`. PKCS#1 v1.5 is deterministic, so its three signatures are checked here byte for +//! byte against this crate's own PKCS#1 v1.5 signing (SHA-256/384/512); PSS is randomized, so its +//! three signatures (BC Java's default PSS: salt length equal to the digest length, matching +//! this crate's own convention) are instead checked with this crate's own +//! PSS verifier, a genuine independent-implementation cross-check even though +//! it cannot be a byte-for-byte one. +//! 2. **Real Wycheproof verify vectors.** `rsa_signature_8192_sha{256,384,512}_test.json` exist +//! (verify-only, with their own unrelated key) and are run in full, 258 or 259 vectors each. + +use bouncycastle_core::errors::SignatureError; +use bouncycastle_core::hex::decode as hex_decode; +use bouncycastle_core::signature_key::{ + DeterministicOneShotSigningKey, DeterministicSigningKey, OneShotSigningKey, + OneShotVerifyingKey, SigningKey, +}; +use bouncycastle_core::traits::SignatureSigner; +use bouncycastle_core_test_framework::signature::{ + CtxBehaviour, TestFrameworkSignature, TestFrameworkSignatureKeys, +}; +use bouncycastle_rng::DefaultRNG; +use bouncycastle_rsa::RSA8192; +use bouncycastle_rsa::keys::{ + RsaPrivateComponents, RsaPrivateKey, RsaPublicComponents, RsaPublicKey, +}; +use bouncycastle_rsa::rsa_8192::{ + PK_LEN, RSASSA_PKCS1_v1_5_SHA256, RSASSA_PKCS1_v1_5_SHA384, RSASSA_PKCS1_v1_5_SHA512, + RSASSA_PSS_SHA256, RSASSA_PSS_SHA384, RSASSA_PSS_SHA512, SIG_LEN, SK_LEN, +}; +use bouncycastle_rsa::rsassa::{ + RsaDeterministicSignatureAlgorithm, RsaRandomizedSignatureAlgorithm, +}; +use serde_json::Value; +use std::fs; +use std::path::Path; + +/// Signs through the streaming trait path with a fixed salt (`set_salt`) -- the +/// deterministic PSS mode, for tests against a known salt. Returns `do_sign_final`'s `Result`. +macro_rules! sign_with_salt { + ($ty:ty, $sk:expr, $msg:expr, $salt:expr) => {{ + let sk_typed_ty = $sk.key::<$ty>(); + let mut signer = sk_typed_ty.create_signer(&mut DefaultRNG::default(), None).unwrap(); + signer.set_salt($salt); + signer.do_update($msg); + signer.do_final() + }}; +} + +const TEST_DATA_PATH_RELATIVE: &str = "../../../wycheproof/testvectors_v1"; +const TEST_DATA_PATH: &str = "../wycheproof/testvectors_v1"; + +fn get_test_data(filename: &str) -> String { + for dir in [TEST_DATA_PATH_RELATIVE, TEST_DATA_PATH] { + let path = format!("{dir}/{filename}"); + if Path::new(&path).exists() { + return fs::read_to_string(path).unwrap(); + } + } + panic!( + "wycheproof not found (looked for {filename} in {TEST_DATA_PATH_RELATIVE:?} and \ + {TEST_DATA_PATH:?}); this suite requires it rather than skipping" + ); +} + +fn limbs_from_hex(hex: &str) -> [u64; L] { + let bytes_len = 8 * L; + let mut bytes = hex_decode(hex).expect("valid hex"); + if bytes.len() == bytes_len + 1 && bytes[0] == 0 { + bytes.remove(0); + } + assert_eq!(bytes.len(), bytes_len, "expected a {}-bit value", bytes_len * 8); + let mut limbs = [0u64; L]; + for i in 0..L { + let start = bytes_len - (i + 1) * 8; + limbs[i] = u64::from_be_bytes(bytes[start..start + 8].try_into().unwrap()); + } + limbs +} + +/// The fresh, self-generated key used for the BC Java cross-check and for self-consistency. +fn genuine_key() -> RsaPrivateComponents { + let p: [u64; 64] = [ + 0xa9a87892c469b1e5, 0x038c3f4efcb198ac, 0xed4f14df1b8a1e1f, 0xef2330d78ee73020, + 0xd3093ddaf276904c, 0x94a438d69aeaff23, 0x48dbb3d700ad58ed, 0xbbd763b5346ff916, + 0xea402fb475938e3e, 0xcaed4c45c543aff3, 0xc0954c4255b90f57, 0x2fe6242da64a5099, + 0x3fd54a6b6175342c, 0xdf8dd0187588abbd, 0x4abc11d33376e220, 0x90d3482c7fc1397d, + 0xde925fb5a2cb1e7e, 0x062e99dfbd3c790b, 0x243ef703c0912a1e, 0x91ee31a02ef1a02e, + 0x13b19d3960842877, 0xc6e8036e26c4a339, 0xf2606f45a73314c9, 0x5dfe4c6dd0aa04ee, + 0x1385bfde55204d94, 0x454123829d28200d, 0x18a3d86f516f2a50, 0xcbe5e841cd2fdb17, + 0xc86825aae3031a2c, 0xf4726a6681852b6e, 0x3f16b45a496eee29, 0xd5c4b2319abff492, + 0x71077736745aee55, 0x72586dba7b765bbe, 0x681813f6851efdce, 0x196c13fa6d6781d2, + 0x4712ba3eb0734e43, 0xde2a9a8da6da8340, 0xc2f93a2af8ffbaaa, 0x4db552ab82a577ae, + 0x07c075eb13064f67, 0x818a7d0b31680682, 0xa58320f732d69460, 0xa5922479f4aaf594, + 0x4d545baa4cd73f39, 0xa20c87a2660869c4, 0x8350211511fe7d7a, 0x50174a372234ba89, + 0x6eefd36b20bd1ce7, 0x07d124cb61d25c8b, 0x7356e6380041dcd5, 0x6a7c98caab76211a, + 0x61ff7eaac65f815d, 0x1167dc0b28f418b3, 0x9fc8bf056efe8677, 0xf5ce4481e1670e10, + 0x6ae488da222292de, 0xcc786e194ea84d2a, 0x41b134cb6a8ae4f5, 0x870ff94b064466b7, + 0xc82ad608c14a9385, 0x5338550ac9d3f96d, 0xdce87e0d41f1ba9d, 0xef9beedb39920589, + ]; + let q: [u64; 64] = [ + 0x08798e2dd82b7d9f, 0x30208e668897171d, 0x8f73c28d70144ec6, 0x66f64ce7d2402ae0, + 0xdbc26c601d5cc3a3, 0x657176891201beee, 0x692812d7b9b796c5, 0xae27fa9062406a23, + 0x7b4e6ee5b4d2d22f, 0xd846e0e8fbeb0108, 0x52ca75d6866b780b, 0x2620152d7bb490c0, + 0xdca773f826ba9118, 0xb308499a61d0a4eb, 0x44ba0f58bff07ed5, 0x268483fe5829eb5c, + 0x02e7f0c1d3ee3856, 0x76eae3a004d0f37a, 0x99d9cb3aab5b3f1f, 0x0c9f76678a44f2c4, + 0xc82ba3f75883e512, 0x57719c85e8888746, 0x63c967ca1b81cf17, 0x6f4942a86e96bb6a, + 0x614105324fdb77ae, 0xdb6a0c777f7a4bbc, 0x184bf293127472d5, 0xc26798126a967a8f, + 0x45fa10ccadd5ef6e, 0x13cacbbf5cbc2722, 0x23b4e2f2d18785fd, 0x83a4d39485ad254b, + 0x3a096f5ddd674174, 0x6df8f2ed81ae9e7e, 0x77ee2d29fb78201d, 0x4b4c10c9ac8853eb, + 0x35690c51d0ff6208, 0x8de9a271cb50aa59, 0x51b0701f8cdd1505, 0x4cb715c9b578c63b, + 0x3c9b35776d94c3c7, 0xe952d6a7c34a2abb, 0xc432f1fcc2a5105f, 0x4f7f23a62cea2f81, + 0xfa507889f33eedd9, 0x7e37e435cb776085, 0x576b2ad8a4f39820, 0x0a85d1466d55ad69, + 0xb1dee047621be714, 0x216c6b3c1c945527, 0xe6298f6e1575e39e, 0xdd16506432adc399, + 0xc1c065319c823d2e, 0xf2d6f25d6f34a582, 0x75d6801f595c50fc, 0xccfcd556c20e1130, + 0xa24e6a1396173d85, 0xe2cbc5218657c80a, 0xe7bec5bf5a944815, 0x656f5fa54bf06f6c, + 0x7b68b002b0ea62d7, 0xa2eb84753d291781, 0xdd329e1ce00c2087, 0xcdb932d13e38ee0a, + ]; + let d_p: [u64; 64] = [ + 0x848c4d06bcab4c19, 0x2fa349116ae2bfd6, 0xcf9ea12f426f7eb3, 0xfa71d15136d85dff, + 0xc3e3a026e3968f1f, 0xd50f8056de82a33e, 0x68213465c1b3b2d7, 0x426387f62ee9c62e, + 0xeb14efe18920a873, 0xf3c385a60c9dc86c, 0x294ffd8852c4d95e, 0x940d14b53927fef5, + 0x3f709e3b4c8390c3, 0x3b9737d39c42994b, 0x5c02182c4dac78fe, 0x3b6b7c01fe0a0737, + 0x7adeedf6194f6d2c, 0x43c30f449d8ae36c, 0xb88cebf30dac95d4, 0x09fc3d623b8ceb6b, + 0x5d28293b759f2b09, 0xd350dee095846993, 0x1b323dc92b794164, 0xe19d52f0e7ef34bb, + 0x5ff017da15232c02, 0x58fa8d3b24b82973, 0x1c8aed916227e53f, 0xad49cd8938c909d4, + 0xc3d98be0501534a1, 0x91cec83019bd5bb6, 0x985b814d838ffdd2, 0x11df5cb357c86888, + 0xbc0d5590336b8dcf, 0xc25fa85b1912ac66, 0x390c8752384cadef, 0x07b54e62df65825a, + 0x7f7ad57e592cfc3b, 0xed1b7f53d6fe2a09, 0x41d9e577118adb13, 0xb6706780ace45139, + 0xbfbaadef8d19443b, 0x3dc42a1dccca1d87, 0xdb8a72a8ca8d4de7, 0xe10dec18507dbc43, + 0x66343911cfeb0313, 0xd29def907cf51b72, 0x998add714f12ef6f, 0x1c394a4b8053f8ec, + 0x46e0b76d81a07852, 0x498c3f81cb9f2b8d, 0x8fd0019a024e19be, 0xf2d405423b1d94e4, + 0x29ce52d9c49ff544, 0xd72643a03a2f9053, 0x1be76a355cfa02d2, 0x8db921cec169edf6, + 0x728f91a0f7d9dc15, 0xe34e3a4f3d41d26d, 0xab0a691f05332eb8, 0xb6241cc75fd5ee1b, + 0x5b8582afd5c1acda, 0xe405bceba411da3e, 0xd849aacac396ef0e, 0x57b5a6ebccd92cf9, + ]; + let d_q: [u64; 64] = [ + 0x77a312e8aa49ed35, 0x3bdc007b0396dd44, 0x187af52b1d2d6e88, 0x7d84fae3e1b134fa, + 0xb1af50faa281bf7d, 0xf868401279f57864, 0x1dba1e456f88eb01, 0xe2ee28d0f43ba792, + 0x3450781c72a68626, 0x30757ab4889c0c41, 0x7f34c53326389381, 0xa28e969fda4bc5e4, + 0x0ed664e6b7a53062, 0xfc9ad2c9c2bd3cf2, 0x1a7bb5627d58e8ba, 0x68b8c4da5a5a5104, + 0x5a0e586f0ebe7967, 0x2dcff7ca08c9b702, 0x89a724facd778478, 0x027fe07b2ad90a40, + 0xd2f67b0b487433d5, 0x28d451f2f0eaa3ad, 0xee8d5d55700c24ca, 0x584202d4e805a701, + 0xa1c40f0ed77d96a5, 0xc4055e480f1674ba, 0xf9fb2aeb561bf104, 0x6b846fe9ef936161, + 0x128295b5f01cf2ad, 0x4aaff225e483b5dd, 0x7cba43b61174a21c, 0xf68f9c7b4474bcbd, + 0xc8979d3dd627346e, 0x9c2b543e42af83ed, 0x221d3779bb596a50, 0xac4d7c5545e7c88b, + 0xa44c83a4cb2ffe15, 0x414d71c3a67b3563, 0xe22dd5c34f66bf5e, 0x6a9cd6374f4513e7, + 0x27765c4e3c8ee4d5, 0xf632603a9e123d3f, 0x748b0b2d39fcb6bd, 0x0bde2fc8edf891e6, + 0xded2b9cf10705222, 0xe5ca5d358eb8067a, 0x23368f3218b1bd0c, 0xe41d6519183900d0, + 0x36d90382237f0987, 0x858624f4663a543a, 0x2309265e924e5f4c, 0xfc548ae0263785e8, + 0xe010d5d5e76f3406, 0x963cc28c4228ff36, 0x4245a573c17ac537, 0x7e9ab38877e4d606, + 0xc69b8cfcee4fba17, 0xe127881203d02766, 0xf3b33254ff10a7b7, 0x4df7b087512a53dd, + 0x28ffecc1c7a3ee5d, 0x4c693f99aa4b22b7, 0x498cdaef4c3d1223, 0x78c24ba834042b07, + ]; + let q_inv: [u64; 64] = [ + 0xd87df1de9c759f36, 0x3ee1b8b22c8eab2d, 0xd6098595c2696717, 0xa922e4722b8304de, + 0x424bec1c55c1db54, 0x918f2f8bf0ac261a, 0x1e190b2089185564, 0xc0dedbfc6ee606bb, + 0x1d1d701caca565c9, 0x2d735f7a1c5b9d67, 0x8339684f656205db, 0xc2dc06896727d9ce, + 0x6c8d6fe334141d31, 0x5245e157c87cd8b4, 0x4975b68eb2eaad9a, 0xfbc3389ffb0e788d, + 0x5e9a45250d135847, 0x676e7e6a128cfa88, 0x74341d8b28dcbcb8, 0x8f7d07f37a0490e0, + 0x83a0eae9ecc99a0e, 0xa8188892180dc052, 0x3cd79e1eea7809cb, 0x3bcc1d769d917b24, + 0x1d8dc8edc7268e8d, 0x3ce2707055f522ca, 0x163ead0ca2eb5fee, 0xf147fb695aa70022, + 0xab406a6c89161f7d, 0x8fbbfe117a95f46e, 0xa16d4e65396165bd, 0xb54f52ab1bb357e5, + 0x67cdec7b6a349ed9, 0x303875e0d97cf3fa, 0x0af9378ecb114fd8, 0x4ada6f45b9d6b1df, + 0x9ef2cf55de53d0ed, 0x33e4c2070b165b52, 0x3feddf0f7a1158c0, 0x91463a2b1952e83a, + 0x65a9db73de55ef6b, 0x8e18c716a69a9a6a, 0x0ca44356ca6e2898, 0x7df214b19f2114f1, + 0x9af2aee9d5cf1077, 0x22fc8b019fd3d0ff, 0x50c6eead29ab18cd, 0xa7e6621f8eae45fe, + 0x588bde2d99b8692d, 0x339be0a07b4f0a7b, 0xcbdbdcc8717105d2, 0x78bbd3e3392a503e, + 0xb868f9db1cf14f74, 0x52f3dc7f028c9f7e, 0xa3629e034b453834, 0x52bab134f3ae91a2, + 0xd1aac2fe108f98c0, 0x1e799537a42b3060, 0xdbcce6fc287e449b, 0x1985969e5afbc524, + 0x61ba61f820f83597, 0x65c8523f0767bccc, 0xde04e1644a214f9a, 0x9748f8d853be7131, + ]; + RsaPrivateComponents::::from_crt_components(&p, &q, &d_p, &d_q, &q_inv, 0x10001) + .expect("self-generated CRT components must be accepted") +} + +const BC_JAVA_SHA256_SIG: &str = "be0dceec05a9aeff34565a9c7e9d2a63f9407d1f17e9786d45b49ee04d872155710b0d2aa4974398fa9b31ab0c61d0fe207fea57d7878736fa05ca44d22cb7d101b8e15d7a1d60c44bd394048d1ba988f351e3c780857a761d6f8a78bbaa150d5e0f3dd920b9c55a6b80541d26e50b343c0c1e3e4bfade12c8d0b7827b49663d8b2ea9196793c1b46bb4128cee5012f8b045d09ab96a172b35c341eaeed6447e02d02aa47c47ba9863052202325bf0e1378b6174d69d46a97d0419861e773272e852f08231a64badc22448d1ea036376de4c2627454803b690613e2c77a0a440bf55208b55a401c1a186c48eebdf0ec386d99dbf1602417c4b6185b4323aaf4805063511e45f2b0e80d7501b54339a491739a3e8c84690648e870c2811d40e20d6eb91d0f493e41e68e5f5dacc617c152e4c8acd5693c25860bdd03f0b64ad409397f196d781e9ffb0c10499662465ca29448359d343290433187ad46d50e864bcfe60b9fa7b67bd0c269baeeed2e23bed574a41600afe8947dda16947eb505d105d11512bdfff1b4853fb65602c9c8cfcbf3a50be13ca4af99c05ba3d9598e2b1f1a174594bc9fc0828fc29ca33343a4149d6bab10fa6a5063af111871777c86fad6952e590f8fc34c7c86637df1d40914109ecdb99a17ae708089eb976228af03783fc2379ef24b45d1fc3e8b875c196cf20aead62cfa968d97899828ca8d92e62d069cc0db0139250b842379d28c0bbfb7e79c9af376b265d14b7383b4c06a4c9fa953b3b413e52c4a87e61afe9bb79dc7ae5ef0d1bbed84b33fb49e105d3a9e9b5c11c83cb6299895c000a5bb68186bb2f29c78bce0ec494edcd79557a7f94faa24c009cee9a429a5e150b9204146056b19b3cfa2527dad32a263b558d51cf0aa12e12f0b8054e83b11caf9c7a49b10cefb5e63f08612b552b335db1ff182c818beeb618f5b6c108cb35e23cea812da2ad26f0af20e4f48b1586d65a563a240d52922ead451526f982a8b6aa3855836c5f274c979fbfca225f2ba4e68b4f233e3995df5471b5716a0b979a524535fed2f6ea67824b2f37d98534f78033bc2858a5aa5179761ba5e9d8458045427cbd035e111dbc35f67c0848890236bb33c1e4bf64881cb62747c50634a008cae2bffd1fd840c2fe4aa3d428e58b741034f89b5056ebd452061b2d3019c19df65122644ead8f0b6085004e4df187f515f11b003e971898845073472878186cd307b6ae1a30c0ad7994b63591bf702d27c191386f4616b99159527de7fd6f27f1200d310011ed3bb5f8c6ec4fb73d5f2c42485cedfacab9051a44c3b81d3631376ffcc5034d33f83fed3e94421cc6413b3be7d662f9400cf7c1d61529ab4dce3db9993d38f654db3edcd143929dd5ec0ed70ba68d834f7fed79b94bb519278440f395ffe623b5b321eb81fac2f6d9ae47a1"; +const BC_JAVA_SHA384_SIG: &str = "bac97ad2bfcde4bc9793c15cad36a4bcab91534800ed5d2d2296bc8287dfbd1e529586eba90cc83bf228be988ef5533c56c8730770f4da0367ffe9eafbbe580c21a968902eab47a84498babe8182d1d36080f856f3c1a0af9bbefe4f90fb430ff82639df5e8278d28a77eab919b0b866d04942d19743c0f94a3feadc03b1c3c7b70aca244528b542e80f6e4bc04e53f6a3489c6c4d5e04e0db3d84c28c96121729b6447de494fc2f00c5441a4a6559dcd611b7f7565124e07122a9b09ffc43f60bd2ba278e780ba906050757dfd9b97acbb0d79654e9f3f2e9d0c9d87cb3767c7a83c6d74f9bd4e3066052fc35a57c074432b80fb0808328f1a6e38b1b5cc3a2826d67600b442852d26e043f5840492541aa574688393546d68d242000964e7cbbf8819b4ee5027c71f1fcc9c31667a3ff9c46f7d2d600bb437b4ea03fb2aabfe5430217021a72b26c27cd0b5933bb189f13cc6fbbab295ead06d9895c6b63063e0088549c5f1df6a6cd1bc59721ccf198034575875bbccb7c4784c6e6bf23d6a10fd2b929be9bf050939adc82ee71ad76b273e38bb2dddb262ba89d9e04257bce8c0b46329b003b5b06c4ea2bf913692caf787bcece575b8bf8744cb2add09199e9207aca80037582973412e639f4616bd588112ed65ebcec01e591edbba7985697248a0396486697e5407e29eca97b7706ea1ec66d46456013cdf8b6b761a44f62ff7a5e5537a32b8bdff134dbb9b732c5267a4a1da698997bceb25e23226efe8aca0f36c8758e1efe58c6e68dbb361732e4d2de70c8053ea9d979355bcbaeccfc44affc4406685906b377962756d5c6390993e73e2c2916400f598c5e6716ff9fe5551318096f1f1d696e00176e213a4e5ea82eadea4923e87d897e8f7829b45b94afc6bec7da169abafea907caaf5a511a99ce75ab31b8cd6c10c2fa9fc84b4fe67842c33521730fc7e18ee7fddd3e939bd5745caf28e5d56ac132da98b18772280b6d331d9702754a226dac161f8496a06c564d9a5e0a0b3496f45d7786d2f21c564a22c765cd2c79765e15fdff972873302c74ad6a346a71becc8de3e21e1a1be7198e81a05c9daeab8cb11e20099cc044c807f40222caf7125d6d0f79b4f9a6210183da8c2655e7f40bd7932024924c1bf253aad02e0d9c8ba95500fea3da66b9d0beedda9c7bb9f77da44237251d30d4d756b672c0d5f0cdb3878ead02768249276b3ef893005894299b505ba44c9a42d0c418b4907f28a374d8641cedbf65ce0022b294aafc8f8365b3c53ef2b0681be5b4ee168929d25289c55bfc8a4f753add94e95dc00d07e72b7e26fda36ac4ca61134b039dba30dbbd1f4eb30b8950be69fc1f1adfa70774f27d804c156962ac8173b9705a7474dc26bc34a37b2013b667848a66bc2d9d965f74f84b36694897b057fee496ffa2e2d59b19b4"; +const BC_JAVA_SHA512_SIG: &str = "3e06407d4cdc681b2bb37ba5a6d73358bee4a19629d29e7ecfe017d907ed1109b7c1941d789fea049ddf4fc4f4e8113a0a3c239dd7eb808cb4ec50bc5f0c30b88ece92fd2de2dc95e983bafc3c64abc513856db49d4b7d953df014759f8eaf70bdc94b30bbe7c63d737d2b8a34a0e6446941204c1513e4c73aa186b95759535bcf394730022b8b5a01b60557f216ecb5a1ecde7966365e469bd64099475fee4df3de87e29be5cc00f243c7d6b88b1f1df176b200939cf760d7aac7f408dc9b7b2c12f3b1ff6c5e59dc0983bc471503c00a718bd06738cbc05e8940225943dd34ebae3f0431fbf0d50b032f2712d479f2bdc7dca856f040709c419f064c592af4a0faecb3780546554070f8e51f5e52c8686d9046c38f134a67192eb2f95c3bffc1fe0c3186db55e89bef8ce5bfb087a1e7f825127002056bc59181827292c015fa7ed0e858b3ec915eff8d945c254814218c73a61bd0d0060ea7974f64284cf94dfdbee1d98fc93bf1752e2710abbbf83ff9f63f80955902e2def49ee519e0103f0d38ce5d68b122a82bd88d1c4ff6816380048aa6e47f72e1cfacb8e8ec53499b38b8822a2bdc559fcf877a121963af5ea46f75f5e11b51253161c32794aafb3fcbdc9a8670801ef9220c9603ce99cdb6354d3f887f848cbfac484e39424fbb4a758007e49fe62b2f662c208df5151ee7b45bf5b33031f9247267d71a68634daadf0f5174727a8a6885452a226bf0d9143e47242bc61d1c16c475ce797bbef32773467d070f7bef2a3dbdd93d320162c587d1a3e302d5ee74109bf9e185d9a0934e256bb6c92fd5cfd98f0241370f3fc81d349d77501de922d3c3090e720ed26505986e3170f06affbea59193a91a8b85abdd170f38380d7587325ddad1a91b31bc96943535adfad65735d22fd8cadc0347055eb49ea6101adc60afdddb95d33adcbb4caeb50fd63e4a12fbeb856049326c508b2abb26c33275e5c994689053689d3c9bd365d5d4f0776d6316b605bd126d4db55334ac44ad2f0f7ea53ec984a0e82a4b800caade6a74088d0eda31c12e3133138fa86c44c63ad67a63b534ef1ec278c857a07dc7974b459af4dbd21ffd040c691a89480d1f34ab80d668e65a988996f21c9121696b80bc710e33d4835ee7e66136506d4ed75d15ebaa9ddb5f4b64fc8baa145a2978debeb8c5c623f4f05c6b17f392dbd9d82a8081519a45344bf15f6e11addc6e444777c56db09ac8f8d3982e596552f0259dcebc378104031bc4d699b75b450ad7d883e0545914e31ec24c3d503ac157f99528f2746c112c3282803db9672245469b70e7f48d3fc83eb3cc808b790d03ef2e602018308d2855c5e4eb57cdf89d1ea1eaf3673c73401ac8d0193263e84e17eb6e8ba87bc29def2d651f3fc677ea5a8733b20478b3ef5a56e92703a5dfc9a86fceeb677dd034"; +const BC_JAVA_PSS_SHA256_SIG: &str = "71c1b3dd982fd6e1e8be1e20c8a4d42fbe6a8b204af54ab84b63f61b8c39efd20b75ebf477463869a21cff0956f304db041d8cc3357b9ebd92390a33a43e8b89d7c8549fd126f2606df61f97c068aea739bf831276dc8ce002e522c2a46465d649daa1ad92bc7d8d46be6d97839dfdadedd5f2f2471f83ac1facd237f673336e5efbcb7b87f44f80414e1f9479870f5624f3eb2c279ff64e99008e715bfcf7f02b32f1aac3e90cea194ddb7701367db41ad8c59ea635783a9ea724626f5d021a3758161ae1bd50b699a314e0a1a92fac184a9eb97ec44fc1c47000bc6da9267f302949aa837e1bfe45a09d526c974d1c5e7a12deb58817ce0cfde09b87e1cf4948df5c3f13d2d11d5dc926d4fd161b273d5f1195a7a8a174aa3f78f391273fef28b21c2a1f1ffe849c27c7545b199cf68a609bf022bca15cf9a946d6559a90240682b2f5437e78e67b15d8ccb8b703967a48f069dda9236d0caa6d3e2fd4c5bd311f83420c29fa3f8416a4b720b59c04fec4ac68f92f8d485ecccf6b1a23aa4b05ae5c220a7a0d4b9388b19f5bb7df484611e2958c5d5179230a37b302ceaf4b52a1ae781017059f8cc011655acc2ada8cc6ac6276e7fa5223a93ab9a17287abe6e9158a983373bb3eea9c28f7f3d2c15268cf41822fda6a029396fa87986a11078e08f9ec6dada5ffaa7f0f437168a136d0c46d076181ec231df545dc7dc6d644c076f95ff427a295cf83d29e5d3a75fc347a3df9895e4042b34b6a38145f8465c0740137b7387d1138f5bda49bab5b03e1ffd2e051a83a7c599a764ff9d931e12509fdbf1e8479ffc74621051e136bf3a50c278a5ad3b5a40a8e1697603d381d8925032e8a3d7a01c38d966636e0d017ee4dc5ac590ae1b730664155fe25aa27d52a7aab8754d525fef530b15b82f8e8bac2218edc5fec27dbfa11446473a92152d03e9d7c7f54ed592a48f126f6e67cb72c9f4795125b1a8dbab6fdc761d0ba83ea903f21c5ddd522da45af655423bfcf012b812054612bd8309f0b31b6dd286d99925cc379904a684ea90239717f0cb13878b2cbf00ee81cd46b37dfa6d8e504101b58ae1b2a43d58e49f982fbc4e3ede6c38a6e223d7eb0cbd49bb6a8d07bfdaa2b3822d6999dfe9ba8b6629c0b692f3f199856e59412a6fbbd5dbae9b116c35f141bf4ace2c7575f733a920c2c3d5750a0d0bba467921a542e1ba3b50384b5b5da9da13bd211e204b9e731568190c035c5b5a319f96de5cddc2e64f6ce386f72ada6f175d025ce15ed00f1ac6bd2572ad214124879b8e9cd95e3573ef6773c5aae10eb2027735bf1d4be77d8a049b63968a4acda99fbfe648a4fbba5a2bc38d43504dcdb862b336488b3f3a09a91ea9ff1ba271575c101b0a14427e4504f1ad2a499e6b5d5c373a72edf3656f33b46c11434e27d019c30dd6924960ca2"; + +#[test] +fn pkcs1_v1_5_matches_bc_java_byte_for_byte() { + let sk = genuine_key(); + let sig256 = sk.key::().sign_deterministic(b"hello", None).unwrap(); + assert_eq!(sig256.to_vec(), hex_decode(BC_JAVA_SHA256_SIG).unwrap()); + + let sig384 = sk.key::().sign_deterministic(b"hello", None).unwrap(); + assert_eq!(sig384.to_vec(), hex_decode(BC_JAVA_SHA384_SIG).unwrap()); + + let sig512 = sk.key::().sign_deterministic(b"hello", None).unwrap(); + assert_eq!(sig512.to_vec(), hex_decode(BC_JAVA_SHA512_SIG).unwrap()); +} + +#[test] +fn pkcs1_v1_5_verifies_bc_java_signatures() { + let sk = genuine_key(); + let pk = RsaPublicComponents::::new(sk.n(), 0x10001).unwrap(); + let sig256: [u8; 1024] = hex_decode(BC_JAVA_SHA256_SIG).unwrap().try_into().unwrap(); + let sig384: [u8; 1024] = hex_decode(BC_JAVA_SHA384_SIG).unwrap().try_into().unwrap(); + let sig512: [u8; 1024] = hex_decode(BC_JAVA_SHA512_SIG).unwrap().try_into().unwrap(); + pk.key::() + .verify(b"hello", None, &sig256) + .expect("BC Java's SHA-256 sig must verify"); + pk.key::() + .verify(b"hello", None, &sig384) + .expect("BC Java's SHA-384 sig must verify"); + pk.key::() + .verify(b"hello", None, &sig512) + .expect("BC Java's SHA-512 sig must verify"); +} + +#[test] +fn pss_verifies_bc_java_sha256_signature() { + let sk = genuine_key(); + let pk = RsaPublicComponents::::new(sk.n(), 0x10001).unwrap(); + let sig: [u8; 1024] = hex_decode(BC_JAVA_PSS_SHA256_SIG).unwrap().try_into().unwrap(); + pk.key::() + .verify(b"hello", None, &sig) + .expect("BC Java's PSS/SHA-256 signature (default salt length = hLen) must verify"); +} + +/// Mutation testing found that fixed-salt PSS/SHA-256 signing, RNG-salted PSS/SHA-384 and /SHA-512 +/// signing, and PSS/SHA-384 and /SHA-512 verification's rejection paths were never +/// exercised at this modulus size (the old combined self-consistency test above only called one +/// salt source per hash and never asserted rejection): a whole-function-body mutant replacing any +/// of them with a constant still passed the whole suite. Split into six tests, one per (hash, salt +/// source) pairing, matching `rsa_2048_pss_sha384_sha512_tests.rs`'s own shape. +#[test] +fn pss_sha256_fixed_salt_round_trips() { + let sk = genuine_key(); + let pk = RsaPublicComponents::::new(sk.n(), 0x10001).unwrap(); + let salt = [0x33u8; 32]; + let sig = + sign_with_salt!(RSASSA_PSS_SHA256, &sk, b"hello", salt).expect("signing must succeed"); + pk.key::().verify(b"hello", None, &sig).expect("must verify"); + assert!(pk.key::().verify(b"goodbye", None, &sig).is_err()); +} + +#[test] +fn pss_sha256_rng_produces_fresh_salts_that_both_verify() { + let sk = genuine_key(); + let pk = RsaPublicComponents::::new(sk.n(), 0x10001).unwrap(); + let mut rng = DefaultRNG::default(); + let sig_a = + sk.key::().sign(&mut rng, b"hello", None).expect("signing must succeed"); + let sig_b = + sk.key::().sign(&mut rng, b"hello", None).expect("signing must succeed"); + assert_ne!(sig_a, sig_b, "PSS is randomized: two signatures of the same message must differ"); + pk.key::().verify(b"hello", None, &sig_a).expect("sig_a must verify"); + pk.key::().verify(b"hello", None, &sig_b).expect("sig_b must verify"); +} + +#[test] +fn pss_sha384_fixed_salt_round_trips() { + let sk = genuine_key(); + let pk = RsaPublicComponents::::new(sk.n(), 0x10001).unwrap(); + let salt = [0x11u8; 48]; + let sig = + sign_with_salt!(RSASSA_PSS_SHA384, &sk, b"hello", salt).expect("signing must succeed"); + pk.key::().verify(b"hello", None, &sig).expect("must verify"); + assert!(pk.key::().verify(b"goodbye", None, &sig).is_err()); +} + +#[test] +fn pss_sha384_rng_produces_fresh_salts_that_both_verify() { + let sk = genuine_key(); + let pk = RsaPublicComponents::::new(sk.n(), 0x10001).unwrap(); + let mut rng = DefaultRNG::default(); + let sig_a = + sk.key::().sign(&mut rng, b"hello", None).expect("signing must succeed"); + let sig_b = + sk.key::().sign(&mut rng, b"hello", None).expect("signing must succeed"); + assert_ne!(sig_a, sig_b, "PSS is randomized: two signatures of the same message must differ"); + pk.key::().verify(b"hello", None, &sig_a).expect("sig_a must verify"); + pk.key::().verify(b"hello", None, &sig_b).expect("sig_b must verify"); +} + +#[test] +fn pss_sha512_fixed_salt_round_trips() { + let sk = genuine_key(); + let pk = RsaPublicComponents::::new(sk.n(), 0x10001).unwrap(); + let salt = [0x22u8; 64]; + let sig = + sign_with_salt!(RSASSA_PSS_SHA512, &sk, b"hello", salt).expect("signing must succeed"); + pk.key::().verify(b"hello", None, &sig).expect("must verify"); + assert!(pk.key::().verify(b"goodbye", None, &sig).is_err()); +} + +#[test] +fn pss_sha512_rng_produces_fresh_salts_that_both_verify() { + let sk = genuine_key(); + let pk = RsaPublicComponents::::new(sk.n(), 0x10001).unwrap(); + let mut rng = DefaultRNG::default(); + let sig_a = + sk.key::().sign(&mut rng, b"hello", None).expect("signing must succeed"); + let sig_b = + sk.key::().sign(&mut rng, b"hello", None).expect("signing must succeed"); + assert_ne!(sig_a, sig_b, "PSS is randomized: two signatures of the same message must differ"); + pk.key::().verify(b"hello", None, &sig_a).expect("sig_a must verify"); + pk.key::().verify(b"hello", None, &sig_b).expect("sig_b must verify"); +} + +fn run_pkcs1_v1_5_verify_vectors( + filename: &str, + verify: impl Fn(&RsaPublicComponents, &[u8], &[u8; 1024]) -> bool, + expected_sha: &str, + expected_valid: usize, + expected_invalid: usize, +) { + let doc: Value = serde_json::from_str(&get_test_data(filename)).expect("valid JSON"); + let mut num_valid = 0usize; + let mut num_invalid = 0usize; + let mut num_missing_null = 0usize; + + for group in doc["testGroups"].as_array().unwrap() { + assert_eq!(group["sha"], expected_sha); + let n: [u64; 128] = limbs_from_hex(group["publicKey"]["modulus"].as_str().unwrap()); + let e = u64::from_str_radix(group["publicKey"]["publicExponent"].as_str().unwrap(), 16) + .unwrap(); + let pk = RsaPublicComponents::::new(&n, e).unwrap(); + + for test in group["tests"].as_array().unwrap() { + let tc_id = test["tcId"].as_u64().unwrap(); + let msg = hex_decode(test["msg"].as_str().unwrap()).unwrap(); + let sig_bytes = hex_decode(test["sig"].as_str().unwrap()).unwrap(); + let flags: Vec<&str> = + test["flags"].as_array().unwrap().iter().map(|f| f.as_str().unwrap()).collect(); + + let Ok(sig): Result<[u8; 1024], _> = sig_bytes.try_into() else { + assert_ne!(test["result"], "valid", "tcId {tc_id}: wrong-length 'valid' signature"); + num_invalid += 1; + continue; + }; + let verified = verify(&pk, &msg, &sig); + match test["result"].as_str().unwrap() { + "valid" => { + assert!(verified, "tcId {tc_id}: expected valid, got invalid"); + num_valid += 1; + } + "invalid" => { + assert!(!verified, "tcId {tc_id}: expected invalid, got valid"); + num_invalid += 1; + } + "acceptable" => { + assert_eq!(flags, vec!["MissingNull"], "tcId {tc_id}: unreviewed acceptable"); + assert!(verified, "tcId {tc_id}: MissingNull must be accepted"); + num_missing_null += 1; + } + other => panic!("tcId {tc_id}: unknown result {other:?}"), + } + } + } + assert_eq!(num_missing_null, 1); + assert_eq!(num_valid, expected_valid, "for {filename}"); + assert_eq!(num_invalid, expected_invalid, "for {filename}"); +} + +#[test] +fn rsa_signature_8192_sha256_wycheproof_vectors() { + run_pkcs1_v1_5_verify_vectors( + "rsa_signature_8192_sha256_test.json", + |pk, msg, sig| pk.key::().verify(msg, None, sig).is_ok(), + "SHA-256", + 7, + 250, + ); +} + +#[test] +fn rsa_signature_8192_sha384_wycheproof_vectors() { + run_pkcs1_v1_5_verify_vectors( + "rsa_signature_8192_sha384_test.json", + |pk, msg, sig| pk.key::().verify(msg, None, sig).is_ok(), + "SHA-384", + 7, + 251, + ); +} + +#[test] +fn rsa_signature_8192_sha512_wycheproof_vectors() { + run_pkcs1_v1_5_verify_vectors( + "rsa_signature_8192_sha512_test.json", + |pk, msg, sig| pk.key::().verify(msg, None, sig).is_ok(), + "SHA-512", + 7, + 251, + ); +} + +// ---- bouncycastle_core trait conformance ------------------------------------------------------ + +fn fixed_keypair() +-> Result<(RsaPublicComponents, RsaPrivateComponents), SignatureError> { + let sk = genuine_key(); + let pk = RsaPublicComponents::::new(sk.n(), 0x10001)?; + Ok((pk, sk)) +} + +/// `core-test-framework`'s full conformance suite for one pairing at this width; the rest get +/// [`trait_round_trip`], for the reason `rsa_4096_tests.rs` gives (an RSA-8192 signature is +/// slower still in a debug build). +#[test] +fn pkcs1_v1_5_sha256_trait_conformance_suite() { + TestFrameworkSignature::with_ctx_behaviour(CtxBehaviour::Refused).test_deterministic_signature::, RsaPrivateKey, SIG_LEN>( + || fixed_keypair().map(|(pk, sk)| (pk.into_key::(), sk.into_key::())), false); +} + +#[test] +fn key_trait_boundary_conditions() { + TestFrameworkSignatureKeys::new() + .test_keys::, RsaPrivateKey, PK_LEN, SK_LEN>( + || fixed_keypair().map(|(pk, sk)| (pk.into_key::(), sk.into_key::())), + ); +} + +/// Sign one-shot and streamed, verify both, and reject a different message -- what a wrong width +/// constant in this size's aliases would break. PSS, through `SigningKey`. +fn pss_round_trip>( + pk: &RsaPublicComponents, + sk: &RsaPrivateComponents, +) { + let msg = b"RSA-8192 trait round trip"; + let mut rng = DefaultRNG::default(); + let sig = sk.key::().sign(&mut rng, msg, None).unwrap(); + pk.key::().verify(msg, None, &sig).unwrap(); + let sk_typed_a = sk.key::(); + let mut signer = sk_typed_a.create_signer(&mut rng, None).unwrap(); + signer.do_update(&msg[..8]); + signer.do_update(&msg[8..]); + pk.key::().verify(msg, None, &signer.do_final().unwrap()).unwrap(); + assert!(pk.key::().verify(b"a different message", None, &sig).is_err()); +} + +/// As [`pss_round_trip`], for PKCS#1 v1.5 through `DeterministicSigningKey`. +fn pkcs1_round_trip>( + pk: &RsaPublicComponents, + sk: &RsaPrivateComponents, +) { + let msg = b"RSA-8192 trait round trip"; + let sig = sk.key::().sign_deterministic(msg, None).unwrap(); + pk.key::().verify(msg, None, &sig).unwrap(); + let sk_typed_a = sk.key::(); + let mut signer = sk_typed_a.create_signer_deterministic(None).unwrap(); + signer.do_update(&msg[..8]); + signer.do_update(&msg[8..]); + assert_eq!(signer.do_final().unwrap(), sig); + assert!(pk.key::().verify(b"a different message", None, &sig).is_err()); +} + +#[test] +fn remaining_pairings_trait_round_trips() { + let (pk, sk) = fixed_keypair().unwrap(); + pkcs1_round_trip::(&pk, &sk); + pkcs1_round_trip::(&pk, &sk); + pss_round_trip::(&pk, &sk); + pss_round_trip::(&pk, &sk); + pss_round_trip::(&pk, &sk); +} + +/// The trait path reproduces BC Java's RSA-8192/PKCS#1 v1.5/SHA-256 signature byte for byte and +/// accepts BC Java's PSS signature -- the same cross-implementation check as the +/// tests above, through the key role traits. +#[test] +fn trait_matches_bc_java() { + let (pk, sk) = fixed_keypair().unwrap(); + let sig = sk.key::().sign_deterministic(b"hello", None).unwrap(); + assert_eq!(sig.to_vec(), hex_decode(BC_JAVA_SHA256_SIG).unwrap()); + let pss = hex_decode(BC_JAVA_PSS_SHA256_SIG).unwrap(); + pk.key::().verify(b"hello", None, &pss).unwrap(); +} diff --git a/crypto/rsa/tests/rsaes_oaep_tests.rs b/crypto/rsa/tests/rsaes_oaep_tests.rs new file mode 100644 index 000000000..39eb42e89 --- /dev/null +++ b/crypto/rsa/tests/rsaes_oaep_tests.rs @@ -0,0 +1,561 @@ +//! RSAES-OAEP (RFC 8017 §7.1; SP 800-56B Rev. 2 §7.2.2 and §9.2.3) on the key-establishment +//! keys, as a KEM and as transport of a caller's key. +//! +//! Known answers are Wycheproof's `rsa_oaep_*_test.json` files, which are decryption vectors: +//! a private key, and for each case a ciphertext, a label and either the message or the verdict +//! that it does not decrypt (`InvalidOaepPadding`, `InvalidCiphertext`). Every group at a +//! modulus size this crate has a private key for (2048, 3072, 4096 and 8192 bits) is run, for +//! every pairing of label hash and MGF1 hash, SHA-1 included; `rsa_oaep_misc_test.json` also +//! has groups at 1024, 1536 and other sizes, which are skipped and counted. The messages are +//! recovered through the key-transport role, which takes a message of any length. +//! +//! Encryption is randomized and RFC 8017 prints no vectors, so the encrypt side is checked by +//! round trip against the decrypt side, which the vectors pin. + +use bouncycastle_core::errors::{KEMError, KeyTransportError, RNGError}; +use bouncycastle_core::hazmat::FixedSeedRNG; +use bouncycastle_core::hex::decode as hex_decode; +use bouncycastle_core::kem_key::{DecapsulatingKey, EncapsulatingKey}; +use bouncycastle_core::key_material::{KeyMaterial, KeyMaterialTrait, KeyType}; +use bouncycastle_core::key_transport_key::{KeyTransportDecryptingKey, KeyTransportEncryptingKey}; +use bouncycastle_core::security_strength::SecurityStrength; +use bouncycastle_core::traits::{Algorithm, PrivateKey, RNG}; +use bouncycastle_core_test_framework::kem::TestFrameworkKEM; +use bouncycastle_core_test_framework::key_transport::TestFrameworkKeyTransport; +use bouncycastle_core_test_framework::test_data_loaders::wycheproof_json; +use bouncycastle_digest::sha1::SHA1; +use bouncycastle_rng::HashDRBG_SHA512; +use bouncycastle_rsa::rsaes_oaep::{OaepHash, OaepParams, RSAES_OAEP}; +use bouncycastle_rsa::rsasve::{RSASVE, RsaKEMPrivateKey, RsaKEMPublicKey}; +use bouncycastle_rsa::size::{RsaSigningSize, RsaSize}; +use bouncycastle_rsa::{RSA2048, RSA3072, RSA4096, RSA8192}; +use bouncycastle_sha2::{SHA224, SHA256, SHA384, SHA512, SHA512_224, SHA512_256}; +use serde_json::Value; +use std::sync::OnceLock; + +/// The RSA-2048 key of Wycheproof's `rsa_oaep_2048_sha256_mgf1sha256_test.json`, as +/// `p || q || dP || dQ || qInv || e`, hex: printed here so that known answers run where +/// Wycheproof is not checked out. +const KAT_SK_HEX: &str = concat!( + "dc431050f782e894fb5248247d98cb7d58b8d1e24f3b55d041c56e4de086b0d5", + "bb028bda42eeb5d234d5681e5809d415e6a289ad4cfbf78f978f6c35814f50ee", + "bff1c5b80a69f788e81e6bab5ddaa78369d659d143ec6f17e79813a575cfad9c", + "569156b90113e2e9110ad9e7b48a1c9348a6e653321191290ea36cfb3a5b18f1", + "bd1a81e7977f9898122273ae3222b598ea5fb19eb4eabc38308a5e32196603b2", + "e500ffb79f5b886816611debc472fac45544070beb057c941378a6868af3b7a0", + "3d3f9880ec47d5e089b94fbde542aba9ae8d72c57088d7abf5b131f39098f7bc", + "160f90536abc9492fd4e06f3ed7299d4b97bb03677207d95669f140cfbc20f25", + "a94b528b28f291599121d91952ffd1c7f21d7c1479d99d478885fb161870ee12", + "18bf08472612dbe5497e8d9c650688e09c786961ae3e2c354dc48ae34514759c", + "4c23c4588488961dc06b414e61c0e1e7fbbd2923d31532fe289f96da220711e5", + "8c14019808e00414276933bb07e4efb9b4a9b37656917205209f33f09515d7c1", + "3af0e72a933aef09ff2503df78bafed531c02ff1a2bc437c540cdcbd4ad35435", + "cf511763596543480629b114ca7f780ff7efa32ea0cb6e000d6d9ea1f2ef71fd", + "9cf9948422a165557e37e755edfe70d90b920502eb478bc98a63f788ce3a0f85", + "6d6ede7251a383bfa8fa480a81a925af7b3cc538c4bab8c9f7597ffb68011d8d", + "2640fbfbcfefb163ee7a87b6483a66ee41f956d90fa8a7939bfc042ee0924b1b", + "7993d0445f758d51933e85179c0320b0c968b48a91c38b5be923e1097c0c562f", + "88d42294b6a2759bafa5428a74f1270874e45f6fcc60f21602de5eccd143cf31", + "241f5921b5ad3983fb54ef17be3b285367e50c999c67247b552fe4bfce945f7b", + "0000000000010001", +); +/// Its public key, `n || e`. +#[allow(dead_code)] +const KAT_PK_HEX: &str = concat!( + "a2b451a07d0aa5f96e455671513550514a8a5b462ebef717094fa1fee82224e6", + "37f9746d3f7cafd31878d80325b6ef5a1700f65903b469429e89d6eac8845097", + "b5ab393189db92512ed8a7711a1253facd20f79c15e8247f3d3e42e46e48c98e", + "254a2fe9765313a03eff8f17e1a029397a1fa26a8dce26f490ed81299615d981", + "4c22da610428e09c7d9658594266f5c021d0fceca08d945a12be82de4d1ece6b", + "4c03145b5d3495d4ed5411eb878daf05fd7afc3e09ada0f1126422f590975a19", + "69816f48698bcbba1b4d9cae79d460d8f9f85e7975005d9bc22c4e5ac0f7c1a4", + "5d12569a62807d3b9a02e5a530e773066f453d1f5b4c2e9cf7820283f742b9d5", + "0000000000010001", +); +/// tcId 2 of that file: a ciphertext of `MSG_HEX` under the empty label. +const CT_HEX: &str = concat!( + "207180c340658b5154ae45d2e4e7326a0997c683a26b595e536a29333c4b6614", + "9af85e029d5419a39e3a147b221516ffd86b6b4b66c3e0c4c49fe8c57a2f5c37", + "b8704b9b592b80db9cd788a4ed51ab4f0a1cbed63bd18d1f06a22f225866b0c2", + "c417cb23473b7ba4250b1353bd2e5b4f0f937cd2efe5fa38db3c295f7748b970", + "088657db4aa9a76e1ee6fbff166ec1861d00d085326c7384bdd1bc2f400d4f74", + "dbdfadaf3fdc46073e668573e02030b9eb5af58eb540c66677a771194479ec00", + "98d858a2ea45d0ba1e6b32440dfbac745000554d51a17684ca964b02a74d479f", + "1d432ef763ef4059715a4348cfe36a215359712f25b6977903be4adb92febbf6", +); +const MSG_HEX: &str = "0000000000000000000000000000000000000000"; +/// tcId 8: a ciphertext of `LABELLED_MSG_HEX` under `LABEL_HEX`. +const LABELLED_CT_HEX: &str = concat!( + "6583e2f176aa7e7f655d2c53497349c156c8851fb23325589e85fb83bfa85734", + "6caba222cdaa3234e71564154298c24dbb85e18822a1d5e7faa47863a64d7687", + "4a3cbc70f4d9f137426a344c473fac1dd7008a9973765e9f66c5b492535a647c", + "273c4f78ceb5aa7ba963a2142f2ce4a81f804c002b9b2eabb3c75e80a3c6ceaf", + "e5384a544c672a5d28d32bb87115f43eb79775fd9b3f4a2f6e6a89368bdd95ef", + "1d014877b60afdb1234acd57653a65459f01b2fbe381f22a739504b4897a7e6c", + "33b6349b276db6083abad9c169405859b800c812237634b503de6ada43013c1d", + "86697a135be78a9784576d796d62aa7819e2ea0e2d902ffdd9cfdd1ae66212ee", +); +const LABELLED_MSG_HEX: &str = "313233343030"; +const LABEL_HEX: &str = "0000000000000000"; +/// tcId 12: "first byte of l_hash modified". +const INVALID_CT_HEX: &str = concat!( + "287d7108a1c6e7a18acb0045b20c57cdf2ac03456b44942764a7a9e9fdf3db48", + "1d7e202e4c8d733b56b9c1e93d71e791af8325c9363df789b252a5ed0eddc79e", + "76fa41c2cb0a35618398217a390a5e6d99eed905d5554d19c1cf4e30bdf1c2fc", + "c5148b641d71b3f1977b63d232648ddd935ec9499a53ac2fbcac55f462e91065", + "adaa018a39c453ba759bd68b454074153421e2ce75cf149f748b5b84758df8a4", + "23d1c50c880af863f2a6df3cd465ca36aa2152b5771f3d507f4a4dd9f8006d80", + "eca23537092287976f218a90df1e16d889fe31e79f7309f3224f613e9b52479f", + "e73b7aad915319a3b62a5936649f7d015d7b09f7fa9f454f78a7c3dd4bf791e0", +); + +/// The printed Wycheproof cases: a message under the empty label, one under a label, and a +/// ciphertext whose lHash was damaged. +#[test] +fn printed_known_answers() { + let sk = RsaKEMPrivateKey::::from_bytes(&hex_decode(KAT_SK_HEX).unwrap()).unwrap(); + let ct = |hex: &str| -> [u8; 256] { hex_decode(hex).unwrap().try_into().unwrap() }; + let mut key = KeyMaterial::<64>::new(); + + let msg = hex_decode(MSG_HEX).unwrap(); + assert_eq!( + sk.recover_out(&ct(CT_HEX), OaepParams::::new(b""), &mut key), + Ok(msg.len()) + ); + assert_eq!(key.ref_to_bytes(), msg.as_slice()); + // tcId 2's message is twenty zero bytes: a value, typed as the zeros it is. + assert_eq!(key.key_type(), KeyType::Zeroized); + + let (msg, label) = (hex_decode(LABELLED_MSG_HEX).unwrap(), hex_decode(LABEL_HEX).unwrap()); + let labelled = OaepParams::::new(&label); + assert_eq!(sk.recover_out(&ct(LABELLED_CT_HEX), labelled, &mut key), Ok(msg.len())); + assert_eq!(key.ref_to_bytes(), msg.as_slice()); + assert_eq!(key.key_type(), KeyType::CryptographicRandom); + assert_eq!(key.security_strength(), SecurityStrength::None, "six bytes carry no strength"); + assert_eq!( + sk.recover_out(&ct(LABELLED_CT_HEX), OaepParams::::new(b""), &mut key), + Err(KeyTransportError::DecryptionFailed) + ); + + assert_eq!( + sk.recover_out(&ct(INVALID_CT_HEX), OaepParams::::new(b""), &mut key), + Err(KeyTransportError::DecryptionFailed) + ); + assert_eq!(key.key_type(), KeyType::Zeroized); +} + +/// `(valid recovered, invalid refused, skipped)`. +type Counts = (usize, usize, usize); + +/// A big-endian hex integer as exactly `len` bytes: Wycheproof writes some with a leading zero +/// byte and some without their leading zeros. +fn be_bytes(hex: &str, len: usize) -> Vec { + let bytes = hex_decode(hex).expect("valid hex"); + let first = bytes.iter().position(|b| *b != 0).unwrap_or(bytes.len()); + let significant = &bytes[first..]; + assert!(significant.len() <= len, "value wider than {len} bytes"); + let mut out = vec![0u8; len - significant.len()]; + out.extend_from_slice(significant); + out +} + +/// One Wycheproof group through `RSAES_OAEP`. +fn run_group(group: &Value) -> Counts +where + K: RsaSigningSize + RsaSize, + H: OaepHash, + M: OaepHash, +{ + // The private key's encoding is p || q || dP || dQ || qInv, each half the modulus long, + // then e in eight bytes. + let key = &group["privateKey"]; + let e = u64::from_str_radix(key["publicExponent"].as_str().unwrap(), 16).unwrap(); + let mut raw = Vec::with_capacity(SK_LEN); + for field in ["prime1", "prime2", "exponent1", "exponent2", "coefficient"] { + raw.extend(be_bytes(key[field].as_str().unwrap(), N / 2)); + } + raw.extend(e.to_be_bytes()); + let sk = RsaKEMPrivateKey::::from_bytes(&raw).expect("a Wycheproof key decodes"); + + let (mut valid, mut invalid) = (0, 0); + for test in group["tests"].as_array().unwrap() { + let tc_id = test["tcId"].as_u64().unwrap(); + let msg = hex_decode(test["msg"].as_str().unwrap()).unwrap(); + let label = hex_decode(test["label"].as_str().unwrap()).unwrap(); + let ct = hex_decode(test["ct"].as_str().unwrap()).unwrap(); + let params = OaepParams::::new(&label); + // A ciphertext of the wrong length is not a ciphertext: RFC 8017 §7.1.2 step 1.b. + let mut recovered = KeyMaterial::<1024>::new(); + let result = <[u8; N]>::try_from(ct.as_slice()) + .map_err(|_| KeyTransportError::DecryptionFailed) + .and_then(|ct| sk.recover_out(&ct, params, &mut recovered)); + match test["result"].as_str().unwrap() { + // "acceptable" cases are valid ciphertexts with an unusual shape (a small integer + // ciphertext), which RFC 8017 gives no reason to refuse. + "valid" | "acceptable" => { + assert_eq!(result, Ok(msg.len()), "tcId {tc_id}"); + assert_eq!(recovered.ref_to_bytes(), msg.as_slice(), "tcId {tc_id}"); + // An empty or all-zero message is typed as what it is; any other is a key. + let expected = if msg.iter().all(|b| *b == 0) { + KeyType::Zeroized + } else { + KeyType::CryptographicRandom + }; + assert_eq!(recovered.key_type(), expected, "tcId {tc_id}"); + valid += 1; + } + "invalid" => { + assert_eq!(result, Err(KeyTransportError::DecryptionFailed), "tcId {tc_id}"); + assert_eq!(recovered.key_type(), KeyType::Zeroized, "tcId {tc_id}"); + invalid += 1; + } + other => panic!("tcId {tc_id}: unexpected result {other}"), + } + } + + // Encryption under the group's public key, which the vectors do not cover: a key + // transported with this size and these hashes comes back. + let pk = RsaKEMPublicKey::::new(sk.n(), e).expect("a Wycheproof key is a KEM key"); + let params = OaepParams::::new(b"round trip"); + let sent = KeyMaterial::<32>::from_bytes_as_type(&[0x42; 32], KeyType::MACKey).unwrap(); + let ct = pk.transport(&mut HashDRBG_SHA512::new_from_os(), params, &sent).unwrap(); + let mut recovered = KeyMaterial::<32>::new(); + assert_eq!(sk.recover_out(&ct, params, &mut recovered), Ok(32)); + assert_eq!(recovered.ref_to_bytes(), [0x42; 32]); + + (valid, invalid, 0) +} + +/// The MGF1 hash by Wycheproof's name. +fn with_mgf(group: &Value) -> Counts +where + K: RsaSigningSize + RsaSize, + H: OaepHash, +{ + match group["mgfSha"].as_str().unwrap() { + "SHA-1" => run_group::(group), + "SHA-224" => run_group::(group), + "SHA-256" => run_group::(group), + "SHA-384" => run_group::(group), + "SHA-512" => run_group::(group), + "SHA-512/224" => run_group::(group), + "SHA-512/256" => run_group::(group), + other => panic!("unexpected mgfSha {other}"), + } +} + +/// The label hash by Wycheproof's name. +fn with_sha(group: &Value) -> Counts +where + K: RsaSigningSize + RsaSize, +{ + assert_eq!(group["mgf"], "MGF1"); + match group["sha"].as_str().unwrap() { + "SHA-1" => with_mgf::(group), + "SHA-224" => with_mgf::(group), + "SHA-256" => with_mgf::(group), + "SHA-384" => with_mgf::(group), + "SHA-512" => with_mgf::(group), + "SHA-512/224" => with_mgf::(group), + "SHA-512/256" => with_mgf::(group), + other => panic!("unexpected sha {other}"), + } +} + +/// Every group of a Wycheproof file, by modulus size; `None` if Wycheproof is not checked out. +fn run_file(filename: &str) -> Option { + let file = wycheproof_json(filename)?; + let mut total = (0, 0, 0); + for group in file["testGroups"].as_array().unwrap() { + let (valid, invalid, skipped) = match group["keySize"].as_u64().unwrap() { + 2048 => with_sha::(group), + 3072 => with_sha::(group), + 4096 => with_sha::(group), + 8192 => with_sha::(group), + // No private key type below 2048 bits or at the odd sizes of the misc file. + _ => (0, 0, group["tests"].as_array().unwrap().len()), + }; + total = (total.0 + valid, total.1 + invalid, total.2 + skipped); + } + Some(total) +} + +/// The per-suite files: `(file stem, valid, invalid)`. +const SUITE_FILES: [(&str, usize, usize); 21] = [ + ("2048_sha1_mgf1sha1", 17, 19), + ("2048_sha224_mgf1sha1", 13, 18), + ("2048_sha224_mgf1sha224", 17, 18), + ("2048_sha256_mgf1sha1", 13, 18), + ("2048_sha256_mgf1sha256", 18, 19), + ("2048_sha384_mgf1sha1", 13, 18), + ("2048_sha384_mgf1sha384", 16, 18), + ("2048_sha512_224_mgf1sha1", 13, 19), + ("2048_sha512_224_mgf1sha512_224", 16, 19), + ("2048_sha512_mgf1sha1", 13, 18), + ("2048_sha512_mgf1sha512", 14, 19), + ("3072_sha256_mgf1sha1", 13, 19), + ("3072_sha256_mgf1sha256", 18, 19), + ("3072_sha512_256_mgf1sha1", 13, 18), + ("3072_sha512_256_mgf1sha512_256", 18, 19), + ("3072_sha512_mgf1sha1", 13, 18), + ("3072_sha512_mgf1sha512", 15, 18), + ("4096_sha256_mgf1sha1", 13, 19), + ("4096_sha256_mgf1sha256", 18, 19), + ("4096_sha512_mgf1sha1", 13, 18), + ("4096_sha512_mgf1sha512", 17, 19), +]; + +#[test] +fn wycheproof_suite_files() { + for (stem, valid, invalid) in SUITE_FILES { + let filename = format!("rsa_oaep_{stem}_test.json"); + match run_file(&filename) { + Some(counts) => assert_eq!(counts, (valid, invalid, 0), "{filename}"), + None => return, + } + } +} + +/// The misc file: every pairing of the hashes at every size, valid cases only. 140 of its 395 +/// cases are at sizes with no private key type here. +#[test] +fn wycheproof_misc_file() { + if let Some(counts) = run_file("rsa_oaep_misc_test.json") { + assert_eq!(counts, (255, 0, 140)); + } +} + +type Pk = RsaKEMPublicKey; +type Sk = RsaKEMPrivateKey; + +/// Two RSA-2048 key pairs, generated once for the file. +fn key_pairs() -> &'static [(Pk, Sk); 2] { + static KEYS: OnceLock<[(Pk, Sk); 2]> = OnceLock::new(); + KEYS.get_or_init(|| { + let mut rng = HashDRBG_SHA512::new_from_os(); + [RSASVE::::keygen(&mut rng).unwrap(), RSASVE::::keygen(&mut rng).unwrap()] + }) +} + +#[test] +fn the_kem_framework_passes() { + fn keygen() -> Result<(Pk, Sk), KEMError> { + Ok(key_pairs()[0].clone()) + } + let framework = TestFrameworkKEM::new(false, false); + framework.test_kem::<_, Pk, Sk, 256, 32>(keygen, OaepParams::::new(b"label"), false); + framework.test_kem::<_, Pk, Sk, 256, 48>( + keygen, + OaepParams::::new(b""), + false, + ); +} + +#[test] +fn the_key_transport_framework_passes() { + let [(pk, sk), (_, other_sk)] = key_pairs(); + let framework = TestFrameworkKeyTransport::new(true); + framework.test::<_, _, _, 256>(pk, sk, other_sk, OaepParams::::new(b"label")); + framework.test::<_, _, _, 256>(pk, sk, other_sk, OaepParams::::new(b"")); + // The longest key is k - 2hLen - 2. + assert_eq!(pk.max_key_len(OaepParams::::new(b"")), 256 - 2 * 32 - 2); + assert_eq!(pk.max_key_len(OaepParams::::new(b"")), 256 - 2 * 64 - 2); + assert_eq!(pk.max_key_len(OaepParams::::new(b"")), 256 - 2 * 20 - 2); +} + +/// The label, the label hash and the MGF1 hash are each part of what a ciphertext is for: a +/// recipient with another one gets the decryption error, through either role. +#[test] +fn the_label_and_both_hashes_are_bound() { + let [(pk, sk), _] = key_pairs(); + let mut rng = HashDRBG_SHA512::new_from_os(); + let params = OaepParams::::new(b"label"); + let (ss, ct) = pk.encaps(&mut rng, params).unwrap(); + assert_eq!(sk.decaps(&ct, params).unwrap(), ss); + + assert_eq!( + sk.decaps(&ct, OaepParams::::new(b"Label")), + Err(KEMError::DecapsulationFailed) + ); + assert_eq!(sk.decaps(&ct, OaepParams::::new(b"")), Err(KEMError::DecapsulationFailed)); + assert_eq!( + sk.decaps(&ct, OaepParams::::new(b"label")), + Err(KEMError::DecapsulationFailed) + ); + assert_eq!( + sk.decaps(&ct, OaepParams::::new(b"label")), + Err(KEMError::DecapsulationFailed) + ); +} + +/// The two roles are one scheme: a key the KEM transported is recovered by the transport role, +/// and a transported key of the KEM's length decapsulates; a key of another length is the +/// decryption error to the KEM, which wants exactly `LEN` bytes. +#[test] +fn the_kem_and_the_transport_roles_interoperate() { + let [(pk, sk), _] = key_pairs(); + let mut rng = HashDRBG_SHA512::new_from_os(); + let params = OaepParams::::new(b""); + + let (ss, ct) = pk.encaps(&mut rng, params).unwrap(); + let mut recovered = KeyMaterial::<64>::new(); + assert_eq!(sk.recover_out(&ct, params, &mut recovered), Ok(32)); + assert_eq!(recovered.ref_to_bytes(), ss.ref_to_bytes()); + + let key = KeyMaterial::<32>::from_bytes_as_type(&[0x42; 32], KeyType::MACKey).unwrap(); + let ct = pk.transport(&mut rng, params, &key).unwrap(); + assert_eq!(sk.decaps(&ct, params).unwrap().ref_to_bytes(), [0x42; 32]); + + for len in [31usize, 33] { + let key = KeyMaterial::<64>::from_bytes_as_type(&vec![0x42; len], KeyType::MACKey).unwrap(); + let ct = pk.transport(&mut rng, params, &key).unwrap(); + assert_eq!(sk.decaps(&ct, params), Err(KEMError::DecapsulationFailed), "len {len}"); + } +} + +/// A ciphertext that is not below the modulus is refused, as is the all-zero one, with the +/// output left zeroized. +#[test] +fn ciphertexts_out_of_range_are_refused() { + let [(_, sk), _] = key_pairs(); + let params = OaepParams::::new(b""); + // SP 800-56B Rev. 2 §7.2.2.4 step 2.c: 1 < c < n - 1. + let mut one = [0u8; 256]; + one[255] = 1; + for ct in [[0xFFu8; 256], [0u8; 256], one] { + assert_eq!(sk.decaps(&ct, params), Err(KEMError::DecapsulationFailed)); + let mut recovered = KeyMaterial::<64>::from_bytes(&[0xEE; 64]).unwrap(); + assert_eq!( + sk.recover_out(&ct, params, &mut recovered), + Err(KeyTransportError::DecryptionFailed) + ); + assert_eq!(recovered.key_type(), KeyType::Zeroized); + } +} + +/// The algorithm is named by size and both hashes, and its strength is the modulus's capped by +/// what the shorter hash output can carry: SHA-1's 160 bits cap RSA-8192 at 128, and do not +/// lower RSA-2048's 112. +#[test] +fn names_and_strengths() { + assert_eq!(RSAES_OAEP::::ALG_NAME, "RSAES-OAEP-2048-SHA256-MGF1-SHA256"); + assert_eq!(RSAES_OAEP::::ALG_NAME, "RSAES-OAEP-4096-SHA512-MGF1-SHA1"); + assert_eq!(RSAES_OAEP::::MAX_SECURITY_STRENGTH, SecurityStrength::_112bit); + assert_eq!(RSAES_OAEP::::MAX_SECURITY_STRENGTH, SecurityStrength::_112bit); + assert_eq!( + RSAES_OAEP::::MAX_SECURITY_STRENGTH, + ::STRENGTH + ); + assert_eq!( + RSAES_OAEP::::MAX_SECURITY_STRENGTH, + SecurityStrength::_128bit + ); + assert_eq!( + RSAES_OAEP::::MAX_SECURITY_STRENGTH, + SecurityStrength::_128bit + ); + // A 28-byte output carries 192 bits, which is RSA-8192's own strength. + assert_eq!(::STRENGTH, SecurityStrength::_192bit); + assert_eq!(RSAES_OAEP::::MAX_SECURITY_STRENGTH, SecurityStrength::_192bit); + assert_eq!( + RSAES_OAEP::::MAX_SECURITY_STRENGTH, + SecurityStrength::_192bit + ); +} + +/// The RNG must offer the algorithm's strength, and exactly that is enough, for both roles; a +/// weaker one is refused, with the outputs left zeroized. +#[test] +fn the_rng_must_offer_the_algorithms_strength() { + let [(pk, sk), _] = key_pairs(); + let params = OaepParams::::new(b""); + let key = KeyMaterial::<32>::from_bytes_as_type(&[0x42; 32], KeyType::MACKey).unwrap(); + let rng_at = |strength| { + let mut rng = FixedSeedRNG::new(core::array::from_fn::(|i| i as u8 ^ 0x5A)); + rng.set_security_strength(strength); + rng + }; + + // RSAES-OAEP-2048 is a 112-bit algorithm. + let (ss, ct) = pk.encaps(&mut rng_at(SecurityStrength::_112bit), params).unwrap(); + assert_eq!(sk.decaps(&ct, params).unwrap(), ss); + let ct = pk.transport(&mut rng_at(SecurityStrength::_112bit), params, &key).unwrap(); + assert_eq!(sk.decaps(&ct, params).unwrap().ref_to_bytes(), [0x42; 32]); + + let mut ct = [0xFFu8; 256]; + let mut ss = KeyMaterial::<32>::from_bytes(&[0xEE; 32]).unwrap(); + assert_eq!( + pk.encaps_out(&mut rng_at(SecurityStrength::None), params, &mut ct, &mut ss), + Err(KEMError::RNGError(RNGError::SecurityStrengthInsufficientForAlgorithm)) + ); + assert_eq!(ct, [0u8; 256]); + assert_eq!(ss.key_type(), KeyType::Zeroized); + let mut ct = [0xFFu8; 256]; + assert_eq!( + pk.transport_out(&mut rng_at(SecurityStrength::None), params, &key, &mut ct), + Err(KeyTransportError::RNGError(RNGError::SecurityStrengthInsufficientForAlgorithm)) + ); + assert_eq!(ct, [0u8; 256]); +} + +/// An RNG that delivers its first draw and fails the second: the KEM's key is drawn first and +/// the OAEP seed second. +struct FailsOnSecondDraw(usize); + +impl RNG for FailsOnSecondDraw { + fn add_seed_keymaterial(&mut self, _: &dyn KeyMaterialTrait) -> Result<(), RNGError> { + Err(RNGError::GenericError("not seedable")) + } + fn next_int(&mut self) -> Result { + Err(RNGError::GenericError("not used")) + } + fn next_bytes_out(&mut self, out: &mut [u8]) -> Result { + self.0 += 1; + if self.0 > 1 { + return Err(RNGError::GenericError("the second draw fails")); + } + out.fill(0xA5); + Ok(out.len()) + } + fn fill_keymaterial_out(&mut self, _: &mut dyn KeyMaterialTrait) -> Result { + Err(RNGError::GenericError("not used")) + } + fn security_strength(&self) -> SecurityStrength { + SecurityStrength::_256bit + } +} + +/// An RNG failure on the seed, after the key was drawn, is the RNG's error, and neither the +/// ciphertext nor the key that was drawn is left in the caller's buffers. +#[test] +fn an_rng_failure_on_the_seed_leaves_the_outputs_zeroized() { + let [(pk, _), _] = key_pairs(); + let params = OaepParams::::new(b""); + let mut ct = [0xFFu8; 256]; + let mut ss = KeyMaterial::<32>::from_bytes(&[0xEE; 32]).unwrap(); + assert_eq!( + pk.encaps_out(&mut FailsOnSecondDraw(0), params, &mut ct, &mut ss), + Err(KEMError::RNGError(RNGError::GenericError("the second draw fails"))) + ); + assert_eq!(ct, [0u8; 256]); + assert_eq!(ss.key_type(), KeyType::Zeroized); + + let key = KeyMaterial::<32>::from_bytes_as_type(&[0x42; 32], KeyType::MACKey).unwrap(); + let mut ct = [0xFFu8; 256]; + assert_eq!( + pk.transport_out(&mut FailsOnSecondDraw(1), params, &key, &mut ct), + Err(KeyTransportError::RNGError(RNGError::GenericError("the second draw fails"))) + ); + assert_eq!(ct, [0u8; 256]); +} + +/// The longest key the KEM carries at RSA-2048 with SHA-256, 190 bytes, builds and round +/// trips; `OaepParams`' doc has the 191-byte case that does not build. +#[test] +fn the_kem_carries_its_longest_key() { + let [(pk, sk), _] = key_pairs(); + let params = OaepParams::::new(b""); + let (ss, ct) = pk.encaps(&mut HashDRBG_SHA512::new_from_os(), params).unwrap(); + assert_eq!(ss.key_len(), 190); + assert_eq!(sk.decaps(&ct, params).unwrap(), ss); +} diff --git a/crypto/rsa/tests/rsassa_worker_tests.rs b/crypto/rsa/tests/rsassa_worker_tests.rs new file mode 100644 index 000000000..41e37f444 --- /dev/null +++ b/crypto/rsa/tests/rsassa_worker_tests.rs @@ -0,0 +1,246 @@ +//! The signature workers name their algorithm, the random-salt `sign_from_hash` entry points +//! of the PSS schemes sign what `verify_from_hash` accepts, and a non-empty context is refused. + +use bouncycastle_core::errors::SignatureError; +use bouncycastle_core::signature_key::{ + DeterministicOneShotSigningKey, DeterministicSigningKey, OneShotSigningKey, + OneShotVerifyingKey, SigningKey, VerifyingKey, +}; +use bouncycastle_core::traits::{AlgorithmInfo, HashOneShot, SignatureSigner, SignatureVerifier}; +use bouncycastle_rng::DefaultRNG; +use bouncycastle_rsa::RSA2048; +use bouncycastle_rsa::keys::{RsaPrivateComponents, RsaPublicComponents}; +use bouncycastle_rsa::rsassa; +use bouncycastle_rsa::rsassa_pkcs1_v1_5::RSASSA_PKCS1_v1_5; +use bouncycastle_rsa::rsassa_pss::RSASSA_PSS; +use bouncycastle_sha2::SHA256; +use bouncycastle_sha3::SHAKE128; + +// The crate docs' example key (Wycheproof's rsa_pkcs1_2048_sig_gen_test.json first SHA-256 group). +const P: [u64; 16] = [ + 0x0ea36cfb3a5b18f1, 0x48a6e65332119129, 0x110ad9e7b48a1c93, 0x569156b90113e2e9, + 0xe79813a575cfad9c, 0x69d659d143ec6f17, 0xe81e6bab5ddaa783, 0xbff1c5b80a69f788, + 0x978f6c35814f50ee, 0xe6a289ad4cfbf78f, 0x34d5681e5809d415, 0xbb028bda42eeb5d2, + 0x41c56e4de086b0d5, 0x58b8d1e24f3b55d0, 0xfb5248247d98cb7d, 0xdc431050f782e894, +]; +const Q: [u64; 16] = [ + 0x669f140cfbc20f25, 0xb97bb03677207d95, 0xfd4e06f3ed7299d4, 0x160f90536abc9492, + 0xf5b131f39098f7bc, 0xae8d72c57088d7ab, 0x89b94fbde542aba9, 0x3d3f9880ec47d5e0, + 0x1378a6868af3b7a0, 0x5544070beb057c94, 0x16611debc472fac4, 0xe500ffb79f5b8868, + 0x308a5e32196603b2, 0xea5fb19eb4eabc38, 0x122273ae3222b598, 0xbd1a81e7977f9898, +]; +const D_P: [u64; 16] = [ + 0x209f33f09515d7c1, 0xb4a9b37656917205, 0x276933bb07e4efb9, 0x8c14019808e00414, + 0x289f96da220711e5, 0xfbbd2923d31532fe, 0xc06b414e61c0e1e7, 0x4c23c4588488961d, + 0x4dc48ae34514759c, 0x9c786961ae3e2c35, 0x497e8d9c650688e0, 0x18bf08472612dbe5, + 0x8885fb161870ee12, 0xf21d7c1479d99d47, 0x9121d91952ffd1c7, 0xa94b528b28f29159, +]; +const D_Q: [u64; 16] = [ + 0xf7597ffb68011d8d, 0x7b3cc538c4bab8c9, 0xa8fa480a81a925af, 0x6d6ede7251a383bf, + 0x8a63f788ce3a0f85, 0x0b920502eb478bc9, 0x7e37e755edfe70d9, 0x9cf9948422a16555, + 0x0d6d9ea1f2ef71fd, 0xf7efa32ea0cb6e00, 0x0629b114ca7f780f, 0xcf51176359654348, + 0x540cdcbd4ad35435, 0x31c02ff1a2bc437c, 0xff2503df78bafed5, 0x3af0e72a933aef09, +]; +const Q_INV: [u64; 16] = [ + 0x552fe4bfce945f7b, 0x67e50c999c67247b, 0xfb54ef17be3b2853, 0x241f5921b5ad3983, + 0x02de5eccd143cf31, 0x74e45f6fcc60f216, 0xafa5428a74f12708, 0x88d42294b6a2759b, + 0xe923e1097c0c562f, 0xc968b48a91c38b5b, 0x933e85179c0320b0, 0x7993d0445f758d51, + 0x9bfc042ee0924b1b, 0x41f956d90fa8a793, 0xee7a87b6483a66ee, 0x2640fbfbcfefb163, +]; + +fn key_pair() -> (RsaPublicComponents, RsaPrivateComponents) { + let sk = + RsaPrivateComponents::::from_crt_components(&P, &Q, &D_P, &D_Q, &Q_INV, 0x10001) + .unwrap(); + let pk = RsaPublicComponents::::new(sk.n(), 0x10001).unwrap(); + (pk, sk) +} + +#[test] +fn workers_name_their_algorithm() { + let (pk, sk) = key_pair(); + let mut rng = DefaultRNG::default(); + + let sk_rsassa_pkcs1_v1_5_rsa2048_sha256 = sk.key::>(); + let signer = sk_rsassa_pkcs1_v1_5_rsa2048_sha256.create_signer_deterministic(None).unwrap(); + assert_eq!(signer.alg_name(), "RSASSA-PKCS1-v1_5-SHA256"); + let pk_rsassa_pkcs1_v1_5_rsa2048_sha256 = pk.key::>(); + + let verifier = pk_rsassa_pkcs1_v1_5_rsa2048_sha256.create_verifier(None).unwrap(); + assert_eq!(verifier.alg_name(), "RSASSA-PKCS1-v1_5-SHA256"); + + let sk_rsassa_pss_rsa2048_sha256 = sk.key::>(); + + let signer = sk_rsassa_pss_rsa2048_sha256.create_signer(&mut rng, None).unwrap(); + assert_eq!(signer.alg_name(), "RSASSA-PSS-SHA256"); + let pk_rsassa_pss_rsa2048_sha256 = pk.key::>(); + + let verifier = pk_rsassa_pss_rsa2048_sha256.create_verifier(None).unwrap(); + assert_eq!(verifier.alg_name(), "RSASSA-PSS-SHA256"); + + let sk_rsassa_pss_rsa2048_shake128 = sk.key::>(); + + let signer = sk_rsassa_pss_rsa2048_shake128.create_signer(&mut rng, None).unwrap(); + assert_eq!(signer.alg_name(), "RSASSA-PSS-SHAKE128"); + let pk_rsassa_pss_rsa2048_shake128 = pk.key::>(); + + let verifier = pk_rsassa_pss_rsa2048_shake128.create_verifier(None).unwrap(); + assert_eq!(verifier.alg_name(), "RSASSA-PSS-SHAKE128"); +} + +/// The random-salt `sign_from_hash` draws its salt from the RNG: two signatures of one digest +/// differ, and both verify. +#[test] +fn pss_sign_from_hash_draws_a_fresh_salt_and_verifies() { + let (pk, sk) = key_pair(); + let mut rng = DefaultRNG::default(); + let mut digest = [0u8; 32]; + SHA256::hash_out(b"the message", &mut digest); + + let a = rsassa::sign_from_hash::, 256>( + &sk.key::>(), + &digest, + &mut rng, + ) + .unwrap(); + let b = rsassa::sign_from_hash::, 256>( + &sk.key::>(), + &digest, + &mut rng, + ) + .unwrap(); + assert_ne!(a, b); + rsassa::verify_from_hash::, 256>( + &pk.key::>(), + &digest, + &a, + ) + .unwrap(); + rsassa::verify_from_hash::, 256>( + &pk.key::>(), + &digest, + &b, + ) + .unwrap(); + assert!( + rsassa::verify_from_hash::, 256>( + &pk.key::>(), + &[0u8; 32], + &a + ) + .is_err() + ); + + let mut digest = [0u8; 32]; + SHAKE128::hash_out(b"the message", &mut digest); + let a = rsassa::sign_from_hash::, 256>( + &sk.key::>(), + &digest, + &mut rng, + ) + .unwrap(); + let b = rsassa::sign_from_hash::, 256>( + &sk.key::>(), + &digest, + &mut rng, + ) + .unwrap(); + assert_ne!(a, b); + rsassa::verify_from_hash::, 256>( + &pk.key::>(), + &digest, + &a, + ) + .unwrap(); + rsassa::verify_from_hash::, 256>( + &pk.key::>(), + &digest, + &b, + ) + .unwrap(); +} + +const NO_CONTEXT: SignatureError = SignatureError::LengthError("RSA takes no context"); + +/// RSA has no context input (RFC 8017 Section 8: the operations take a key and a message), so +/// the absent and the empty context are the same and a non-empty one is refused, by signing and +/// by verifying, one-shot and where a worker is made: RSASSA-PKCS1-v1_5. +#[test] +fn pkcs1_v1_5_refuses_a_context() { + type Alg = RSASSA_PKCS1_v1_5; + let (pk, sk) = key_pair(); + let (pk, sk) = (pk.key::(), sk.key::()); + let msg = b"no context to bind"; + + let sig = sk.sign_deterministic(msg, None).unwrap(); + assert_eq!(sk.sign_deterministic(msg, Some(&[])).unwrap(), sig); + pk.verify(msg, None, &sig).unwrap(); + pk.verify(msg, Some(&[]), &sig).unwrap(); + + for ctx in [&b"c"[..], b"a context"] { + assert_eq!(sk.sign_deterministic(msg, Some(ctx)), Err(NO_CONTEXT)); + let mut out = [0xFFu8; 256]; + assert_eq!(sk.sign_deterministic_out(msg, Some(ctx), &mut out), Err(NO_CONTEXT)); + assert_eq!(out, [0u8; 256]); + assert!(matches!(sk.create_signer_deterministic(Some(ctx)), Err(NO_CONTEXT))); + assert_eq!(pk.verify(msg, Some(ctx), &sig), Err(NO_CONTEXT)); + assert!(matches!(pk.create_verifier(Some(ctx)), Err(NO_CONTEXT))); + } + + // Streaming under the empty context is streaming under none. + let mut signer = sk.create_signer_deterministic(Some(&[])).unwrap(); + signer.do_update(msg); + assert_eq!(signer.do_final().unwrap(), sig); + let mut verifier = pk.create_verifier(Some(&[])).unwrap(); + verifier.do_update(msg); + verifier.do_verify_final(&sig).unwrap(); +} + +/// The same for RSASSA-PSS, salted and unsalted, where a refused context draws no salt. +#[test] +fn pss_refuses_a_context() { + use bouncycastle_core::hazmat::FixedSeedRNG; + use bouncycastle_rsa::rsassa_pss::NoSalt; + type Alg = RSASSA_PSS; + let (pk, sk) = key_pair(); + let (pk_pss, sk_pss) = (pk.key::(), sk.key::()); + let msg = b"no context to bind"; + let seed: [u8; 96] = core::array::from_fn(|i| i as u8); + + let sig = sk_pss.sign(&mut FixedSeedRNG::new(seed), msg, None).unwrap(); + // The empty context gives the signature the absent one gives, from the same draw. + assert_eq!(sk_pss.sign(&mut FixedSeedRNG::new(seed), msg, Some(&[])).unwrap(), sig); + pk_pss.verify(msg, None, &sig).unwrap(); + pk_pss.verify(msg, Some(&[]), &sig).unwrap(); + + for ctx in [&b"c"[..], b"a context"] { + // Refused before the salt is drawn: the next signature is the one a fresh RNG gives. + let mut rng = FixedSeedRNG::new(seed); + assert_eq!(sk_pss.sign(&mut rng, msg, Some(ctx)), Err(NO_CONTEXT)); + let mut out = [0xFFu8; 256]; + assert_eq!(sk_pss.sign_out(&mut rng, msg, Some(ctx), &mut out), Err(NO_CONTEXT)); + assert_eq!(out, [0u8; 256]); + assert!(matches!(sk_pss.create_signer(&mut rng, Some(ctx)), Err(NO_CONTEXT))); + assert_eq!(sk_pss.sign(&mut rng, msg, None).unwrap(), sig); + assert_eq!(pk_pss.verify(msg, Some(ctx), &sig), Err(NO_CONTEXT)); + assert!(matches!(pk_pss.create_verifier(Some(ctx)), Err(NO_CONTEXT))); + } + + let mut signer = sk_pss.create_signer(&mut FixedSeedRNG::new(seed), Some(&[])).unwrap(); + signer.do_update(msg); + assert_eq!(signer.do_final().unwrap(), sig); + let mut verifier = pk_pss.create_verifier(Some(&[])).unwrap(); + verifier.do_update(msg); + verifier.do_verify_final(&sig).unwrap(); + + // Unsalted PSS signs through the deterministic role. + type Unsalted = RSASSA_PSS>; + let (pk_ns, sk_ns) = (pk.key::(), sk.key::()); + let sig = sk_ns.sign_deterministic(msg, None).unwrap(); + assert_eq!(sk_ns.sign_deterministic(msg, Some(&[])).unwrap(), sig); + pk_ns.verify(msg, Some(&[]), &sig).unwrap(); + assert_eq!(sk_ns.sign_deterministic(msg, Some(b"a context")), Err(NO_CONTEXT)); + assert!(matches!(sk_ns.create_signer_deterministic(Some(b"a context")), Err(NO_CONTEXT))); + assert_eq!(pk_ns.verify(msg, Some(b"a context"), &sig), Err(NO_CONTEXT)); + assert!(matches!(pk_ns.create_verifier(Some(b"a context")), Err(NO_CONTEXT))); +} diff --git a/crypto/rsa/tests/rsasve_hkdf_tests.rs b/crypto/rsa/tests/rsasve_hkdf_tests.rs new file mode 100644 index 000000000..713160feb --- /dev/null +++ b/crypto/rsa/tests/rsasve_hkdf_tests.rs @@ -0,0 +1,149 @@ +//! RSASVE with the secret value derived through HKDF, `RSASVE_HKDF`: the core framework +//! suite over the pairing, what the derivation is (HKDF by hand over the raw `Z`), the names and +//! strengths, and the parameters' length and info. + +use bouncycastle_core::errors::KEMError; +use bouncycastle_core::kdf_params::{KdfParams, KeyLen}; +use bouncycastle_core::kem_key::{DecapsulatingKey, EncapsulatingKey}; +use bouncycastle_core::key_material::{KeyMaterial, KeyMaterial0, KeyMaterialTrait, KeyType}; +use bouncycastle_core::security_strength::SecurityStrength; +use bouncycastle_core::traits::{Algorithm, AlgorithmInfo, KEMDecapsulator}; +use bouncycastle_core_test_framework::DUMMY_SEED; +use bouncycastle_core_test_framework::kem::TestFrameworkKEM; +use bouncycastle_hkdf::HkdfDescription; +use bouncycastle_rng::DefaultRNG; +use bouncycastle_rsa::rsasve::{RsaKEMPrivateKey, RsaKEMPublicKey}; +use bouncycastle_rsa::rsasve_kdf::RSASVE_HKDF; +use bouncycastle_rsa::{RSA2048, RSA3072, RSA4096}; +use bouncycastle_sha2::hkdf::HKDF_SHA256; +use bouncycastle_sha2::{SHA256, SHA384, SHA512}; + +// A genuine RSA-2048 key pair (the crate docs' example key, Wycheproof's +// rsa_pkcs1_2048_sig_gen_test.json first SHA-256 group): key generation is seconds in a debug +// build, so the tests share this one. +const P: [u64; 16] = [ + 0x0ea36cfb3a5b18f1, 0x48a6e65332119129, 0x110ad9e7b48a1c93, 0x569156b90113e2e9, + 0xe79813a575cfad9c, 0x69d659d143ec6f17, 0xe81e6bab5ddaa783, 0xbff1c5b80a69f788, + 0x978f6c35814f50ee, 0xe6a289ad4cfbf78f, 0x34d5681e5809d415, 0xbb028bda42eeb5d2, + 0x41c56e4de086b0d5, 0x58b8d1e24f3b55d0, 0xfb5248247d98cb7d, 0xdc431050f782e894, +]; +const Q: [u64; 16] = [ + 0x669f140cfbc20f25, 0xb97bb03677207d95, 0xfd4e06f3ed7299d4, 0x160f90536abc9492, + 0xf5b131f39098f7bc, 0xae8d72c57088d7ab, 0x89b94fbde542aba9, 0x3d3f9880ec47d5e0, + 0x1378a6868af3b7a0, 0x5544070beb057c94, 0x16611debc472fac4, 0xe500ffb79f5b8868, + 0x308a5e32196603b2, 0xea5fb19eb4eabc38, 0x122273ae3222b598, 0xbd1a81e7977f9898, +]; +const D_P: [u64; 16] = [ + 0x209f33f09515d7c1, 0xb4a9b37656917205, 0x276933bb07e4efb9, 0x8c14019808e00414, + 0x289f96da220711e5, 0xfbbd2923d31532fe, 0xc06b414e61c0e1e7, 0x4c23c4588488961d, + 0x4dc48ae34514759c, 0x9c786961ae3e2c35, 0x497e8d9c650688e0, 0x18bf08472612dbe5, + 0x8885fb161870ee12, 0xf21d7c1479d99d47, 0x9121d91952ffd1c7, 0xa94b528b28f29159, +]; +const D_Q: [u64; 16] = [ + 0xf7597ffb68011d8d, 0x7b3cc538c4bab8c9, 0xa8fa480a81a925af, 0x6d6ede7251a383bf, + 0x8a63f788ce3a0f85, 0x0b920502eb478bc9, 0x7e37e755edfe70d9, 0x9cf9948422a16555, + 0x0d6d9ea1f2ef71fd, 0xf7efa32ea0cb6e00, 0x0629b114ca7f780f, 0xcf51176359654348, + 0x540cdcbd4ad35435, 0x31c02ff1a2bc437c, 0xff2503df78bafed5, 0x3af0e72a933aef09, +]; +const Q_INV: [u64; 16] = [ + 0x552fe4bfce945f7b, 0x67e50c999c67247b, 0xfb54ef17be3b2853, 0x241f5921b5ad3983, + 0x02de5eccd143cf31, 0x74e45f6fcc60f216, 0xafa5428a74f12708, 0x88d42294b6a2759b, + 0xe923e1097c0c562f, 0xc968b48a91c38b5b, 0x933e85179c0320b0, 0x7993d0445f758d51, + 0x9bfc042ee0924b1b, 0x41f956d90fa8a793, 0xee7a87b6483a66ee, 0x2640fbfbcfefb163, +]; + +const INFO: &[u8] = b"rsasve hkdf tests"; + +fn key_pair() -> Result<(RsaKEMPublicKey, RsaKEMPrivateKey), KEMError> { + let sk = RsaKEMPrivateKey::::from_crt_components(&P, &Q, &D_P, &D_Q, &Q_INV, 0x10001)?; + let pk = RsaKEMPublicKey::::new(sk.n(), 65537)?; + Ok((pk, sk)) +} + +/// A 32-byte salt of the kind a protocol fixes: typed, not secret. +fn salt() -> KeyMaterial<32> { + KeyMaterial::<32>::from_bytes_as_type(&DUMMY_SEED[..32], KeyType::CryptographicRandom).unwrap() +} + +#[test] +fn core_framework_suite() { + let salt = salt(); + let hkdf = HkdfDescription::::with_salt(&salt).unwrap(); + let params = KdfParams::new(&hkdf, INFO, KeyLen::<32>); + TestFrameworkKEM::new(false, true) + .test_kem::, 32>, _, _, 256, 32>( + key_pair, params, false, + ); + let no_salt = HkdfDescription::::new(); + let params = KdfParams::new(&no_salt, b"", KeyLen::<64>); + TestFrameworkKEM::new(false, true) + .test_kem::, 64>, _, _, 256, 64>( + key_pair, params, false, + ); +} + +/// The key is HKDF-Hash(salt, Z, info) over the raw RSASVE secret value, the length the +/// parameters name, labelled at the lesser of the modulus's and the hash's strength. +#[test] +fn the_derivation_is_hkdf_over_z() { + let (pk, sk) = key_pair().unwrap(); + let salt = salt(); + let hkdf = HkdfDescription::::with_salt(&salt).unwrap(); + let params = KdfParams::new(&hkdf, INFO, KeyLen::<32>); + let mut rng = DefaultRNG::default(); + + let (key, ct) = pk.encaps(&mut rng, params).unwrap(); + assert_eq!(key.key_len(), 32); + assert_eq!(key.key_type(), KeyType::CryptographicRandom); + assert_eq!(key.security_strength(), SecurityStrength::_112bit); + assert_eq!(sk.decaps(&ct, params).unwrap(), key); + + let z = sk.decaps(&ct, ()).unwrap(); + assert_eq!(z.key_len(), 256); + let mut expected = KeyMaterial::<32>::new(); + HKDF_SHA256::extract_and_expand_out(&salt, &z, INFO, 32, &mut expected).unwrap(); + assert!(key.equals(&expected)); + + // Another info is another key; the absent salt is another key; a shorter length is the + // prefix (RFC 5869 Section 2.3), which is why two keys take two infos. + let other = KdfParams::new(&hkdf, b"another context", KeyLen::<32>); + assert!(!sk.decaps(&ct, other).unwrap().equals(&key)); + let absent = KeyMaterial0::new(); + let no_salt = HkdfDescription::::with_salt(&absent).unwrap(); + assert!(!sk.decaps(&ct, KdfParams::new(&no_salt, INFO, KeyLen::<32>)).unwrap().equals(&key)); + let short = sk.decaps(&ct, KdfParams::new(&hkdf, INFO, KeyLen::<16>)).unwrap(); + assert_eq!(short.ref_to_bytes(), &key.ref_to_bytes()[..16]); + assert_eq!(short.security_strength(), SecurityStrength::_112bit); + let long = sk.decaps(&ct, KdfParams::new(&hkdf, INFO, KeyLen::<{ 255 * 32 }>)).unwrap(); + assert_eq!(&long.ref_to_bytes()[..32], key.ref_to_bytes()); + + // A ciphertext RSASVE refuses is refused here, with the buffer left zeroized. + let mut ss = KeyMaterial::<32>::from_bytes_as_type(&DUMMY_SEED[..32], KeyType::Seed).unwrap(); + assert!(matches!( + sk.create_decapsulator(params).unwrap().decaps_out(&[0u8; 256], &mut ss), + Err(KEMError::DecapsulationFailed) + )); + assert_eq!(ss.key_len(), 0); + assert_eq!(ss.key_type(), KeyType::Zeroized); +} + +#[test] +fn names_and_strengths() { + assert_eq!(RSASVE_HKDF::::ALG_NAME, "RSASVE-2048-HKDF-SHA256"); + assert_eq!(RSASVE_HKDF::::MAX_SECURITY_STRENGTH, SecurityStrength::_112bit); + assert_eq!(RSASVE_HKDF::::ALG_NAME, "RSASVE-3072-HKDF-SHA256"); + assert_eq!(RSASVE_HKDF::::MAX_SECURITY_STRENGTH, SecurityStrength::_128bit); + assert_eq!(RSASVE_HKDF::::ALG_NAME, "RSASVE-4096-HKDF-SHA384"); + assert_eq!(RSASVE_HKDF::::MAX_SECURITY_STRENGTH, SecurityStrength::_128bit); + assert_eq!(RSASVE_HKDF::::MAX_SECURITY_STRENGTH, SecurityStrength::_112bit); + assert_eq!(RSASVE_HKDF::::MAX_LEN, 255 * 32); + + let (pk, sk) = key_pair().unwrap(); + let hkdf = HkdfDescription::::new(); + let params = KdfParams::new(&hkdf, INFO, KeyLen::<32>); + assert_eq!(pk.create_encapsulator(params).unwrap().alg_name(), "RSASVE-2048-HKDF-SHA256"); + let worker = sk.create_decapsulator(params).unwrap(); + assert_eq!(worker.alg_name(), "RSASVE-2048-HKDF-SHA256"); + assert_eq!(worker.max_security_strength(), SecurityStrength::_112bit); + let _: &dyn KEMDecapsulator<256, 32> = &worker; +} diff --git a/crypto/rsa/tests/rsasve_tests.rs b/crypto/rsa/tests/rsasve_tests.rs new file mode 100644 index 000000000..12f987b85 --- /dev/null +++ b/crypto/rsa/tests/rsasve_tests.rs @@ -0,0 +1,654 @@ +//! RSASVE (SP 800-56B Rev. 2 §7.2.1) as a KEM, at every modulus size that has one. +//! +//! Known-answer sources, all in `bc-test-data/crypto/rsa/`: +//! +//! * `acvp/KAS-IFC-SSC-Sp800-56Br2.json`: NIST ACVP-Server's sample KAS-IFC-SSC vector set +//! (`gen-val/json-files/KAS-IFC-SSC-Sp800-56Br2/internalProjection.json`). Its KAS1 (2048-bit) and +//! KAS2 (3072-bit) groups with CRT keys (`rsakpg1-crt`/`rsakpg2-crt`) carry RSASVE ciphertexts +//! with their secret values in both directions: `serverZ^iutE = serverC` and `iutZ^serverE = +//! iutC`. They exercise `decaps` directly, and `encaps` through an RNG that emits the +//! vector's `Z`, since RSASVE.GENERATE's step 2.b turns the RNG's bytes straight into `z`. The +//! `failChangedZ` cases carry a `Z` inconsistent with `C`, which must not be recovered. +//! * `acvp/RSA-DecryptionPrimitive-Sp800-56Br2.json`: ACVP-Server's RSADP vector set +//! (`gen-val/json-files/RSA-DecryptionPrimitive-Sp800-56Br2/internalProjection.json`). Its CRT +//! groups (2048/3072/4096) are RSASVE.RECOVER's step 3.b, including the out-of-range +//! ciphertexts (`c <= 1` or `c >= n - 1`) that step 3.c must reject. Their public exponents +//! are 30 to 56 bits wide, so the passing cases also pin RSAEP under such an `e`, through +//! `encaps` with an RNG that emits the vector's `pt`. The basic-format groups +//! (`keyMode: standard`, no CRT components) are skipped, since this crate has no `(n, d)` key +//! type. +//! * `openssl/openssl_rsasve_.json`: produced by `openssl/ossl_rsasve.c` against OpenSSL +//! 3.0.13's `EVP_PKEY_encapsulate` with `EVP_PKEY_CTX_set_kem_op(ctx, "RSASVE")`. Each file has +//! one freshly generated key (`e = 65537`) and five OpenSSL encapsulations `(C, Z)` under it. +//! These are the only third-party vectors at 8192 bits, and they are what the trait-conformance +//! suites below use as their fixed keys. + +use bouncycastle_core::errors::{KEMError, KeyDecodingError, RNGError}; +use bouncycastle_core::hazmat::FixedSeedRNG; +use bouncycastle_core::hex::decode as hex_decode; +use bouncycastle_core::kem_key::{DecapsulatingKey, EncapsulatingKey}; +use bouncycastle_core::key_material::{KeyMaterialTrait, KeyType}; +use bouncycastle_core::security_strength::SecurityStrength; +use bouncycastle_core::traits::{PrivateKey, PublicKey}; +use bouncycastle_core_test_framework::kem::{TestFrameworkKEM, TestFrameworkKEMKeys}; +use bouncycastle_rng::DefaultRNG; +use serde_json::Value; +use std::fs; +use std::path::Path; + +const TEST_DATA_PATH_RELATIVE: &str = "../../../bc-test-data/crypto/rsa"; +const TEST_DATA_PATH: &str = "../bc-test-data/crypto/rsa"; + +fn get_test_data(filename: &str) -> Value { + for dir in [TEST_DATA_PATH_RELATIVE, TEST_DATA_PATH] { + let path = format!("{dir}/{filename}"); + if Path::new(&path).exists() { + return serde_json::from_str(&fs::read_to_string(path).unwrap()).unwrap(); + } + } + panic!( + "bc-test-data not found (looked for {filename} in {TEST_DATA_PATH_RELATIVE:?} and \ + {TEST_DATA_PATH:?}); this suite requires it rather than skipping" + ); +} + +/// A big-endian hex integer as exactly `LEN` bytes, left-padded with zeros. ACVP drops leading +/// zero nibbles from some values (its `passLeadingZeroNibble` cases), so the input may be shorter. +fn be_bytes(hex: &str) -> [u8; LEN] { + let padded = if hex.len() % 2 == 1 { format!("0{hex}") } else { hex.to_string() }; + let bytes = hex_decode(&padded).expect("valid hex"); + assert!(bytes.len() <= LEN, "value wider than {LEN} bytes"); + let mut out = [0u8; LEN]; + out[LEN - bytes.len()..].copy_from_slice(&bytes); + out +} + +/// A big-endian hex integer as `L` little-endian limbs (the key constructors' representation). +fn limbs(hex: &str) -> [u64; L] { + let padded = if hex.len() % 2 == 1 { format!("0{hex}") } else { hex.to_string() }; + let bytes = hex_decode(&padded).expect("valid hex"); + assert!(bytes.len() <= 8 * L, "value wider than {L} limbs"); + let mut wide = vec![0u8; 8 * L - bytes.len()]; + wide.extend_from_slice(&bytes); + let mut out = [0u64; L]; + for i in 0..L { + let start = 8 * L - (i + 1) * 8; + out[i] = u64::from_be_bytes(wide[start..start + 8].try_into().unwrap()); + } + out +} + +/// An `RNG` whose stream is `bytes` repeated, reporting `strength`. +fn rng_emitting( + bytes: [u8; N], + strength: SecurityStrength, +) -> FixedSeedRNG<[u8; N]> { + let mut rng = FixedSeedRNG::new(bytes); + rng.set_security_strength(strength); + rng +} + +macro_rules! rsasve_suite { + ($module:ident, $size:ident, $marker:ident, $bits:literal, $strength:expr, $weaker:expr) => { + mod $module { + use super::*; + use bouncycastle_rsa::$size::{CT_LEN, PK_LEN, SK_LEN, SS_LEN}; + + type PK = bouncycastle_rsa::rsasve::RsaKEMPublicKey; + type SK = bouncycastle_rsa::rsasve::RsaKEMPrivateKey; + + fn openssl_vectors() -> Value { + get_test_data(&format!("openssl/openssl_rsasve_{}.json", $bits)) + } + + fn sk_from(v: &Value, p: &str, q: &str, dp: &str, dq: &str, qinv: &str) -> SK { + SK::from_crt_components( + &limbs(v[p].as_str().unwrap()), + &limbs(v[q].as_str().unwrap()), + &limbs(v[dp].as_str().unwrap()), + &limbs(v[dq].as_str().unwrap()), + &limbs(v[qinv].as_str().unwrap()), + v["e"].as_u64().unwrap(), + ) + .expect("vector CRT key must be accepted") + } + + fn openssl_keypair() -> Result<(PK, SK), KEMError> { + let v = openssl_vectors(); + let pk = PK::new(&limbs(v["n"].as_str().unwrap()), 65537)?; + let sk = sk_from(&v, "p", "q", "dP", "dQ", "qInv"); + Ok((pk, sk)) + } + + #[test] + fn lengths_are_nlen() { + assert_eq!(CT_LEN, $bits / 8); + assert_eq!(SS_LEN, $bits / 8); + assert_eq!(PK_LEN, $bits / 8 + 8); + assert_eq!(SK_LEN, 5 * $bits / 16 + 8); + } + + #[test] + fn kem_trait_conformance_suite() { + // Not deterministic (fresh `Z` per call). "Implicitly rejecting" in the test + // framework's sense: a corrupted but in-range ciphertext recovers a different `Z` + // rather than an error, since RSASVE has no redundancy to check. + TestFrameworkKEM::new(false, true).test_kem::<(), PK, SK, CT_LEN, SS_LEN>( + openssl_keypair, + (), + false, + ); + } + + #[test] + fn kem_key_trait_conformance_suite() { + TestFrameworkKEMKeys::new().test_keys::(openssl_keypair); + } + + #[test] + fn keys_round_trip_through_their_encoding() { + let (pk, sk) = openssl_keypair().unwrap(); + assert_eq!(PK::from_bytes(&pk.encode()).unwrap(), pk); + assert_eq!(SK::from_bytes(&sk.encode()).unwrap(), sk); + let mut pk_out = [0xAAu8; PK_LEN]; + assert_eq!(pk.encode_out(&mut pk_out), PK_LEN); + assert_eq!(pk_out, pk.encode()); + let mut sk_out = [0xAAu8; SK_LEN]; + assert_eq!(sk.encode_out(&mut sk_out), SK_LEN); + assert_eq!(sk_out, sk.encode()); + assert_eq!(pk.n(), sk.n()); + assert_eq!(pk.e(), 65537); + // `Display` names the KEM key type and the size, then the public data. + assert!(format!("{pk}").starts_with(&format!( + "RsaKEMPublicKey<{}> {{ n: ", + ::NAME + ))); + } + + /// OpenSSL encapsulated; this crate decapsulates. And the other way round: fed + /// OpenSSL's `Z` as its RNG output, `encaps` must produce OpenSSL's `C` exactly + /// (RSAEP is deterministic in `z`). + #[test] + fn openssl_rsasve_vectors() { + let v = openssl_vectors(); + let (pk, sk) = openssl_keypair().unwrap(); + let encs = v["encapsulations"].as_array().unwrap(); + assert_eq!(encs.len(), 5); + for enc in encs { + let c = be_bytes::(enc["C"].as_str().unwrap()); + let z = be_bytes::(enc["Z"].as_str().unwrap()); + + let ss = sk.decaps(&c, ()).unwrap(); + assert_eq!(ss.ref_to_bytes(), &z[..]); + + let (ss, ct) = + pk.encaps(&mut rng_emitting(z, SecurityStrength::_256bit), ()).unwrap(); + assert_eq!(ct, c); + assert_eq!(ss.ref_to_bytes(), &z[..]); + } + } + + #[test] + fn shared_secret_is_labelled_with_the_modulus_strength() { + let (pk, sk) = openssl_keypair().unwrap(); + let (ss, ct) = pk.encaps(&mut DefaultRNG::default(), ()).unwrap(); + assert_eq!(ss.key_len(), SS_LEN); + assert_eq!(ss.key_type(), KeyType::CryptographicRandom); + assert_eq!(ss.security_strength(), $strength); + let ss2 = sk.decaps(&ct, ()).unwrap(); + assert_eq!(ss2.key_len(), SS_LEN); + assert_eq!(ss2.key_type(), KeyType::CryptographicRandom); + assert_eq!(ss2.security_strength(), $strength); + assert_eq!(ss, ss2); + } + + /// SP 800-56B Rev. 2 §6.4.1.4.3 through the key and the size's forwarder: the RNG + /// is held to the size's strength, and with that strength validation gets as far + /// as the primality test, where a stream of zeros gives it no base. + #[test] + fn validate_reaches_the_size_and_checks_its_rng() { + let (_, sk) = openssl_keypair().unwrap(); + assert_eq!( + sk.validate(&mut rng_emitting([0u8; 64], $weaker)), + Err(KEMError::RNGError(RNGError::SecurityStrengthInsufficientForAlgorithm)) + ); + assert_eq!( + sk.validate(&mut rng_emitting([0u8; 64], $strength)), + Err(KEMError::GenericError( + "RNG produced no usable Miller-Rabin base in 128 draws" + )) + ); + } + + #[test] + fn encaps_accepts_exactly_the_modulus_strength_and_rejects_below_it() { + let (pk, _) = openssl_keypair().unwrap(); + assert!(pk.encaps(&mut rng_emitting([0x5Au8; CT_LEN], $strength), ()).is_ok()); + assert!(matches!( + pk.encaps(&mut rng_emitting([0x5Au8; CT_LEN], $weaker), ()), + Err(KEMError::RNGError(RNGError::SecurityStrengthInsufficientForAlgorithm)) + )); + } + + /// RSASVE.GENERATE step 2.c's boundaries, one draw at a time: `z` in {0, 1, n - 1, + /// all-ones} must be redrawn, and `z` in {2, n - 2} kept. + #[test] + fn generate_redraws_exactly_outside_one_to_n_minus_one() { + let (pk, sk) = openssl_keypair().unwrap(); + let n = be_bytes::(openssl_vectors()["n"].as_str().unwrap()); + let mut n_minus_1 = n; + n_minus_1[CT_LEN - 1] -= 1; // n is odd: no borrow + // Byte-wise `n - 2` needs no borrow only if `n`'s low byte is at least 3. + assert!(n[CT_LEN - 1] >= 3, "vector key's low byte makes n - 2 need a borrow"); + let mut n_minus_2 = n; + n_minus_2[CT_LEN - 1] -= 2; + let mut two = [0u8; CT_LEN]; + two[CT_LEN - 1] = 2; + let mut one = [0u8; CT_LEN]; + one[CT_LEN - 1] = 1; + let zero = [0u8; CT_LEN]; + let ones = [0xFFu8; CT_LEN]; + + for good in [two, n_minus_2] { + for bad in [zero, one, n_minus_1, n, ones] { + // The RNG emits `bad` then `good`: one rejected draw, then an accepted one. + let mut stream = [0u8; 2 * CT_LEN]; + stream[..CT_LEN].copy_from_slice(&bad); + stream[CT_LEN..].copy_from_slice(&good); + let (ss, ct) = pk + .encaps(&mut rng_emitting(stream, SecurityStrength::_256bit), ()) + .unwrap(); + assert_eq!(ss.ref_to_bytes(), &good[..]); + assert_eq!(sk.decaps(&ct, ()).unwrap().ref_to_bytes(), &good[..]); + } + } + } + + #[test] + fn generate_gives_up_on_an_rng_that_never_lands_in_range() { + let (pk, _) = openssl_keypair().unwrap(); + for stuck in [[0xFFu8; CT_LEN], [0u8; CT_LEN]] { + assert!(matches!( + pk.encaps(&mut rng_emitting(stuck, SecurityStrength::_256bit), ()), + Err(KEMError::GenericError(_)) + )); + } + // One in-range draw after `MAX_GENERATE_ATTEMPTS - 1` rejected ones still succeeds: + // the cap is exactly `MAX_GENERATE_ATTEMPTS` draws, not one fewer. + const ATTEMPTS: usize = bouncycastle_rsa::rsasve::MAX_GENERATE_ATTEMPTS; + let mut stream = vec![0xFFu8; ATTEMPTS * CT_LEN]; + stream[(ATTEMPTS - 1) * CT_LEN..].fill(0x5A); + let seed: [u8; ATTEMPTS * CT_LEN] = stream.try_into().unwrap(); + let mut rng = FixedSeedRNG::new(seed); + let (ss, _) = pk.encaps(&mut rng, ()).unwrap(); + assert_eq!(ss.ref_to_bytes(), &[0x5Au8; CT_LEN][..]); + } + + /// RSADP's step 1 range (§7.1.2.3): `1 < c < n - 1`. + #[test] + fn recover_rejects_exactly_outside_one_to_n_minus_one() { + let (_, sk) = openssl_keypair().unwrap(); + let n = be_bytes::(openssl_vectors()["n"].as_str().unwrap()); + let mut n_minus_1 = n; + n_minus_1[CT_LEN - 1] -= 1; + assert!(n[CT_LEN - 1] >= 3, "vector key's low byte makes n - 2 need a borrow"); + let mut n_minus_2 = n; + n_minus_2[CT_LEN - 1] -= 2; + let mut two = [0u8; CT_LEN]; + two[CT_LEN - 1] = 2; + let mut one = [0u8; CT_LEN]; + one[CT_LEN - 1] = 1; + + for bad in [[0u8; CT_LEN], one, n_minus_1, n, [0xFFu8; CT_LEN]] { + assert!(matches!(sk.decaps(&bad, ()), Err(KEMError::DecapsulationFailed))); + } + for good in [two, n_minus_2] { + assert!(sk.decaps(&good, ()).is_ok()); + } + } + + #[test] + fn public_key_validation() { + let v = openssl_vectors(); + let n = limbs(v["n"].as_str().unwrap()); + // SP 800-56B Rev. 2 §6.2.1: 65,537 <= e. + assert!(PK::new(&n, 65537).is_ok()); + assert!(PK::new(&n, 65539).is_ok()); + for e in [3u64, 17, 65535] { + assert!(matches!(PK::new(&n, e), Err(KEMError::DecodingError(_)))); + } + // Still rejected for being even (RsaPublicKey's own check). + assert!(matches!(PK::new(&n, 65538), Err(KEMError::DecodingError(_)))); + let mut even_n = n; + even_n[0] &= !1; + assert!(matches!(PK::new(&even_n, 65537), Err(KEMError::DecodingError(_)))); + // n must be exactly $bits bits: its top bit set. + let mut short_n = n; + let top = short_n.len() - 1; + short_n[top] &= !(1 << 63); + assert!(matches!(PK::new(&short_n, 65537), Err(KEMError::DecodingError(_)))); + // The same checks apply on decoding. + let (pk, _) = openssl_keypair().unwrap(); + let mut bytes = pk.encode(); + bytes[0] &= 0x7F; + assert!(matches!(PK::from_bytes(&bytes), Err(KeyDecodingError(_)))); + let mut bytes = pk.encode(); + bytes[PK_LEN - 8..].copy_from_slice(&3u64.to_be_bytes()); + assert!(matches!(PK::from_bytes(&bytes), Err(KeyDecodingError(_)))); + } + + #[test] + fn private_key_validation() { + let v = openssl_vectors(); + // RsaPrivateKey's own checks come through as DecodingError: p == q. + assert!(matches!( + SK::from_crt_components( + &limbs(v["p"].as_str().unwrap()), + &limbs(v["p"].as_str().unwrap()), + &limbs(v["dP"].as_str().unwrap()), + &limbs(v["dP"].as_str().unwrap()), + &limbs(v["qInv"].as_str().unwrap()), + 65537, + ), + Err(KEMError::DecodingError(_)) + )); + // p = 3, q = 5, dP = dQ = qInv = 1: every RsaPrivateKey check passes, but + // n = 15 has its top bit clear. + let mut p = [0u64; $bits / 128]; + p[0] = 3; + let mut q = [0u64; $bits / 128]; + q[0] = 5; + let mut small = [0u64; $bits / 128]; + small[0] = 1; + assert!(matches!( + SK::from_crt_components(&p, &q, &small, &small, &small, 65537), + Err(KEMError::DecodingError(_)) + )); + let (_, sk) = openssl_keypair().unwrap(); + let mut bytes = sk.encode(); + bytes[..$bits / 16].fill(0); // p = 0, which is even + assert!(matches!(SK::from_bytes(&bytes), Err(KeyDecodingError(_)))); + // SP 800-56B Rev. 2 §6.2.1: 65,537 <= e. These components are not a key under + // a smaller e, so the refusal is not pinned to that rule here: + // `keys_tests.rs` has genuine keys under small exponents. + assert_eq!(sk.e(), 65537); + for e in [3u64, 17, 65535] { + assert!(matches!( + SK::from_crt_components( + &limbs(v["p"].as_str().unwrap()), + &limbs(v["q"].as_str().unwrap()), + &limbs(v["dP"].as_str().unwrap()), + &limbs(v["dQ"].as_str().unwrap()), + &limbs(v["qInv"].as_str().unwrap()), + e, + ), + Err(KEMError::DecodingError(_)) + )); + let mut bytes = sk.encode(); + bytes[SK_LEN - 8..].copy_from_slice(&e.to_be_bytes()); + assert!(matches!(SK::from_bytes(&bytes), Err(KeyDecodingError(_)))); + } + } + } + }; +} + +rsasve_suite!( + rsa_2048_rsasve, + rsa_2048, + RSA2048, + 2048, + SecurityStrength::_112bit, + SecurityStrength::None +); +rsasve_suite!( + rsa_3072_rsasve, + rsa_3072, + RSA3072, + 3072, + SecurityStrength::_128bit, + SecurityStrength::_112bit +); +rsasve_suite!( + rsa_4096_rsasve, + rsa_4096, + RSA4096, + 4096, + SecurityStrength::_128bit, + SecurityStrength::_112bit +); +rsasve_suite!( + rsa_8192_rsasve, + rsa_8192, + RSA8192, + 8192, + SecurityStrength::_192bit, + SecurityStrength::_128bit +); + +/// ACVP KAS-IFC-SSC's KAS1 group (2048-bit, CRT IUT key, IUT as responder): the server +/// encapsulated to the IUT's key. Also checks `encaps` reproduces `serverC` from `serverZ`. +#[test] +fn acvp_kas_ifc_ssc_kas1_2048() { + use bouncycastle_rsa::rsa_2048::{CT_LEN, RSA2048KEMPrivateKey, RSA2048KEMPublicKey}; + let d = get_test_data("acvp/KAS-IFC-SSC-Sp800-56Br2.json"); + let group = d["testGroups"] + .as_array() + .unwrap() + .iter() + .find(|g| g["scheme"] == "KAS1" && g["keyGenerationMethod"] == "rsakpg1-crt") + .expect("KAS1 CRT group"); + assert_eq!(group["modulo"], 2048); + let (mut passed, mut failed) = (0, 0); + for t in group["tests"].as_array().unwrap() { + let s = |k: &str| t[k].as_str().unwrap(); + let e = u64::from_str_radix(s("iutE"), 16).unwrap(); + let sk = RSA2048KEMPrivateKey::from_crt_components( + &limbs(s("iutP")), + &limbs(s("iutQ")), + &limbs(s("iutDmp1")), + &limbs(s("iutDmq1")), + &limbs(s("iutIqmp")), + e, + ) + .unwrap(); + let pk = RSA2048KEMPublicKey::new(&limbs(s("iutN")), e).unwrap(); + let c = be_bytes::(s("serverC")); + let z = be_bytes::(s("serverZ")); + let recovered = sk.decaps(&c, ()).unwrap(); + if t["testPassed"].as_bool().unwrap() { + assert_eq!(recovered.ref_to_bytes(), &z[..], "tcId {}", t["tcId"]); + let (_, ct) = pk.encaps(&mut rng_emitting(z, SecurityStrength::_256bit), ()).unwrap(); + assert_eq!(ct, c, "tcId {}", t["tcId"]); + passed += 1; + } else { + assert_ne!(recovered.ref_to_bytes(), &z[..], "tcId {}", t["tcId"]); + failed += 1; + } + } + assert_eq!((passed, failed), (4, 1)); +} + +/// ACVP KAS-IFC-SSC's KAS2 CRT group (3072-bit, both parties' keys CRT): one RSASVE in each +/// direction per case. +#[test] +fn acvp_kas_ifc_ssc_kas2_3072() { + use bouncycastle_rsa::rsa_3072::{CT_LEN, RSA3072KEMPrivateKey, RSA3072KEMPublicKey}; + let d = get_test_data("acvp/KAS-IFC-SSC-Sp800-56Br2.json"); + let group = d["testGroups"] + .as_array() + .unwrap() + .iter() + .find(|g| g["scheme"] == "KAS2" && g["keyGenerationMethod"] == "rsakpg2-crt") + .expect("KAS2 CRT group"); + assert_eq!(group["modulo"], 3072); + let (mut passed, mut failed) = (0, 0); + for t in group["tests"].as_array().unwrap() { + let s = |k: &str| t[k].as_str().unwrap(); + let key = |who: &str| { + let e = u64::from_str_radix(s(&format!("{who}E")), 16).unwrap(); + let sk = RSA3072KEMPrivateKey::from_crt_components( + &limbs(s(&format!("{who}P"))), + &limbs(s(&format!("{who}Q"))), + &limbs(s(&format!("{who}Dmp1"))), + &limbs(s(&format!("{who}Dmq1"))), + &limbs(s(&format!("{who}Iqmp"))), + e, + ) + .unwrap(); + let pk = RSA3072KEMPublicKey::new(&limbs(s(&format!("{who}N"))), e).unwrap(); + (pk, sk) + }; + let (iut_pk, iut_sk) = key("iut"); + let (server_pk, server_sk) = key("server"); + // (recipient pk, recipient sk, C, Z): serverC was made to the IUT's key, iutC to the + // server's. + let directions = [ + (&iut_pk, &iut_sk, s("serverC"), s("serverZ")), + (&server_pk, &server_sk, s("iutC"), s("iutZ")), + ]; + let ok = t["testPassed"].as_bool().unwrap(); + for (pk, sk, c, z) in directions { + let c = be_bytes::(c); + let z = be_bytes::(z); + let recovered = sk.decaps(&c, ()).unwrap(); + if ok { + assert_eq!(recovered.ref_to_bytes(), &z[..], "tcId {}", t["tcId"]); + let (_, ct) = + pk.encaps(&mut rng_emitting(z, SecurityStrength::_256bit), ()).unwrap(); + assert_eq!(ct, c, "tcId {}", t["tcId"]); + } else { + assert_ne!(recovered.ref_to_bytes(), &z[..], "tcId {}", t["tcId"]); + } + } + if ok { + passed += 1; + } else { + failed += 1; + } + } + assert_eq!((passed, failed), (4, 1)); +} + +/// ACVP's SP 800-56B Rev. 2 RSADP vectors, CRT groups: RSASVE.RECOVER is RSADP plus I2BS, so +/// `decaps(ct)` must be `pt` at `nLen` bytes, or `DecapsulationFailed` for the out-of-range +/// ciphertexts ACVP marks as failing; and for the passing cases RSASVE.GENERATE over a draw of +/// `pt` must give `ct` under the vector's `(n, e)`, all but three of whose exponents are wider +/// than 32 bits. +macro_rules! acvp_rsadp { + ($name:ident, $size:ident, $marker:ident, $bits:literal, $wide:literal) => { + #[test] + fn $name() { + use bouncycastle_rsa::$size::CT_LEN; + type SK = bouncycastle_rsa::rsasve::RsaKEMPrivateKey; + type PK = bouncycastle_rsa::rsasve::RsaKEMPublicKey; + let d = get_test_data("acvp/RSA-DecryptionPrimitive-Sp800-56Br2.json"); + let group = d["testGroups"] + .as_array() + .unwrap() + .iter() + .find(|g| g["keyMode"] == "crt" && g["modulo"] == $bits) + .expect("CRT group"); + let (mut passed, mut failed, mut wide) = (0, 0, 0); + for t in group["tests"].as_array().unwrap() { + let s = |k: &str| t[k].as_str().unwrap(); + let e = u64::from_str_radix(s("e"), 16).expect("every exponent here fits a u64"); + wide += usize::from(e > u64::from(u32::MAX)); + let sk = SK::from_crt_components( + &limbs(s("p")), + &limbs(s("q")), + &limbs(s("dmp1")), + &limbs(s("dmq1")), + &limbs(s("iqmp")), + e, + ) + .unwrap(); + let ct = be_bytes::(s("ct")); + if t["testPassed"].as_bool().unwrap() { + let pt = be_bytes::(s("pt")); + assert_eq!( + sk.decaps(&ct, ()).unwrap().ref_to_bytes(), + &pt[..], + "tcId {}", + t["tcId"] + ); + let pk = PK::new(&limbs(s("n")), e).unwrap(); + let (_, c) = + pk.encaps(&mut rng_emitting(pt, SecurityStrength::_256bit), ()).unwrap(); + assert_eq!(c, ct, "tcId {}", t["tcId"]); + passed += 1; + } else { + assert!( + matches!(sk.decaps(&ct, ()), Err(KEMError::DecapsulationFailed)), + "tcId {}", + t["tcId"] + ); + failed += 1; + } + } + assert_eq!((passed, failed), (11, 4)); + assert_eq!(wide, $wide, "exponents wider than 32 bits"); + } + }; +} + +acvp_rsadp!(acvp_rsadp_crt_2048, rsa_2048, RSA2048, 2048, 14); +acvp_rsadp!(acvp_rsadp_crt_3072, rsa_3072, RSA3072, 3072, 15); +acvp_rsadp!(acvp_rsadp_crt_4096, rsa_4096, RSA4096, 4096, 13); + +/// `RSASVE::keygen`'s pairs are usable KEM keys (a genuine generation, at the smallest size +/// only: key generation is the slow part), and `keygen` enforces the RNG strength. +#[test] +fn keygen_produces_working_kem_keys() { + use bouncycastle_rsa::rsa_2048::RSASVE; + let (pk, sk) = RSASVE::keygen(&mut DefaultRNG::default()).unwrap(); + assert_eq!(pk.e(), 65537); + assert_eq!(pk.n(), sk.n()); + let (ss, ct) = pk.encaps(&mut DefaultRNG::default(), ()).unwrap(); + assert_eq!(sk.decaps(&ct, ()).unwrap(), ss); + + // A stuck RNG exhausts FIPS 186-5 A.1.3's candidate limit (see `keygen_tests.rs`'s + // `keygen_gives_up_on_a_stuck_rng`), and the KEM keygen passes that error through + // as `GenericError` with key generation's own message, not a generic one. + let mut stuck = FixedSeedRNG::new([0x42u8; 64]); + match RSASVE::keygen(&mut stuck) { + Err(KEMError::GenericError(msg)) => assert!(msg.contains("candidate limit"), "{msg}"), + other => panic!("expected GenericError, got {other:?}"), + } + + let mut weak = FixedSeedRNG::new([0x5Au8; 64]); + weak.set_security_strength(SecurityStrength::None); + assert!(matches!( + RSASVE::keygen(&mut weak), + Err(KEMError::RNGError(RNGError::SecurityStrengthInsufficientForAlgorithm)) + )); +} + +/// `RSASVE::keygen` at the larger sizes, following `keygen_tests.rs`: 3072 runs by default, and +/// 4096/8192 are `#[ignore]`d for the same reason as there. +macro_rules! kem_keygen_round_trip { + ($name:ident, $size:ident $(, $ignore:meta)?) => { + #[test] + $(#[$ignore])? + fn $name() { + use bouncycastle_rsa::$size::RSASVE; + let (pk, sk) = RSASVE::keygen(&mut DefaultRNG::default()).unwrap(); + assert_eq!(pk.e(), 65537); + assert_eq!(pk.n(), sk.n()); + let (ss, ct) = pk.encaps(&mut DefaultRNG::default(), ()).unwrap(); + assert_eq!(sk.decaps(&ct, ()).unwrap(), ss); + } + }; +} + +kem_keygen_round_trip!(kem_keygen_3072_round_trips, rsa_3072); +kem_keygen_round_trip!( + kem_keygen_4096_round_trips, + rsa_4096, + ignore = "tens of minutes in a debug build: run with --release --ignored" +); +kem_keygen_round_trip!( + kem_keygen_8192_round_trips, + rsa_8192, + ignore = "tens of minutes in a debug build: run with --release --ignored" +); diff --git a/crypto/utils/src/const_str.rs b/crypto/utils/src/const_str.rs index 1603d4480..ad4f9d93e 100644 --- a/crypto/utils/src/const_str.rs +++ b/crypto/utils/src/const_str.rs @@ -31,6 +31,31 @@ impl ConstStr { Self { buf, len } } + /// The decimal digits of `n`, which must fit in `N` bytes: a longer result is a compile-time + /// error where the constant is evaluated. For a number in an algorithm name, such as a salt + /// length. + pub const fn decimal(n: usize) -> Self { + let mut digits = [0u8; 20]; + let mut count = 0; + let mut rest = n; + loop { + digits[count] = b'0' + (rest % 10) as u8; + count += 1; + rest /= 10; + if rest == 0 { + break; + } + } + let mut buf = [0u8; N]; + let mut i = 0; + while i < count { + assert!(i < N, "ConstStr::decimal: the digits do not fit in N bytes"); + buf[i] = digits[count - 1 - i]; + i += 1; + } + Self { buf, len: count } + } + /// The string. pub const fn as_str(&self) -> &str { match core::str::from_utf8(self.buf.split_at(self.len).0) { diff --git a/crypto/utils/tests/const_str_tests.rs b/crypto/utils/tests/const_str_tests.rs index 613982902..a534fb960 100644 --- a/crypto/utils/tests/const_str_tests.rs +++ b/crypto/utils/tests/const_str_tests.rs @@ -50,3 +50,21 @@ fn multibyte_parts_stay_valid_utf8() { const S: ConstStr<16> = ConstStr::concat(&["🚨", "-", "ü"]); assert_eq!(S.as_str(), "🚨-ü"); } + +#[test] +fn decimal_digits_of_a_number() { + const ZERO: ConstStr<1> = ConstStr::decimal(0); + assert_eq!(ZERO.as_str(), "0"); + const ONE_DIGIT: ConstStr<8> = ConstStr::decimal(7); + assert_eq!(ONE_DIGIT.as_str(), "7"); + const SALT: ConstStr<8> = ConstStr::decimal(32); + assert_eq!(SALT.as_str(), "32"); + assert_eq!(SALT.len(), 2); + const EXACT: ConstStr<3> = ConstStr::decimal(100); + assert_eq!(EXACT.as_str(), "100"); + const MAX: ConstStr<20> = ConstStr::decimal(usize::MAX); + assert_eq!(MAX.as_str(), "18446744073709551615"); + const IN_NAME: ConstStr<32> = + ConstStr::concat(&["-MGF1-SHA256-", ConstStr::<8>::decimal(32).as_str()]); + assert_eq!(IN_NAME.as_str(), "-MGF1-SHA256-32"); +} diff --git a/dev_scripts/check_oaep_ct.sh b/dev_scripts/check_oaep_ct.sh new file mode 100755 index 000000000..d8d8dd249 --- /dev/null +++ b/dev_scripts/check_oaep_ct.sh @@ -0,0 +1,93 @@ +#!/usr/bin/env bash +# Checks that the EME-OAEP decoding (`decode_out` in crypto/rsa/src/eme_oaep.rs) does nothing +# that depends on the encoded message, in two ways, over dev_scripts/oaep_ct_harness, which +# includes that file by path. +# +# 1. On the host, under valgrind memcheck, with the encoded message left undefined: memcheck +# reports any conditional jump or address computed from it. Both paths (a message of any +# length, and of an exact length) must be clean, and the control, a variable-time search for +# the separator, must be reported, so that a memcheck that reports nothing is noticed. +# 2. On the targets whose multiply is not fixed-latency, in the assembly: the decode must hold +# no multiply or divide, and no call but the buffer clear, the two MGF calls and the panics +# of its length checks. The two MGF calls must be found, so that a grep that matches nothing +# is noticed. The decode's loops branch on lengths, so branches are not grepped for; the +# memcheck run is what covers them. +# +# sudo apt-get install valgrind +# rustup toolchain install nightly --profile minimal --component rust-src +# ./dev_scripts/check_oaep_ct.sh # thumbv6m-none-eabi riscv32i-unknown-none-elf +# ./dev_scripts/check_oaep_ct.sh thumbv6m-none-eabi +set -euo pipefail + +cd "$(dirname "$0")/oaep_ct_harness" +TARGETS=${*:-"thumbv6m-none-eabi riscv32i-unknown-none-elf"} +status=0 + +if ! command -v valgrind >/dev/null; then + echo "FAIL: valgrind is not installed, so the memcheck run cannot be made" + exit 2 +fi +rm -rf target +cargo build --release --bin memcheck +for mode in any exact control; do + rc=0 + valgrind -q --error-exitcode=9 target/release/memcheck "$mode" >"target/memcheck-$mode.log" 2>&1 || rc=$? + case "$mode:$rc" in + control:9) echo "ok memcheck control: the variable-time search is reported" ;; + control:*) echo "FAIL memcheck control: exit $rc, the variable-time search was not reported, so a clean run proves nothing" + status=1 ;; + *:0) echo "ok memcheck $mode: nothing depends on the encoded message" ;; + *) echo "FAIL memcheck $mode: exit $rc" + cat "target/memcheck-$mode.log" + status=1 ;; + esac +done + +# Prints the instruction lines of the function whose mangled symbol contains $2 in $1. +body() { + awk -v f="$2" '$0 ~ f && /:$/ { on = 1 } on { print } on && /^\.Lfunc_end/ { exit }' "$1" | + grep -vE '^\s*(\.|@|#|//)' | grep -vE ':\s*$' || true +} + +for t in $TARGETS; do + case "$t" in + thumb*|arm*) + arith='\b(mul|muls|smull|umull|mla|sdiv|udiv)\b|__aeabi_(l?mul|u?l?divmod|u?idiv)|__(u?div|u?mod|mul)' + call='\b(bl|blx)\b' ;; + riscv*) + arith='\b(mul|mulh|mulhu|mulhsu|div|divu|rem|remu)\b|__(u?div|u?mod|mul)' + call='\b(call|jalr|tail)\b' ;; + *) echo "no mnemonic table for $t"; exit 2 ;; + esac + + # `--emit asm` writes beside the intermediate artifacts, which newer cargo keeps in a build + # directory separate from the target directory; pinning both to `target` keeps the file + # findable on every cargo. + cargo +nightly rustc --release --lib --target "$t" -Zbuild-std=core \ + --config 'build.build-dir="target"' -- --emit asm + asm=$(find target -name 'oaep_ct_harness-*.s' -path "*$t*" | head -n 1) + if [ -z "$asm" ]; then + echo "FAIL $t: no oaep_ct_harness-*.s under $(pwd)/target" + exit 2 + fi + + n=$(body "$asm" decode_out | wc -l) + mgf=$(body "$asm" decode_out | grep -E "$call" | grep -c 'mgf1_xor' || true) + hits=$(body "$asm" decode_out | grep -cE "$arith" || true) + other=$(body "$asm" decode_out | grep -E "$call" | grep -vE 'mgf1_xor|memset|memclr|panic' || true) + if [ "$n" -eq 0 ]; then + echo "FAIL $t decode_out: not found in the assembly (renamed or inlined?), nothing was checked" + status=1 + elif [ "$mgf" -ne 2 ]; then + echo "FAIL $t decode_out: $mgf MGF call(s) found where two are made, so the grep proves nothing" + status=1 + elif [ "$hits" -ne 0 ] || [ -n "$other" ]; then + echo "FAIL $t decode_out: a multiply, divide or unexpected call in $n instructions" + body "$asm" decode_out | grep -E "$arith" || true + echo "$other" + status=1 + else + echo "ok $t decode_out: no multiply, divide or unexpected call in $n instructions" + fi +done +exit $status diff --git a/dev_scripts/check_rsa_ct.sh b/dev_scripts/check_rsa_ct.sh new file mode 100755 index 000000000..2d6125280 --- /dev/null +++ b/dev_scripts/check_rsa_ct.sh @@ -0,0 +1,57 @@ +#!/usr/bin/env bash +# Checks that the RSA private-key arithmetic does nothing that depends on the key, on the host, +# under valgrind memcheck, over dev_scripts/rsa_ct_harness, which runs the arithmetic with the +# secrets left undefined: memcheck then reports any conditional jump or address computed from +# them. The checked exponentiation and the congruences are not public API (every public +# operation over them branches on their verdict, which memcheck would report), so the library +# is built here with `--cfg bouncycastle_rsa_ct_harness`, which adds a module that names them +# and changes nothing else. +# +# - context: `MontgomeryContext::for_secret_modulus` over an undefined modulus, the setup the +# CRT makes over p and over q in every private-key operation. +# - crt: the size's `crt_exp` at RSA-2048 with p, q, dP, dQ and qInv undefined: the two +# exponentiations, the recombination, the check of the result against e and the masked write +# of the output, which is all of RSASP1 and RSADP below the range check of their input. +# - import: the size's `crt_congruences` at RSA-2048 with p, q, dP, dQ and qInv undefined: +# the three congruences a private key's constructor and decoder check of its components. +# +# All three must be clean. The three controls must be reported, so that a memcheck that reports +# nothing is noticed: the variable-time `for_public_modulus` over the same undefined modulus, a +# branch on what `crt_exp` returns, which shows that the key it ran over was undefined, and a +# branch on the congruences' verdicts. +# +# Not covered: key generation and `RsaPrivateComponents::validate`, which are not constant time +# and do not claim to be; the range and parity checks a constructor makes of its components +# before the congruences, which branch on what they find; the padding schemes above the CRT +# (the EME-OAEP decode has check_oaep_ct.sh); and anything memcheck cannot see, an instruction +# whose time depends on its operands or a target other than the host. +# +# sudo apt-get install valgrind +# ./dev_scripts/check_rsa_ct.sh +set -euo pipefail + +cd "$(dirname "$0")/rsa_ct_harness" +status=0 + +if ! command -v valgrind >/dev/null; then + echo "FAIL: valgrind is not installed, so the memcheck run cannot be made" + exit 2 +fi +rm -rf target +RUSTFLAGS="--cfg bouncycastle_rsa_ct_harness" cargo build --release --bin memcheck +for mode in context crt import control-context control-crt control-import; do + rc=0 + valgrind -q --malloc-fill=0x00 --error-exitcode=9 target/release/memcheck "$mode" >"target/memcheck-$mode.log" 2>&1 || rc=$? + case "$mode:$rc" in + control-context:9) echo "ok memcheck control-context: the variable-time setup is reported" ;; + control-crt:9) echo "ok memcheck control-crt: the branch on the result is reported" ;; + control-import:9) echo "ok memcheck control-import: the branch on the verdicts is reported" ;; + control-*) echo "FAIL memcheck $mode: exit $rc, nothing was reported where something must be, so a clean run proves nothing" + status=1 ;; + *:0) echo "ok memcheck $mode: nothing depends on the key" ;; + *) echo "FAIL memcheck $mode: exit $rc" + cat "target/memcheck-$mode.log" + status=1 ;; + esac +done +exit $status diff --git a/dev_scripts/check_rsa_stack.sh b/dev_scripts/check_rsa_stack.sh new file mode 100755 index 000000000..6f46d4333 --- /dev/null +++ b/dev_scripts/check_rsa_stack.sh @@ -0,0 +1,35 @@ +#!/usr/bin/env bash +# Checks that the private-key operations of bouncycastle-rsa leave nothing of the key on the +# stack they used, over dev_scripts/rsa_stack_harness: for each operation it paints the stack, +# runs the operation, copies the dead stack out and searches the copy for the words of every +# secret the operation handled (the key's components as limbs and as encoded bytes, the +# Montgomery constants of p and q, the CRT's intermediates, and what a decryption recovers and +# derives). The operations are key generation, the construction, decoding, encoding and cloning +# of a private key, signing (PKCS#1 v1.5 and PSS; one-shot, streaming and from a hash), RSASVE +# decapsulation raw and through HKDF, RSAES-OAEP decapsulation and recovery, RSASVE +# encapsulation through HKDF, `keygen::is_probable_prime`, and the validation of a key pair. +# +# Two controls: nothing run must leave nothing, and a copy of p left in a frame must be found, +# so that a search that finds nothing is noticed. +# +# What a pass shows: that in a release build for the host, x86-64, by the installed toolchain, +# the wipes reach as far as the operations write. The wipes are sized by measurement, so a pass +# says nothing of another target or another compiler, and nothing of a debug build, whose frames +# are larger and are not covered. It does not look at registers, at the heap, or at what a +# caller does with a key it was returned. +# +# ./dev_scripts/check_rsa_stack.sh # RSA-2048 +# ./dev_scripts/check_rsa_stack.sh 2048 3072 4096 8192 +set -euo pipefail + +cd "$(dirname "$0")/rsa_stack_harness" +SIZES=${*:-"2048"} +status=0 + +rm -rf target +cargo build --release +for size in $SIZES; do + echo "RSA-$size" + target/release/rsa_stack_harness "$size" || status=1 +done +exit $status diff --git a/dev_scripts/oaep_ct_harness/Cargo.toml b/dev_scripts/oaep_ct_harness/Cargo.toml new file mode 100644 index 000000000..6b0c6e2af --- /dev/null +++ b/dev_scripts/oaep_ct_harness/Cargo.toml @@ -0,0 +1,18 @@ +# The EME-OAEP decoding, out of line, for `../check_oaep_ct.sh` to read the assembly of and to +# run under memcheck. Its own workspace, so the root `cargo build --workspace` never builds it. +[package] +name = "oaep_ct_harness" +version = "0.0.0" +edition = "2024" +publish = false + +[dependencies] +bouncycastle-utils = { path = "../../crypto/utils" } +# eme_oaep.rs names two traits of bouncycastle-core, which is not yet no_std; the stub supplies +# them under that name so the file builds for the bare-metal targets. +bouncycastle-core = { package = "oaep_ct_stub_core", path = "stub_core" } + +[profile.release] +debug = 1 + +[workspace] diff --git a/dev_scripts/oaep_ct_harness/src/bin/memcheck.rs b/dev_scripts/oaep_ct_harness/src/bin/memcheck.rs new file mode 100644 index 000000000..b8afd4478 --- /dev/null +++ b/dev_scripts/oaep_ct_harness/src/bin/memcheck.rs @@ -0,0 +1,46 @@ +//! Runs the EME-OAEP decode over an encoded message memcheck regards as undefined (fresh heap +//! memory, never written), so that memcheck reports any conditional jump or address computed +//! from it. `control` is a variable-time separator search over the same bytes, which memcheck +//! must report, or a clean run proves nothing. +//! +//! valgrind -q --error-exitcode=9 target/release/memcheck any|exact|control +use std::alloc::{Layout, alloc, dealloc}; +use std::hint::black_box; + +#[inline(never)] +fn control(em: &[u8]) -> usize { + let mut i = 65; + while i < em.len() && em[i] == 0 { + i += 1; + } + i +} + +fn main() { + let mode = std::env::args().nth(1).unwrap_or_default(); + // k for a 2048-bit modulus; the key-transport output is k - 2hLen - 2 bytes. + let k: usize = 256; + let layout = Layout::from_size_align(k, 16).unwrap(); + let l_hash = [0x5au8; 32]; + // SAFETY: a fresh allocation of `k` bytes, deliberately left uninitialised. This program + // exists only to be run under memcheck, which tracks those bytes as undefined. + let p = unsafe { alloc(layout) }; + assert!(!p.is_null()); + let em = unsafe { core::slice::from_raw_parts_mut(p, k) }; + let mut out = [0u8; 190]; + match mode.as_str() { + "any" => { + black_box(oaep_ct_harness::decode_any(&l_hash, em, &mut out)); + } + "exact" => { + black_box(oaep_ct_harness::decode_exact(&l_hash, em, 32, &mut out[..32])); + } + "control" => { + black_box(control(em)); + } + _ => panic!("usage: memcheck any|exact|control"), + } + black_box(&out); + // SAFETY: `p` came from `alloc` with this layout and is not used again. + unsafe { dealloc(p, layout) }; +} diff --git a/dev_scripts/oaep_ct_harness/src/lib.rs b/dev_scripts/oaep_ct_harness/src/lib.rs new file mode 100644 index 000000000..d4db942a3 --- /dev/null +++ b/dev_scripts/oaep_ct_harness/src/lib.rs @@ -0,0 +1,51 @@ +//! `crypto/rsa/src/eme_oaep.rs`, included by path and unmodified, with the MGF an opaque call so +//! that `decode_out` lands in the assembly as one symbol. `../check_oaep_ct.sh` builds this for +//! the Cortex-M0 and RISC-V 32I targets and checks the decode for a multiply, a divide or a call +//! it should not make, and runs `src/bin/memcheck.rs` over it on the host. +#![no_std] +#![forbid(unsafe_code)] +#![allow(dead_code)] + +#[path = "../../../crypto/rsa/src/eme_oaep.rs"] +mod eme_oaep; + +/// What `eme_oaep.rs` uses of the crate's `mgf1` module. The mask is not what is under test: it +/// only has to keep the decode's input opaque to the optimiser and, under memcheck, undefined. +mod mgf1 { + pub(crate) const MAX_HASH_LEN: usize = 64; + + #[inline(never)] + pub(crate) fn mgf1_xor(seed: &[u8], target: &mut [u8]) { + for (t, s) in target.iter_mut().zip(seed.iter().cycle()) { + *t ^= core::hint::black_box(*s); + } + } +} + +use bouncycastle_core::traits::{HashAlgParams, HashOneShot}; + +/// A 32-byte hash, for `hLen`; the decode never calls it. +#[derive(Default)] +pub struct H32; +impl HashAlgParams for H32 { + const OUTPUT_LEN: usize = 32; +} +impl HashOneShot for H32 { + #[inline(never)] + fn hash_out(_data: &[u8], out: &mut [u8]) -> usize { + out.fill(0); + 32 + } +} + +/// The key-transport path: a message of any length up to `out.len()`. +#[inline(never)] +pub fn decode_any(l_hash: &[u8], em: &mut [u8], out: &mut [u8]) -> Option { + eme_oaep::decode_out::(l_hash, em, None, out) +} + +/// The KEM path: the message must be exactly `len` bytes. +#[inline(never)] +pub fn decode_exact(l_hash: &[u8], em: &mut [u8], len: usize, out: &mut [u8]) -> Option { + eme_oaep::decode_out::(l_hash, em, Some(len), out) +} diff --git a/dev_scripts/oaep_ct_harness/stub_core/Cargo.toml b/dev_scripts/oaep_ct_harness/stub_core/Cargo.toml new file mode 100644 index 000000000..13924bfb2 --- /dev/null +++ b/dev_scripts/oaep_ct_harness/stub_core/Cargo.toml @@ -0,0 +1,5 @@ +[package] +name = "oaep_ct_stub_core" +version = "0.0.0" +edition = "2024" +publish = false diff --git a/dev_scripts/oaep_ct_harness/stub_core/src/lib.rs b/dev_scripts/oaep_ct_harness/stub_core/src/lib.rs new file mode 100644 index 000000000..5e404bb18 --- /dev/null +++ b/dev_scripts/oaep_ct_harness/stub_core/src/lib.rs @@ -0,0 +1,13 @@ +//! The two `bouncycastle_core::traits` names `crypto/rsa/src/eme_oaep.rs` imports, reduced to +//! what that file uses of them. +#![no_std] +#![forbid(unsafe_code)] + +pub mod traits { + pub trait HashAlgParams { + const OUTPUT_LEN: usize; + } + pub trait HashOneShot: Default { + fn hash_out(data: &[u8], out: &mut [u8]) -> usize; + } +} diff --git a/dev_scripts/rsa_ct_harness/Cargo.toml b/dev_scripts/rsa_ct_harness/Cargo.toml new file mode 100644 index 000000000..8c09493d1 --- /dev/null +++ b/dev_scripts/rsa_ct_harness/Cargo.toml @@ -0,0 +1,19 @@ +# The RSA private-key arithmetic, reached through bouncycastle-rsa's public API, for +# `../check_rsa_ct.sh` to run under memcheck with the key undefined. Its own workspace, so the +# root `cargo build --workspace` never builds it. +[package] +name = "rsa_ct_harness" +version = "0.0.0" +edition = "2024" +publish = false + +[dependencies] +bouncycastle-rsa = { path = "../../crypto/rsa" } + +# The root workspace's release profile, so that memcheck runs the code a release build of the +# library is; `debug` for the line numbers in a report. +[profile.release] +lto = "thin" +debug = 1 + +[workspace] diff --git a/dev_scripts/rsa_ct_harness/src/bin/memcheck.rs b/dev_scripts/rsa_ct_harness/src/bin/memcheck.rs new file mode 100644 index 000000000..b074bca4e --- /dev/null +++ b/dev_scripts/rsa_ct_harness/src/bin/memcheck.rs @@ -0,0 +1,171 @@ +//! Runs the RSA private-key arithmetic over a key memcheck regards as undefined, so that +//! memcheck reports any conditional jump or address computed from it. That arithmetic is not +//! public: `bouncycastle-rsa` shows it to this program under `--cfg +//! bouncycastle_rsa_ct_harness`, which `check_rsa_ct.sh` sets. A secret is made +//! undefined without changing its value by XOR with fresh heap memory, which memcheck tracks +//! as undefined and `--malloc-fill=0x00` makes zero. The controls must be reported, or a +//! clean run proves nothing. +//! +//! valgrind -q --malloc-fill=0x00 --error-exitcode=9 target/release/memcheck +//! +//! context `MontgomeryContext::for_secret_modulus` over an undefined modulus +//! crt `RSA2048::crt_exp` with p, q, dP, dQ and qInv undefined +//! import `RSA2048::crt_congruences` with p, q, dP, dQ and qInv undefined +//! control-context `for_public_modulus`, which is variable time, over the same modulus +//! control-crt `crt`, then a branch on its result, which is computed from the key +//! control-import `import`, then a branch on its verdicts +use bouncycastle_rsa::RSA2048; +use bouncycastle_rsa::ct_harness::PrivateKeyEngine; +use bouncycastle_rsa::keys::RsaPrivateComponents; +use bouncycastle_rsa::modexp::MontgomeryContext; +use bouncycastle_rsa::size::RsaSigningSize; +use std::alloc::{Layout, alloc}; +use std::hint::black_box; + +// The RSA-2048 key of `mem_usage_benches`' `bench_rsa_mem_usage`. +const P: [u64; 16] = [ + 0x0ea36cfb3a5b18f1, 0x48a6e65332119129, 0x110ad9e7b48a1c93, 0x569156b90113e2e9, + 0xe79813a575cfad9c, 0x69d659d143ec6f17, 0xe81e6bab5ddaa783, 0xbff1c5b80a69f788, + 0x978f6c35814f50ee, 0xe6a289ad4cfbf78f, 0x34d5681e5809d415, 0xbb028bda42eeb5d2, + 0x41c56e4de086b0d5, 0x58b8d1e24f3b55d0, 0xfb5248247d98cb7d, 0xdc431050f782e894, +]; +const Q: [u64; 16] = [ + 0x669f140cfbc20f25, 0xb97bb03677207d95, 0xfd4e06f3ed7299d4, 0x160f90536abc9492, + 0xf5b131f39098f7bc, 0xae8d72c57088d7ab, 0x89b94fbde542aba9, 0x3d3f9880ec47d5e0, + 0x1378a6868af3b7a0, 0x5544070beb057c94, 0x16611debc472fac4, 0xe500ffb79f5b8868, + 0x308a5e32196603b2, 0xea5fb19eb4eabc38, 0x122273ae3222b598, 0xbd1a81e7977f9898, +]; +const D_P: [u64; 16] = [ + 0x209f33f09515d7c1, 0xb4a9b37656917205, 0x276933bb07e4efb9, 0x8c14019808e00414, + 0x289f96da220711e5, 0xfbbd2923d31532fe, 0xc06b414e61c0e1e7, 0x4c23c4588488961d, + 0x4dc48ae34514759c, 0x9c786961ae3e2c35, 0x497e8d9c650688e0, 0x18bf08472612dbe5, + 0x8885fb161870ee12, 0xf21d7c1479d99d47, 0x9121d91952ffd1c7, 0xa94b528b28f29159, +]; +const D_Q: [u64; 16] = [ + 0xf7597ffb68011d8d, 0x7b3cc538c4bab8c9, 0xa8fa480a81a925af, 0x6d6ede7251a383bf, + 0x8a63f788ce3a0f85, 0x0b920502eb478bc9, 0x7e37e755edfe70d9, 0x9cf9948422a16555, + 0x0d6d9ea1f2ef71fd, 0xf7efa32ea0cb6e00, 0x0629b114ca7f780f, 0xcf51176359654348, + 0x540cdcbd4ad35435, 0x31c02ff1a2bc437c, 0xff2503df78bafed5, 0x3af0e72a933aef09, +]; +const Q_INV: [u64; 16] = [ + 0x552fe4bfce945f7b, 0x67e50c999c67247b, 0xfb54ef17be3b2853, 0x241f5921b5ad3983, + 0x02de5eccd143cf31, 0x74e45f6fcc60f216, 0xafa5428a74f12708, 0x88d42294b6a2759b, + 0xe923e1097c0c562f, 0xc968b48a91c38b5b, 0x933e85179c0320b0, 0x7993d0445f758d51, + 0x9bfc042ee0924b1b, 0x41f956d90fa8a793, 0xee7a87b6483a66ee, 0x2640fbfbcfefb163, +]; + +/// XORs `len` bytes of fresh heap memory into the `len` bytes at `at`. The allocation is not +/// freed: the process is about to exit, and memcheck is not asked for leaks. +/// +/// # Safety +/// `at` must be valid for reads and writes of `len` bytes, of a type every bit pattern is a +/// value of. +unsafe fn make_undefined(at: *mut u8, len: usize) { + // SAFETY: a fresh allocation of `len` bytes, deliberately left uninitialised and read. This + // program exists only to be run under memcheck, which tracks those bytes as undefined and + // was told to fill them with zeros. The pointer goes through `black_box` so that the + // compiler cannot see the memory is fresh and fold the XOR away. + let zeros = black_box(unsafe { alloc(Layout::from_size_align(len, 8).unwrap()) }); + assert!(!zeros.is_null()); + for i in 0..len { + // SAFETY: `i < len`, within the allocation and within what the caller vouched for. + unsafe { *at.add(i) ^= *zeros.add(i) }; + } +} + +/// `value`, undefined. +fn undefined(value: &[u64; 16]) -> [u64; 16] { + let mut n = *value; + // SAFETY: `n` is 128 bytes of `u64`. + unsafe { make_undefined(n.as_mut_ptr().cast(), 128) }; + n +} + +/// p, undefined. +fn undefined_modulus() -> [u64; 16] { + undefined(&P) +} + +/// p, q, dP, dQ and qInv, undefined, for the congruences a private key's constructor checks. +fn undefined_components() -> [[u64; 16]; 5] { + [&P, &Q, &D_P, &D_Q, &Q_INV].map(undefined) +} + +/// The key, with its five secret components undefined and `n` and `e` left defined: the +/// result check works over those two in variable time, as it may. +fn undefined_key() -> RsaPrivateComponents { + let mut sk = + RsaPrivateComponents::::from_crt_components(&P, &Q, &D_P, &D_Q, &Q_INV, 65537) + .unwrap(); + // The key type gives no mutable access to its components, so they are found in its bytes. + // Five components, n and e are all it holds; a field added to it holds key material this + // function would leave defined, and has to be dealt with here first. + let size = size_of::>(); + assert_eq!( + size, + 5 * 128 + 256 + 8, + "RsaPrivateComponents has a field this harness does not know" + ); + let base = (&raw mut sk).cast::(); + // SAFETY: `base` points at `size` initialised bytes of `sk`, which has no padding (the + // assertion above), read while nothing else borrows it. + let image = unsafe { std::slice::from_raw_parts(base, size) }.to_vec(); + for component in [&P, &Q, &D_P, &D_Q, &Q_INV] { + let needle: Vec = component.iter().flat_map(|limb| limb.to_ne_bytes()).collect(); + let at = image.windows(128).position(|w| w == needle).expect("component not found"); + // SAFETY: `at + 128 <= size`, inside `sk`, whose components are arrays of `u64`. + unsafe { make_undefined(base.add(at), 128) }; + } + sk +} + +fn input() -> [u64; 32] { + let mut x = [0u64; 32]; + x[0] = 0x0123_4567_89ab_cdef; + x[17] = 0xfeed_face_cafe_f00d; + x +} + +fn main() { + let mode = std::env::args().nth(1).unwrap_or_default(); + match mode.as_str() { + "context" => { + let n = undefined_modulus(); + black_box(MontgomeryContext::<16>::for_secret_modulus(black_box(&n))); + } + "control-context" => { + let n = undefined_modulus(); + black_box(MontgomeryContext::<16>::for_public_modulus(black_box(&n))); + } + "crt" => { + let sk = undefined_key(); + let mut out = [0u64; 32]; + // The result is not turned into a `bool`: whether the check passed is computed + // from the key, and a branch on it here would be this program's own. + let _ = black_box(RSA2048::crt_exp(black_box(&sk), black_box(&input()), &mut out)); + black_box(&out); + } + "control-crt" => { + let sk = undefined_key(); + let mut out = [0u64; 32]; + if RSA2048::crt_exp(black_box(&sk), black_box(&input()), &mut out).to_bool() { + black_box(&out); + } + } + "import" => { + let [p, q, d_p, d_q, q_inv] = black_box(undefined_components()); + // The verdicts are not turned into `bool`s, as `crt`'s result is not. + let _ = black_box(RSA2048::crt_congruences(&p, &q, &d_p, &d_q, &q_inv, 65537)); + } + "control-import" => { + let [p, q, d_p, d_q, q_inv] = black_box(undefined_components()); + let verdicts = RSA2048::crt_congruences(&p, &q, &d_p, &d_q, &q_inv, 65537); + if verdicts.into_iter().all(|ok| ok.to_bool()) { + black_box(()); + } + } + _ => { + panic!("usage: memcheck context|crt|import|control-context|control-crt|control-import") + } + } +} diff --git a/dev_scripts/rsa_stack_harness/Cargo.toml b/dev_scripts/rsa_stack_harness/Cargo.toml new file mode 100644 index 000000000..54aeeec68 --- /dev/null +++ b/dev_scripts/rsa_stack_harness/Cargo.toml @@ -0,0 +1,22 @@ +# The private-key operations of bouncycastle-rsa, each run over a painted stack that is then +# searched for what the operation handled, for `../check_rsa_stack.sh`. Its own workspace, so +# the root `cargo build --workspace` never builds it. +[package] +name = "rsa_stack_harness" +version = "0.0.0" +edition = "2024" +publish = false + +[dependencies] +bouncycastle-core = { path = "../../crypto/core" } +bouncycastle-hkdf = { path = "../../crypto/hkdf" } +bouncycastle-rng = { path = "../../crypto/rng" } +bouncycastle-rsa = { path = "../../crypto/rsa" } +bouncycastle-sha2 = { path = "../../crypto/sha2" } + +# The root workspace's release profile: the wipes are sized for the frames it lays out. +[profile.release] +lto = "thin" +strip = "debuginfo" + +[workspace] diff --git a/dev_scripts/rsa_stack_harness/src/main.rs b/dev_scripts/rsa_stack_harness/src/main.rs new file mode 100644 index 000000000..d560f49dd --- /dev/null +++ b/dev_scripts/rsa_stack_harness/src/main.rs @@ -0,0 +1,518 @@ +//! What the private-key operations of bouncycastle-rsa leave on the dead stack, for +//! `../check_rsa_stack.sh`. For each operation the stack below the call is painted, the +//! operation run with its results going to the heap or to a live frame above, the dead stack +//! copied out, and the copy searched for the 8-byte words of every secret the operation +//! handled: the key's components as limbs and as encoded bytes, the Montgomery constants of p +//! and q, the intermediates of the CRT, and what a decryption recovers and derives. The key is +//! generated when the program starts, so the values are computed here, with the crate's public +//! arithmetic, and checked against the operation's own output before they are searched for. +//! +//! Two controls: nothing run must leave nothing, and a copy of p left in a frame must be found. +//! +//! target/release/rsa_stack_harness [2048|3072|4096|8192] +//! +//! One line per operation, `ok` or `FAIL`; the exit status is 1 if anything failed. +use bouncycastle_core::kdf_params::{KdfParams, KeyLen}; +use bouncycastle_core::kem_key::{DecapsulatingKey, EncapsulatingKey}; +use bouncycastle_core::key_material::{KeyMaterial, KeyMaterial0, KeyMaterialTrait}; +use bouncycastle_core::key_transport_key::KeyTransportDecryptingKey; +use bouncycastle_core::signature_key::{ + DeterministicOneShotSigningKey, DeterministicSigningKey, OneShotSigningKey, SigningKey, +}; +use bouncycastle_core::traits::{PrivateKey, SignatureSigner}; +use bouncycastle_hkdf::{HKDF, HkdfDescription}; +use bouncycastle_rng::DefaultRNG; +use bouncycastle_rsa::keygen::is_probable_prime; +use bouncycastle_rsa::keys::{RsaPrivateComponents, RsaPrivateKey}; +use bouncycastle_rsa::modexp::{MontgomeryContext, mod_pow, mul_mod, reduce_wide, sub_mod}; +use bouncycastle_rsa::rsaes_oaep::OaepParams; +use bouncycastle_rsa::rsassa; +use bouncycastle_rsa::rsassa_pkcs1_v1_5::RSASSA_PKCS1_v1_5; +use bouncycastle_rsa::rsassa_pss::RSASSA_PSS; +use bouncycastle_rsa::rsasve::{RsaKEMPrivateKey, RsaKEMPublicKey}; +use bouncycastle_rsa::size::{KemKeyPair, RsaSigningSize, RsaSize, SignatureKeyPair}; +use bouncycastle_rsa::{RSA2048, RSA3072, RSA4096, RSA8192}; +use bouncycastle_sha2::SHA256; +use std::collections::HashSet; +use std::hint::black_box; +use std::num::NonZeroUsize; + +/// How far below the call the stack is painted and searched. Key generation at RSA-8192, the +/// deepest operation here, uses under 50 KiB. +const DEPTH: usize = 512 * 1024; +/// The gap between the frame that takes the copy and the operation's first frame. +const PAD: usize = 16 * 1024; +const PAINT: u8 = 0xA5; + +const MSG: &[u8] = b"what a private-key operation leaves on the stack"; +const DIGEST: [u8; 32] = [0x3c; 32]; +const SALT: [u8; 32] = [0x71; 32]; + +#[inline(never)] +fn paint() { + let mut frame = [PAINT; DEPTH + PAD]; + black_box(&mut frame); +} + +/// Runs `f` with its frames starting `PAD` below this one, so that the frame of [`snapshot`] +/// does not land on them. `f` is the tail call, so that what it returns by value is written +/// straight to where the caller of [`measure`] keeps it, a live frame above everything +/// searched, and is not staged in a frame that is then dead. +#[inline(never)] +fn run_deep(f: impl FnOnce() -> T) -> T { + let mut pad = [0u8; PAD]; + black_box(&mut pad); + f() +} + +/// Copies the `DEPTH` bytes below this frame into `buf`, lowest address first. +#[inline(never)] +fn snapshot(buf: &mut [u8]) { + let marker = 0u8; + let top = black_box(&raw const marker as usize) & !15; + let base = top - DEPTH; + for (i, b) in buf.iter_mut().enumerate() { + // SAFETY: none that Rust would recognise: this reads the stack below the current + // frame, which no live object owns. It is what this program exists to do. The pages + // are mapped, `paint` having written every byte of them, and on x86-64 Linux nothing + // else writes below the stack pointer of a thread that takes no signal. + *b = unsafe { core::ptr::read_volatile((base + i) as *const u8) }; + } +} + +#[inline(never)] +fn measure(buf: &mut [u8], f: impl FnOnce() -> T) -> T { + paint(); + let result = run_deep(f); + snapshot(buf); + result +} + +/// The leak the second control looks for: a copy of `value` in a frame, left as it is. +#[inline(never)] +fn leak(value: &[u64; N]) { + let mut local = *value; + black_box(&mut local); +} + +/// A named secret, as the bytes it would be in memory. +type Values = Vec<(String, Vec)>; + +/// Limbs as they lie in memory. +fn limb_image(limbs: &[u64]) -> Vec { + limbs.iter().flat_map(|limb| limb.to_ne_bytes()).collect() +} + +/// Limbs as the big-endian byte string an encoding holds them in. +fn be_of_limbs(limbs: &[u64]) -> Vec { + limbs.iter().rev().flat_map(|limb| limb.to_be_bytes()).collect() +} + +/// A big-endian byte string of `8 * N` bytes as limbs. +fn limbs_from_be(bytes: &[u8]) -> [u64; N] { + assert_eq!(bytes.len(), 8 * N); + let mut limbs = [0u64; N]; + for (limb, chunk) in limbs.iter_mut().zip(bytes.rchunks_exact(8)) { + *limb = u64::from_be_bytes(chunk.try_into().unwrap()); + } + limbs +} + +/// A byte string as SHA-256's message schedule holds it: each 32-bit word's bytes reversed. +fn sha256_words(bytes: &[u8]) -> Vec { + bytes.chunks_exact(4).flat_map(|word| word.iter().rev().copied()).collect() +} + +/// An integer, as limbs and as its big-endian encoding. +fn push_integer(values: &mut Values, name: &str, limbs: &[u64]) { + values.push((name.to_string(), limb_image(limbs))); + values.push((format!("{name} (bytes)"), be_of_limbs(limbs))); +} + +/// A byte string, as it is and as a hash that reads it has it. +fn push_bytes(values: &mut Values, name: &str, bytes: &[u8]) { + values.push((name.to_string(), bytes.to_vec())); + values.push((format!("{name} (SHA-256 words)"), sha256_words(bytes))); +} + +/// The five secret components of a private key. +struct Key { + p: [u64; H], + q: [u64; H], + d_p: [u64; H], + d_q: [u64; H], + q_inv: [u64; H], +} + +impl Key { + /// From the encoding `p || q || dP || dQ || qInv || e`. + fn from_encoding(encoded: &[u8]) -> Self { + let field = |i: usize| limbs_from_be::(&encoded[8 * H * i..8 * H * (i + 1)]); + Self { p: field(0), q: field(1), d_p: field(2), d_q: field(3), q_inv: field(4) } + } + + /// The components, and the constants of the Montgomery contexts over p and q, `R mod m` + /// and `R^2 mod m` for `R = 2^(64 * H)`: what every operation is searched for. + fn values(&self) -> Values { + let mut values = Values::new(); + push_integer(&mut values, "p", &self.p); + push_integer(&mut values, "q", &self.q); + push_integer(&mut values, "dP", &self.d_p); + push_integer(&mut values, "dQ", &self.d_q); + push_integer(&mut values, "qInv", &self.q_inv); + let mut r = [0u64; H2]; + r[H] = 1; + let mut r2 = [0u64; H21]; + r2[H2] = 1; + for (name, modulus) in [("p", &self.p), ("q", &self.q)] { + values.push((format!("R mod {name}"), limb_image(&reduce_wide::(&r, modulus)))); + values.push(( + format!("R^2 mod {name}"), + limb_image(&reduce_wide::(&r2, modulus)), + )); + } + values + } + + /// [`Self::values`] and the intermediates of `x^d mod n` by the CRT (RFC 8017 Section + /// 5.1.2 step 2.b), and the result, which is returned for the caller to check against what + /// the operation gave and to add to the search where it is a secret. + fn crt_values(&self, x: &[u64; H2]) -> (Values, [u64; H2]) { + let ctx_p = MontgomeryContext::::for_secret_modulus(&self.p); + let ctx_q = MontgomeryContext::::for_secret_modulus(&self.q); + let x_mod_p = reduce_wide::(x, &self.p); + let x_mod_q = reduce_wide::(x, &self.q); + let s1 = mod_pow::(&x_mod_p, &self.d_p, &ctx_p); + let s2 = mod_pow::(&x_mod_q, &self.d_q, &ctx_q); + let s2_mod_p = reduce_wide::(&s2, &self.p); + let h = mul_mod::(&self.q_inv, &sub_mod(&s1, &s2_mod_p, &self.p), &ctx_p); + // q * h, then y = s2 + q * h. + let mut qh = [0u64; H2]; + for i in 0..H { + let mut carry = 0u128; + for j in 0..H { + let t = u128::from(qh[i + j]) + u128::from(self.q[i]) * u128::from(h[j]) + carry; + qh[i + j] = t as u64; + carry = t >> 64; + } + qh[i + H] = carry as u64; + } + let mut y = qh; + let mut carry = 0u128; + for i in 0..H2 { + let t = u128::from(y[i]) + if i < H { u128::from(s2[i]) } else { 0 } + carry; + y[i] = t as u64; + carry = t >> 64; + } + let mut values = self.values::(); + values.push(("x mod p".into(), limb_image(&x_mod_p))); + values.push(("x mod q".into(), limb_image(&x_mod_q))); + values.push(("s1".into(), limb_image(&s1))); + values.push(("s2".into(), limb_image(&s2))); + values.push(("h".into(), limb_image(&h))); + // The low half only: the high half is the result's own, give or take a carry, and a + // signature is not a secret. + values.push(("q*h (low half)".into(), limb_image(&qh[..H]))); + (values, y) + } +} + +/// The painted stack's copy, and the count of what failed. +struct Scan { + buf: Vec, + failures: usize, +} + +impl Scan { + fn new() -> Self { + Self { buf: vec![0u8; DEPTH], failures: 0 } + } + + /// Paints, runs `f` and copies the stack out. What `f` returns comes back by value. + fn run(&mut self, f: impl FnOnce() -> T) -> T { + measure(&mut self.buf, f) + } + + /// The bytes of stack the last run used, and for each of `values`, how many of its words + /// were found in them and how many it has. + fn search(&self, values: &Values) -> (usize, Vec<(String, usize, usize)>) { + let lowest = self.buf.iter().position(|b| *b != PAINT).unwrap_or(DEPTH); + let used = (DEPTH - lowest).saturating_sub(PAD); + // Every 8 bytes of the used region, at every offset: a secret need not lie aligned. + let mut windows: HashSet<&[u8]> = HashSet::new(); + for i in lowest..DEPTH.saturating_sub(7) { + windows.insert(&self.buf[i..i + 8]); + } + let mut counts = Vec::new(); + for (name, image) in values { + // A word of one repeated byte (a zero limb, padding) says nothing when found. + let words: Vec<&[u8]> = + image.chunks_exact(8).filter(|w| w.iter().any(|b| *b != w[0])).collect(); + let hits = words.iter().filter(|w| windows.contains(*w)).count(); + counts.push((name.clone(), hits, words.len())); + } + (used, counts) + } + + /// After an operation: none of `values` may be on the stack it used. + fn clean(&mut self, operation: &str, values: &Values) { + let (used, counts) = self.search(values); + let found: Vec = counts + .iter() + .filter(|(_, hits, _)| *hits > 0) + .map(|(name, hits, words)| format!("{name}: {hits} of {words} words")) + .collect(); + if found.is_empty() { + println!("ok {operation}: none of its secrets in the {used} bytes of stack it used"); + } else { + println!( + "FAIL {operation}: left in the {used} bytes of stack it used: {}", + found.join(", ") + ); + self.failures += 1; + } + } + + /// After the leak control: every word of `values` must be found. + fn leaked(&mut self, operation: &str, values: &Values) { + let (_, counts) = self.search(values); + if counts.iter().all(|(_, hits, words)| *words > 0 && hits == words) { + println!("ok {operation}: found"); + } else { + println!( + "FAIL {operation}: not found, so an operation that leaves nothing proves nothing" + ); + self.failures += 1; + } + } +} + +/// Every operation at one size. `$HALF` is the limbs of a prime; the function returns the +/// count of what failed. +macro_rules! scan_size { + ($name:ident, $K:ty, $HALF:literal) => { + fn $name() -> usize { + const H: usize = $HALF; + const H2: usize = 2 * H; + const H21: usize = 2 * H + 1; + const K_LEN: usize = 16 * H; + const SK_LEN: usize = 40 * H + 8; + type V15 = RSASSA_PKCS1_v1_5<$K, SHA256>; + type Pss = RSASSA_PSS<$K, SHA256>; + let limbs_of = |bytes: &[u8; K_LEN]| <$K>::limbs_from_be_bytes(bytes); + + let mut scan = Scan::new(); + let mut rng = Box::new(DefaultRNG::default()); + + // Key generation, and the key the rest runs over. + let pair = scan.run(|| <$K>::keygen(&mut *rng)); + let components = Box::new(pair.unwrap().1); + let sk_v15: Box> = Box::new(components.key()); + let sk_pss: Box> = Box::new(components.key()); + let encoded: Box<[u8; SK_LEN]> = Box::new(sk_pss.encode()); + let key = Key::::from_encoding(&encoded[..]); + let secrets = key.values::(); + scan.clean("key generation (keygen)", &secrets); + + let pair = scan.run(|| <$K>::generate_pss_signature_key_pair::(&mut *rng)); + let other: Box<[u8; SK_LEN]> = Box::new(pair.unwrap().1.encode()); + scan.clean( + "key generation (generate_pss_signature_key_pair)", + &Key::::from_encoding(&other[..]).values::(), + ); + let pair = scan.run(|| <$K>::generate_kem_key_pair(&mut *rng)); + let other: Box<[u8; SK_LEN]> = Box::new(pair.unwrap().1.encode()); + scan.clean( + "key generation (generate_kem_key_pair)", + &Key::::from_encoding(&other[..]).values::(), + ); + + // The controls. + scan.run(|| {}); + scan.clean("control, nothing run", &secrets); + scan.run(|| leak(&key.p)); + scan.leaked("control, a copy of p left in a frame", &vec![secrets[0].clone()]); + + // Key handling. + let (p, q, d_p, d_q, q_inv, e) = + (&key.p, &key.q, &key.d_p, &key.d_q, &key.q_inv, components.e()); + let kept = scan + .run(|| RsaPrivateComponents::<$K>::from_crt_components(p, q, d_p, d_q, q_inv, e)); + black_box(&kept); + scan.clean("from_crt_components (components)", &secrets); + let kept = + scan.run(|| RsaPrivateKey::::from_crt_components(p, q, d_p, d_q, q_inv, e)); + black_box(&kept); + scan.clean("from_crt_components (signature key)", &secrets); + let kept = + scan.run(|| RsaKEMPrivateKey::<$K>::from_crt_components(p, q, d_p, d_q, q_inv, e)); + black_box(&kept); + scan.clean("from_crt_components (key-establishment key)", &secrets); + let kept = scan.run(|| RsaPrivateKey::::from_bytes(&encoded[..])); + black_box(&kept); + scan.clean("from_bytes (signature key)", &secrets); + let kept = scan.run(|| RsaKEMPrivateKey::<$K>::from_bytes(&encoded[..])); + let sk_kem = Box::new(kept.unwrap()); + scan.clean("from_bytes (key-establishment key)", &secrets); + let mut out: Box<[u8; SK_LEN]> = Box::new([0u8; SK_LEN]); + scan.run(|| { + sk_pss.encode_out(&mut out); + }); + scan.clean("encode_out", &secrets); + let kept = scan.run(|| sk_pss.encode()); + black_box(&kept); + scan.clean("encode", &secrets); + let kept = scan.run(|| (*components).clone()); + black_box(&kept); + scan.clean("clone (components)", &secrets); + let kept: RsaPrivateKey = scan.run(|| components.key()); + black_box(&kept); + scan.clean("components.key()", &secrets); + let kept = scan.run(|| (*sk_pss).clone()); + black_box(&kept); + scan.clean("clone (key)", &secrets); + + // Signing. The representative that was signed is the signature under the public + // key, and the CRT over it must give the signature back. + let mut sig: Box<[u8; K_LEN]> = Box::new([0u8; K_LEN]); + let signed = |sig: &[u8; K_LEN]| { + let s = limbs_of(sig); + let (values, y) = + key.crt_values::(&<$K>::public_exp(components.n(), e, &s)); + assert_eq!(y, s, "the harness's CRT is not the library's"); + values + }; + scan.run(|| { + sk_v15.sign_deterministic_out(MSG, None, &mut sig).unwrap(); + }); + scan.clean("PKCS#1 v1.5 sign_deterministic_out", &signed(&sig)); + scan.run(|| { + let mut signer = sk_v15.create_signer_deterministic(None).unwrap(); + signer.do_update(MSG); + signer.do_final_out(&mut sig).unwrap(); + }); + scan.clean("PKCS#1 v1.5 streaming", &signed(&sig)); + let made = scan.run(|| rsassa::sign_from_hash_deterministic(&*sk_v15, &DIGEST)); + scan.clean("PKCS#1 v1.5 sign_from_hash_deterministic", &signed(&made.unwrap())); + scan.run(|| { + sk_pss.sign_out(&mut *rng, MSG, None, &mut sig).unwrap(); + }); + scan.clean("PSS sign_out", &signed(&sig)); + scan.run(|| { + let mut signer = sk_pss.create_signer(&mut *rng, None).unwrap(); + signer.do_update(MSG); + signer.do_final_out(&mut sig).unwrap(); + }); + scan.clean("PSS streaming", &signed(&sig)); + let made = scan.run(|| rsassa::sign_from_hash_with_salt(&*sk_pss, &DIGEST, &SALT)); + scan.clean("PSS sign_from_hash_with_salt", &signed(&made.unwrap())); + + // RSASVE. What decryption recovers is a secret too: the CRT's result, as limbs and + // as the bytes handed out. + let recovered = |ct: &[u8; K_LEN], name: &str| { + let (mut values, y) = key.crt_values::(&limbs_of(ct)); + push_integer(&mut values, name, &y); + (values, y) + }; + let pk_kem = Box::new(RsaKEMPublicKey::<$K>::new(components.n(), e).unwrap()); + let mut ct: Box<[u8; K_LEN]> = Box::new([0u8; K_LEN]); + let mut z: Box> = Box::new(KeyMaterial::new()); + pk_kem.encaps_out(&mut *rng, (), &mut ct, &mut z).unwrap(); + scan.run(|| { + sk_kem.decaps_out(&ct, (), &mut z).unwrap(); + }); + let (mut values, y) = recovered(&ct, "Z"); + assert_eq!(z.ref_to_bytes(), be_of_limbs(&y), "the harness's CRT is not the library's"); + scan.clean("RSASVE decaps_out", &values); + + // RSASVE with HKDF: Z as SHA-256 reads it, the pseudorandom key and the derived key. + let hkdf = HkdfDescription::::new(); + let mut derived: Box> = Box::new(KeyMaterial::new()); + let derivation = |z: &KeyMaterial, derived: &KeyMaterial<32>| { + let no_salt = KeyMaterial0::new(); + let prk = HKDF::::extract(&no_salt, z).unwrap(); + let mut okm = KeyMaterial::<32>::new(); + HKDF::::expand_out(&prk, b"info", 32, &mut okm).unwrap(); + assert_eq!(okm.ref_to_bytes(), derived.ref_to_bytes(), "not the library's HKDF"); + let mut values = Values::new(); + push_bytes(&mut values, "Z", z.ref_to_bytes()); + push_bytes(&mut values, "pseudorandom key", prk.ref_to_bytes()); + push_bytes(&mut values, "derived key", derived.ref_to_bytes()); + values + }; + scan.run(|| { + let params = KdfParams::new(&hkdf, b"info", KeyLen::<32>); + sk_kem.decaps_out(&ct, params, &mut derived).unwrap(); + }); + values.extend(derivation(&z, &derived)); + scan.clean("RSASVE with HKDF decaps_out", &values); + + // The one public-key operation here: it derives the same key. + let mut ct_kdf: Box<[u8; K_LEN]> = Box::new([0u8; K_LEN]); + scan.run(|| { + let params = KdfParams::new(&hkdf, b"info", KeyLen::<32>); + pk_kem.encaps_out(&mut *rng, params, &mut ct_kdf, &mut derived).unwrap(); + }); + let mut z_kdf: Box> = Box::new(KeyMaterial::new()); + sk_kem.decaps_out(&ct_kdf, (), &mut z_kdf).unwrap(); + let mut values = derivation(&z_kdf, &derived); + push_integer(&mut values, "Z", &limbs_of(z_kdf.ref_to_bytes().try_into().unwrap())); + scan.clean("RSASVE with HKDF encaps_out", &values); + + // RSAES-OAEP: the encoded message is what the CRT recovers. + let oaep = || OaepParams::::new(b""); + let mut ct_oaep: Box<[u8; K_LEN]> = Box::new([0u8; K_LEN]); + let mut sent: Box> = Box::new(KeyMaterial::new()); + pk_kem.encaps_out(&mut *rng, oaep(), &mut ct_oaep, &mut sent).unwrap(); + let (mut values, _) = recovered(&ct_oaep, "EM"); + push_bytes(&mut values, "transported key", sent.ref_to_bytes()); + let mut key32: Box> = Box::new(KeyMaterial::new()); + scan.run(|| { + sk_kem.decaps_out(&ct_oaep, oaep(), &mut key32).unwrap(); + }); + assert_eq!(key32.ref_to_bytes(), sent.ref_to_bytes()); + scan.clean("RSAES-OAEP decaps_out", &values); + let mut key64: Box> = Box::new(KeyMaterial::new()); + scan.run(|| { + sk_kem.recover_out(&ct_oaep, oaep(), &mut key64).unwrap(); + }); + scan.clean("RSAES-OAEP recover_out", &values); + // A ciphertext the decoding refuses: RSASVE's, whose "encoded message" is Z. + scan.run(|| { + assert!(sk_kem.recover_out(&ct, oaep(), &mut key64).is_err()); + }); + scan.clean("RSAES-OAEP recover_out, ciphertext refused", &recovered(&ct, "EM").0); + + // The primality test, as a caller would run it over an imported key's prime. + let verdict = scan.run(|| { + is_probable_prime::(&key.p, NonZeroUsize::new(5).unwrap(), &mut *rng) + }); + assert_eq!(verdict, Ok(true)); + scan.clean("is_probable_prime (p)", &secrets); + + // Validation of the key pair, as a caller would ask of an imported key. + let verdict = scan.run(|| components.validate(&mut *rng)); + assert_eq!(verdict, Ok(())); + scan.clean("validate", &secrets); + + scan.failures + } + }; +} + +scan_size!(scan_2048, RSA2048, 16); +scan_size!(scan_3072, RSA3072, 24); +scan_size!(scan_4096, RSA4096, 32); +scan_size!(scan_8192, RSA8192, 64); + +fn main() { + let size = std::env::args().nth(1).unwrap_or_else(|| "2048".into()); + let failures = match size.as_str() { + "2048" => scan_2048(), + "3072" => scan_3072(), + "4096" => scan_4096(), + "8192" => scan_8192(), + _ => panic!("usage: rsa_stack_harness [2048|3072|4096|8192]"), + }; + std::process::exit(if failures == 0 { 0 } else { 1 }); +} diff --git a/mem_usage_benches/Cargo.toml b/mem_usage_benches/Cargo.toml index 8ad8ce7c5..458e7dc6c 100644 --- a/mem_usage_benches/Cargo.toml +++ b/mem_usage_benches/Cargo.toml @@ -48,6 +48,10 @@ path = "src/bench_ecdsa_mem_usage.rs" name = "bench_sm2_mem_usage" path = "src/bench_sm2_mem_usage.rs" +[[bin]] +name = "bench_rsa_mem_usage" +path = "src/bench_rsa_mem_usage.rs" + [[bin]] name = "bench_ascon_mem_usage" path = "src/bench_ascon_mem_usage.rs" @@ -108,6 +112,10 @@ path = "src/bench_pbkdf2_mem_usage.rs" name = "bench_scrypt_mem_usage" path = "src/bench_scrypt_mem_usage.rs" +[[bin]] +name = "bench_sha1_mem_usage" +path = "src/bench_sha1_mem_usage.rs" + [[bin]] name = "bench_sm3_mem_usage" path = "src/bench_sm3_mem_usage.rs" diff --git a/mem_usage_benches/src/bench_rsa_mem_usage.rs b/mem_usage_benches/src/bench_rsa_mem_usage.rs new file mode 100644 index 000000000..b5822544e --- /dev/null +++ b/mem_usage_benches/src/bench_rsa_mem_usage.rs @@ -0,0 +1,547 @@ +//! The purpose of this binary is to perform a single run of the primitive under test so that +//! its peak memory usage can be measured with: +//! +//! ```text +//! valgrind --tool=massif --heap=no --stacks=yes -- target/release/bench_rsa_mem_usage > /dev/null +//! +//! ms_print massif.out.* +//! ``` +//! +//! or, shoved all into one line: +//! +//! ```text +//! clear; clear; valgrind --tool=massif --heap=no --stacks=yes -- target/release/bench_rsa_mem_usage > /dev/null; ms_print massif.out.*; rm massif.out.* +//! ``` +//! +//! Make sure you build in release mode! +//! +//! The code is using print!() to force the compiler not to optimize away the actual code. +//! It is printing important outputs for benchmarking to stderr so that the rest can be mapped to /dev/null +//! (this is because /usr/bin/time prints useful outputs to stderr as well) +//! +//! Only one representative (scheme, hash) is benched per modulus size (PKCS#1 v1.5/SHA-256): peak +//! stack usage here is dominated by the const-generic-width RSASP1/RSAVP1 modular exponentiation +//! (`L`, this modulus size's own limb count), not by which hash fed into it -- the +//! `crypto/rsa/benches/rsa_*_benches.rs` criterion benches are where per-hash/per-scheme +//! *time* differences are measured instead. +//! +//! Main is at the bottom, controls which this was actually run. + +#![allow(dead_code)] +#![allow(unused_imports)] + +use bouncycastle::core::kem_key::{DecapsulatingKey, EncapsulatingKey}; +use bouncycastle::core::key_material::KeyMaterialTrait; +use bouncycastle::core::signature_key::{ + DeterministicOneShotSigningKey, DeterministicSigningKey, OneShotSigningKey, + OneShotVerifyingKey, SigningKey, VerifyingKey, +}; +use bouncycastle::core::traits::{PrivateKey, PublicKey}; +use bouncycastle::rng::DefaultRNG; +use bouncycastle::rsa::keys::{ + RsaPrivateComponents, RsaPrivateKey, RsaPublicComponents, RsaPublicKey, +}; +use bouncycastle::rsa::rsaes_oaep::OaepParams; +use bouncycastle::rsa::size::RsaSigningSize; +use bouncycastle::rsa::{ + RSA1024, RSA1536, RSA2048, RSA3072, RSA4096, RSA8192, rsa_1024, rsa_1536, rsa_2048, rsa_3072, + rsa_4096, rsa_8192, +}; +use bouncycastle::sha2::SHA256; + +const MSG: &[u8] = b"peak stack usage of RSA sign/verify, held constant across every modulus size"; + +/// This prints the on-disk encoded length and the in-memory struct size of each modulus size's +/// private/public keys, and each modulus size's signature length. This is the source for the +/// table in `bouncycastle_rsa`'s own crate docs' `# Memory Usage` section. +fn print_key_sizes() { + use core::mem::size_of; + + println!("\nRSA-1024 (verification only)"); + println!("public key on disk (n || e): {} bytes", rsa_1024::PK_LEN); + println!( + "size_of>: {} bytes", + size_of::>() + ); + println!("signature: {} bytes", rsa_1024::SIG_LEN); + + println!("\nRSA-1536 (verification only)"); + println!("public key on disk (n || e): {} bytes", rsa_1536::PK_LEN); + println!( + "size_of>: {} bytes", + size_of::>() + ); + println!("signature: {} bytes", rsa_1536::SIG_LEN); + + println!("\nRSA-2048"); + println!("private key on disk (p||q||dP||dQ||qInv||e): {} bytes", rsa_2048::SK_LEN); + println!( + "size_of>: {} bytes", + size_of::>() + ); + println!("public key on disk (n || e): {} bytes", rsa_2048::PK_LEN); + println!( + "size_of>: {} bytes", + size_of::>() + ); + println!( + "size_of: {} bytes", + size_of::() + ); + println!("size_of: {} bytes", size_of::()); + println!( + "RSASVE ciphertext / shared secret: {} / {} bytes", + rsa_2048::CT_LEN, + rsa_2048::SS_LEN + ); + println!("signature: {} bytes", rsa_2048::SIG_LEN); + + println!("\nRSA-3072"); + println!("private key on disk (p||q||dP||dQ||qInv||e): {} bytes", rsa_3072::SK_LEN); + println!( + "size_of>: {} bytes", + size_of::>() + ); + println!("public key on disk (n || e): {} bytes", rsa_3072::PK_LEN); + println!( + "size_of>: {} bytes", + size_of::>() + ); + println!( + "size_of: {} bytes", + size_of::() + ); + println!("size_of: {} bytes", size_of::()); + println!( + "RSASVE ciphertext / shared secret: {} / {} bytes", + rsa_3072::CT_LEN, + rsa_3072::SS_LEN + ); + println!("signature: {} bytes", rsa_3072::SIG_LEN); + + println!("\nRSA-4096"); + println!("private key on disk (p||q||dP||dQ||qInv||e): {} bytes", rsa_4096::SK_LEN); + println!( + "size_of>: {} bytes", + size_of::>() + ); + println!("public key on disk (n || e): {} bytes", rsa_4096::PK_LEN); + println!( + "size_of>: {} bytes", + size_of::>() + ); + println!( + "size_of: {} bytes", + size_of::() + ); + println!("size_of: {} bytes", size_of::()); + println!( + "RSASVE ciphertext / shared secret: {} / {} bytes", + rsa_4096::CT_LEN, + rsa_4096::SS_LEN + ); + println!("signature: {} bytes", rsa_4096::SIG_LEN); + + println!("\nRSA-8192"); + println!("private key on disk (p||q||dP||dQ||qInv||e): {} bytes", rsa_8192::SK_LEN); + println!( + "size_of>: {} bytes", + size_of::>() + ); + println!("public key on disk (n || e): {} bytes", rsa_8192::PK_LEN); + println!( + "size_of>: {} bytes", + size_of::>() + ); + println!( + "size_of: {} bytes", + size_of::() + ); + println!("size_of: {} bytes", size_of::()); + println!( + "RSASVE ciphertext / shared secret: {} / {} bytes", + rsa_8192::CT_LEN, + rsa_8192::SS_LEN + ); + println!("signature: {} bytes", rsa_8192::SIG_LEN); +} + +/// This exists that /usr/bin/time can be used to measure the base memory footprint of the cargo bench harness +fn bench_do_nothing() { + eprintln!("DoNothing"); + + print!("{}", 1 + 1); +} + +fn bench_1024_verify() { + eprintln!("RSA-1024/Verify"); + + let n: [u64; 16] = [ + 0xd00343468eaacfbf, 0xb7c7044cc202dcca, 0x9686f30f478db649, 0x5179b54951fff6aa, + 0xbabb14f550d5d0dd, 0x5405db7c5c8f4cf6, 0x9816e2eda41fd7b9, 0xb31b6abd805bace9, + 0xb909dd0f4c6014f2, 0x9c8a5810b6d05990, 0x40760d1f23fe9250, 0x90adb011a919575a, + 0x45e48572113cab28, 0xcb9ca9ec12000fc8, 0x91b4fcaf62a14595, 0xac9048a7a4f560af, + ]; + let pk = RsaPublicComponents::::new(&n, 0x10001).unwrap(); + let mut sig = [0u8; 128]; + sig.copy_from_slice( + &bouncycastle::hex::decode( + "41339884a9b3940e8488d666bb158063c6a2a2717cae7f564834a876fcbf7098ecf3acbfabf37d38a8e6127b1e313744f1f896e165efdaea0b2e7673867842b9e94db0868ed9a92bcdcb370a4e20ff275c82595e4400a8b9e9f12482f014846b48216f321266ae6ae6338dbcdc41b711e483e6e3e728772e7f9f5ef95c30196b", + ) + .unwrap(), + ); + let msg = bouncycastle::hex::decode("0000000000000000000000000000000000000000").unwrap(); + + if pk.key::().verify(&msg, None, &sig).is_ok() { + eprintln!("Verification succeeded!"); + } else { + panic!("Verification failed! -- figure that out"); + } +} + +fn genuine_2048_key() -> RsaPrivateComponents { + let p: [u64; 16] = [ + 0x0ea36cfb3a5b18f1, 0x48a6e65332119129, 0x110ad9e7b48a1c93, 0x569156b90113e2e9, + 0xe79813a575cfad9c, 0x69d659d143ec6f17, 0xe81e6bab5ddaa783, 0xbff1c5b80a69f788, + 0x978f6c35814f50ee, 0xe6a289ad4cfbf78f, 0x34d5681e5809d415, 0xbb028bda42eeb5d2, + 0x41c56e4de086b0d5, 0x58b8d1e24f3b55d0, 0xfb5248247d98cb7d, 0xdc431050f782e894, + ]; + let q: [u64; 16] = [ + 0x669f140cfbc20f25, 0xb97bb03677207d95, 0xfd4e06f3ed7299d4, 0x160f90536abc9492, + 0xf5b131f39098f7bc, 0xae8d72c57088d7ab, 0x89b94fbde542aba9, 0x3d3f9880ec47d5e0, + 0x1378a6868af3b7a0, 0x5544070beb057c94, 0x16611debc472fac4, 0xe500ffb79f5b8868, + 0x308a5e32196603b2, 0xea5fb19eb4eabc38, 0x122273ae3222b598, 0xbd1a81e7977f9898, + ]; + let d_p: [u64; 16] = [ + 0x209f33f09515d7c1, 0xb4a9b37656917205, 0x276933bb07e4efb9, 0x8c14019808e00414, + 0x289f96da220711e5, 0xfbbd2923d31532fe, 0xc06b414e61c0e1e7, 0x4c23c4588488961d, + 0x4dc48ae34514759c, 0x9c786961ae3e2c35, 0x497e8d9c650688e0, 0x18bf08472612dbe5, + 0x8885fb161870ee12, 0xf21d7c1479d99d47, 0x9121d91952ffd1c7, 0xa94b528b28f29159, + ]; + let d_q: [u64; 16] = [ + 0xf7597ffb68011d8d, 0x7b3cc538c4bab8c9, 0xa8fa480a81a925af, 0x6d6ede7251a383bf, + 0x8a63f788ce3a0f85, 0x0b920502eb478bc9, 0x7e37e755edfe70d9, 0x9cf9948422a16555, + 0x0d6d9ea1f2ef71fd, 0xf7efa32ea0cb6e00, 0x0629b114ca7f780f, 0xcf51176359654348, + 0x540cdcbd4ad35435, 0x31c02ff1a2bc437c, 0xff2503df78bafed5, 0x3af0e72a933aef09, + ]; + let q_inv: [u64; 16] = [ + 0x552fe4bfce945f7b, 0x67e50c999c67247b, 0xfb54ef17be3b2853, 0x241f5921b5ad3983, + 0x02de5eccd143cf31, 0x74e45f6fcc60f216, 0xafa5428a74f12708, 0x88d42294b6a2759b, + 0xe923e1097c0c562f, 0xc968b48a91c38b5b, 0x933e85179c0320b0, 0x7993d0445f758d51, + 0x9bfc042ee0924b1b, 0x41f956d90fa8a793, 0xee7a87b6483a66ee, 0x2640fbfbcfefb163, + ]; + RsaPrivateComponents::::from_crt_components(&p, &q, &d_p, &d_q, &q_inv, 0x10001) + .unwrap() +} + +/// FIPS 186-5 A.1.3 key generation: the candidate buffers, the Miller-Rabin Montgomery context +/// and `mod_pow`'s ladder at the CRT-prime width, plus the `lcm(p - 1, q - 1)`/`d` bound check at +/// the modulus width. +fn bench_2048_keygen() { + eprintln!("RSA-2048/Keygen"); + let (pk, sk) = RSA2048::keygen(&mut DefaultRNG::default()).unwrap(); + println!("{:x?}", pk.key::().encode()); + println!("{}", sk.key::().encode().len()); +} + +fn bench_2048_sign() { + eprintln!("RSA-2048/Sign"); + let sk = genuine_2048_key(); + let sig = sk.key::().sign_deterministic(MSG, None).unwrap(); + println!("{:x?}", sig); +} + +fn bench_2048_verify() { + eprintln!("RSA-2048/Verify"); + let sk = genuine_2048_key(); + let pk = RsaPublicComponents::::new(sk.n(), 0x10001).unwrap(); + let sig = sk.key::().sign_deterministic(MSG, None).unwrap(); + + if pk.key::().verify(MSG, None, &sig).is_ok() { + eprintln!("Verification succeeded!"); + } else { + panic!("Verification failed! -- figure that out"); + } +} + +fn genuine_8192_key() -> RsaPrivateComponents { + let p: [u64; 64] = [ + 0xa9a87892c469b1e5, 0x038c3f4efcb198ac, 0xed4f14df1b8a1e1f, 0xef2330d78ee73020, + 0xd3093ddaf276904c, 0x94a438d69aeaff23, 0x48dbb3d700ad58ed, 0xbbd763b5346ff916, + 0xea402fb475938e3e, 0xcaed4c45c543aff3, 0xc0954c4255b90f57, 0x2fe6242da64a5099, + 0x3fd54a6b6175342c, 0xdf8dd0187588abbd, 0x4abc11d33376e220, 0x90d3482c7fc1397d, + 0xde925fb5a2cb1e7e, 0x062e99dfbd3c790b, 0x243ef703c0912a1e, 0x91ee31a02ef1a02e, + 0x13b19d3960842877, 0xc6e8036e26c4a339, 0xf2606f45a73314c9, 0x5dfe4c6dd0aa04ee, + 0x1385bfde55204d94, 0x454123829d28200d, 0x18a3d86f516f2a50, 0xcbe5e841cd2fdb17, + 0xc86825aae3031a2c, 0xf4726a6681852b6e, 0x3f16b45a496eee29, 0xd5c4b2319abff492, + 0x71077736745aee55, 0x72586dba7b765bbe, 0x681813f6851efdce, 0x196c13fa6d6781d2, + 0x4712ba3eb0734e43, 0xde2a9a8da6da8340, 0xc2f93a2af8ffbaaa, 0x4db552ab82a577ae, + 0x07c075eb13064f67, 0x818a7d0b31680682, 0xa58320f732d69460, 0xa5922479f4aaf594, + 0x4d545baa4cd73f39, 0xa20c87a2660869c4, 0x8350211511fe7d7a, 0x50174a372234ba89, + 0x6eefd36b20bd1ce7, 0x07d124cb61d25c8b, 0x7356e6380041dcd5, 0x6a7c98caab76211a, + 0x61ff7eaac65f815d, 0x1167dc0b28f418b3, 0x9fc8bf056efe8677, 0xf5ce4481e1670e10, + 0x6ae488da222292de, 0xcc786e194ea84d2a, 0x41b134cb6a8ae4f5, 0x870ff94b064466b7, + 0xc82ad608c14a9385, 0x5338550ac9d3f96d, 0xdce87e0d41f1ba9d, 0xef9beedb39920589, + ]; + let q: [u64; 64] = [ + 0x08798e2dd82b7d9f, 0x30208e668897171d, 0x8f73c28d70144ec6, 0x66f64ce7d2402ae0, + 0xdbc26c601d5cc3a3, 0x657176891201beee, 0x692812d7b9b796c5, 0xae27fa9062406a23, + 0x7b4e6ee5b4d2d22f, 0xd846e0e8fbeb0108, 0x52ca75d6866b780b, 0x2620152d7bb490c0, + 0xdca773f826ba9118, 0xb308499a61d0a4eb, 0x44ba0f58bff07ed5, 0x268483fe5829eb5c, + 0x02e7f0c1d3ee3856, 0x76eae3a004d0f37a, 0x99d9cb3aab5b3f1f, 0x0c9f76678a44f2c4, + 0xc82ba3f75883e512, 0x57719c85e8888746, 0x63c967ca1b81cf17, 0x6f4942a86e96bb6a, + 0x614105324fdb77ae, 0xdb6a0c777f7a4bbc, 0x184bf293127472d5, 0xc26798126a967a8f, + 0x45fa10ccadd5ef6e, 0x13cacbbf5cbc2722, 0x23b4e2f2d18785fd, 0x83a4d39485ad254b, + 0x3a096f5ddd674174, 0x6df8f2ed81ae9e7e, 0x77ee2d29fb78201d, 0x4b4c10c9ac8853eb, + 0x35690c51d0ff6208, 0x8de9a271cb50aa59, 0x51b0701f8cdd1505, 0x4cb715c9b578c63b, + 0x3c9b35776d94c3c7, 0xe952d6a7c34a2abb, 0xc432f1fcc2a5105f, 0x4f7f23a62cea2f81, + 0xfa507889f33eedd9, 0x7e37e435cb776085, 0x576b2ad8a4f39820, 0x0a85d1466d55ad69, + 0xb1dee047621be714, 0x216c6b3c1c945527, 0xe6298f6e1575e39e, 0xdd16506432adc399, + 0xc1c065319c823d2e, 0xf2d6f25d6f34a582, 0x75d6801f595c50fc, 0xccfcd556c20e1130, + 0xa24e6a1396173d85, 0xe2cbc5218657c80a, 0xe7bec5bf5a944815, 0x656f5fa54bf06f6c, + 0x7b68b002b0ea62d7, 0xa2eb84753d291781, 0xdd329e1ce00c2087, 0xcdb932d13e38ee0a, + ]; + let d_p: [u64; 64] = [ + 0x848c4d06bcab4c19, 0x2fa349116ae2bfd6, 0xcf9ea12f426f7eb3, 0xfa71d15136d85dff, + 0xc3e3a026e3968f1f, 0xd50f8056de82a33e, 0x68213465c1b3b2d7, 0x426387f62ee9c62e, + 0xeb14efe18920a873, 0xf3c385a60c9dc86c, 0x294ffd8852c4d95e, 0x940d14b53927fef5, + 0x3f709e3b4c8390c3, 0x3b9737d39c42994b, 0x5c02182c4dac78fe, 0x3b6b7c01fe0a0737, + 0x7adeedf6194f6d2c, 0x43c30f449d8ae36c, 0xb88cebf30dac95d4, 0x09fc3d623b8ceb6b, + 0x5d28293b759f2b09, 0xd350dee095846993, 0x1b323dc92b794164, 0xe19d52f0e7ef34bb, + 0x5ff017da15232c02, 0x58fa8d3b24b82973, 0x1c8aed916227e53f, 0xad49cd8938c909d4, + 0xc3d98be0501534a1, 0x91cec83019bd5bb6, 0x985b814d838ffdd2, 0x11df5cb357c86888, + 0xbc0d5590336b8dcf, 0xc25fa85b1912ac66, 0x390c8752384cadef, 0x07b54e62df65825a, + 0x7f7ad57e592cfc3b, 0xed1b7f53d6fe2a09, 0x41d9e577118adb13, 0xb6706780ace45139, + 0xbfbaadef8d19443b, 0x3dc42a1dccca1d87, 0xdb8a72a8ca8d4de7, 0xe10dec18507dbc43, + 0x66343911cfeb0313, 0xd29def907cf51b72, 0x998add714f12ef6f, 0x1c394a4b8053f8ec, + 0x46e0b76d81a07852, 0x498c3f81cb9f2b8d, 0x8fd0019a024e19be, 0xf2d405423b1d94e4, + 0x29ce52d9c49ff544, 0xd72643a03a2f9053, 0x1be76a355cfa02d2, 0x8db921cec169edf6, + 0x728f91a0f7d9dc15, 0xe34e3a4f3d41d26d, 0xab0a691f05332eb8, 0xb6241cc75fd5ee1b, + 0x5b8582afd5c1acda, 0xe405bceba411da3e, 0xd849aacac396ef0e, 0x57b5a6ebccd92cf9, + ]; + let d_q: [u64; 64] = [ + 0x77a312e8aa49ed35, 0x3bdc007b0396dd44, 0x187af52b1d2d6e88, 0x7d84fae3e1b134fa, + 0xb1af50faa281bf7d, 0xf868401279f57864, 0x1dba1e456f88eb01, 0xe2ee28d0f43ba792, + 0x3450781c72a68626, 0x30757ab4889c0c41, 0x7f34c53326389381, 0xa28e969fda4bc5e4, + 0x0ed664e6b7a53062, 0xfc9ad2c9c2bd3cf2, 0x1a7bb5627d58e8ba, 0x68b8c4da5a5a5104, + 0x5a0e586f0ebe7967, 0x2dcff7ca08c9b702, 0x89a724facd778478, 0x027fe07b2ad90a40, + 0xd2f67b0b487433d5, 0x28d451f2f0eaa3ad, 0xee8d5d55700c24ca, 0x584202d4e805a701, + 0xa1c40f0ed77d96a5, 0xc4055e480f1674ba, 0xf9fb2aeb561bf104, 0x6b846fe9ef936161, + 0x128295b5f01cf2ad, 0x4aaff225e483b5dd, 0x7cba43b61174a21c, 0xf68f9c7b4474bcbd, + 0xc8979d3dd627346e, 0x9c2b543e42af83ed, 0x221d3779bb596a50, 0xac4d7c5545e7c88b, + 0xa44c83a4cb2ffe15, 0x414d71c3a67b3563, 0xe22dd5c34f66bf5e, 0x6a9cd6374f4513e7, + 0x27765c4e3c8ee4d5, 0xf632603a9e123d3f, 0x748b0b2d39fcb6bd, 0x0bde2fc8edf891e6, + 0xded2b9cf10705222, 0xe5ca5d358eb8067a, 0x23368f3218b1bd0c, 0xe41d6519183900d0, + 0x36d90382237f0987, 0x858624f4663a543a, 0x2309265e924e5f4c, 0xfc548ae0263785e8, + 0xe010d5d5e76f3406, 0x963cc28c4228ff36, 0x4245a573c17ac537, 0x7e9ab38877e4d606, + 0xc69b8cfcee4fba17, 0xe127881203d02766, 0xf3b33254ff10a7b7, 0x4df7b087512a53dd, + 0x28ffecc1c7a3ee5d, 0x4c693f99aa4b22b7, 0x498cdaef4c3d1223, 0x78c24ba834042b07, + ]; + let q_inv: [u64; 64] = [ + 0xd87df1de9c759f36, 0x3ee1b8b22c8eab2d, 0xd6098595c2696717, 0xa922e4722b8304de, + 0x424bec1c55c1db54, 0x918f2f8bf0ac261a, 0x1e190b2089185564, 0xc0dedbfc6ee606bb, + 0x1d1d701caca565c9, 0x2d735f7a1c5b9d67, 0x8339684f656205db, 0xc2dc06896727d9ce, + 0x6c8d6fe334141d31, 0x5245e157c87cd8b4, 0x4975b68eb2eaad9a, 0xfbc3389ffb0e788d, + 0x5e9a45250d135847, 0x676e7e6a128cfa88, 0x74341d8b28dcbcb8, 0x8f7d07f37a0490e0, + 0x83a0eae9ecc99a0e, 0xa8188892180dc052, 0x3cd79e1eea7809cb, 0x3bcc1d769d917b24, + 0x1d8dc8edc7268e8d, 0x3ce2707055f522ca, 0x163ead0ca2eb5fee, 0xf147fb695aa70022, + 0xab406a6c89161f7d, 0x8fbbfe117a95f46e, 0xa16d4e65396165bd, 0xb54f52ab1bb357e5, + 0x67cdec7b6a349ed9, 0x303875e0d97cf3fa, 0x0af9378ecb114fd8, 0x4ada6f45b9d6b1df, + 0x9ef2cf55de53d0ed, 0x33e4c2070b165b52, 0x3feddf0f7a1158c0, 0x91463a2b1952e83a, + 0x65a9db73de55ef6b, 0x8e18c716a69a9a6a, 0x0ca44356ca6e2898, 0x7df214b19f2114f1, + 0x9af2aee9d5cf1077, 0x22fc8b019fd3d0ff, 0x50c6eead29ab18cd, 0xa7e6621f8eae45fe, + 0x588bde2d99b8692d, 0x339be0a07b4f0a7b, 0xcbdbdcc8717105d2, 0x78bbd3e3392a503e, + 0xb868f9db1cf14f74, 0x52f3dc7f028c9f7e, 0xa3629e034b453834, 0x52bab134f3ae91a2, + 0xd1aac2fe108f98c0, 0x1e799537a42b3060, 0xdbcce6fc287e449b, 0x1985969e5afbc524, + 0x61ba61f820f83597, 0x65c8523f0767bccc, 0xde04e1644a214f9a, 0x9748f8d853be7131, + ]; + RsaPrivateComponents::::from_crt_components(&p, &q, &d_p, &d_q, &q_inv, 0x10001) + .unwrap() +} + +fn bench_8192_sign() { + eprintln!("RSA-8192/Sign"); + let sk = genuine_8192_key(); + let sig = sk.key::().sign_deterministic(MSG, None).unwrap(); + println!("{:x?}", sig); +} + +fn bench_8192_verify() { + eprintln!("RSA-8192/Verify"); + let sk = genuine_8192_key(); + let pk = RsaPublicComponents::::new(sk.n(), 0x10001).unwrap(); + let sig = sk.key::().sign_deterministic(MSG, None).unwrap(); + + if pk.key::().verify(MSG, None, &sig).is_ok() { + eprintln!("Verification succeeded!"); + } else { + panic!("Verification failed! -- figure that out"); + } +} + +/// The modulus of [`genuine_2048_key`], `p * q`, for the functions that measure a public-key +/// operation: building the private key to read `n` off it would put that construction's stack, +/// which is the deeper, in the measurement. +const N_2048: [u64; 32] = [ + 0xf7820283f742b9d5, 0x6f453d1f5b4c2e9c, 0x9a02e5a530e77306, 0x5d12569a62807d3b, + 0xc22c4e5ac0f7c1a4, 0xf9f85e7975005d9b, 0x1b4d9cae79d460d8, 0x69816f48698bcbba, + 0x126422f590975a19, 0xfd7afc3e09ada0f1, 0xed5411eb878daf05, 0x4c03145b5d3495d4, + 0x12be82de4d1ece6b, 0x21d0fceca08d945a, 0x7d9658594266f5c0, 0x4c22da610428e09c, + 0x90ed81299615d981, 0x7a1fa26a8dce26f4, 0x3eff8f17e1a02939, 0x254a2fe9765313a0, + 0x3d3e42e46e48c98e, 0xcd20f79c15e8247f, 0x2ed8a7711a1253fa, 0xb5ab393189db9251, + 0x9e89d6eac8845097, 0x1700f65903b46942, 0x1878d80325b6ef5a, 0x37f9746d3f7cafd3, + 0x094fa1fee82224e6, 0x4a8a5b462ebef717, 0x6e45567151355051, 0xa2b451a07d0aa5f9, +]; + +/// The modulus of [`genuine_8192_key`], as [`N_2048`] is of the RSA-2048 key. +const N_8192: [u64; 128] = [ + 0x1d61042ab2f94e3b, 0xf48eff502c093f51, 0xaa5bc4f9c8864611, 0x1db99c956fbdd1a4, + 0x7740c38dc0641032, 0xa93862a47ba4a132, 0x084763423a1e3191, 0xb1e872ce3811655d, + 0x7d9b6e43e1a2f9e2, 0xba4e9c2b36dabbe8, 0xc507fe8aed9ca2b8, 0xc5906450175fd0cc, + 0xe9a4409728487b57, 0xdc94884b0178d78f, 0x17c4c87dc8281035, 0xac96c76a9846e427, + 0xdf7e3d9db9a47755, 0x0b4353025e768963, 0x27f12a01bdfb74a1, 0x67997c0a9d66235d, + 0x7b7decf82483b6f2, 0x53effe97c44dcd3a, 0x93c1f9f8677d0594, 0xfe737c2bcac36e0a, + 0x978892c9bd7ec5de, 0x7c2cdda67b530f53, 0xf7bae381b684cbd5, 0x4c1d6ac3fa567751, + 0xc573274bdd131b40, 0xdf8d3177c2541827, 0x7f106b9d83e90ae9, 0x2c568fed547825e6, + 0x61fb1c4adcfcb251, 0x90f737d790bda4e3, 0x0e12086d9bb35f0a, 0xf73b3cb66429b918, + 0xbe23ae5ae8aa37e3, 0x7441da06eb8ee824, 0x440ad98e26d4e9e9, 0xeee172a57ef2bfe0, + 0xd7e4a7577bc7c925, 0x8ab720cd38b6709c, 0x0fe68bef0d9a7b77, 0xc1e72ff0d9152bf3, + 0x35dae077e9a6e132, 0xfd1bd0ed310ece7a, 0x87c7ec64286b8883, 0xbd7da0b4b475b56a, + 0x65ee52c9b7774425, 0xa49fac22d107c295, 0xc5c94d7ea6ba2f32, 0xa84b7c461ae1cf71, + 0xdca738bd0c2cbf76, 0x750138e02e57f5bc, 0xb5503a2c69879036, 0xe1298856f3dc0a2d, + 0x5349f37c86ea36e3, 0xf29670ed8ce496a8, 0x4bbc0eb0207c94d1, 0x2d6b8a2e3a2c2d39, + 0x32cac66a8e99ca14, 0x3b14bb88e04b6b53, 0xfbf849e99df6121b, 0xbbdd6e94d5d9e20a, + 0xc247b149e4a2f03b, 0xb3c8485b24661348, 0x1323040e774c2f40, 0xc33618245cfcc322, + 0x9e3ae2251d6e1d5b, 0x6b4a62932e7e86cd, 0x41d1534a82c4c14f, 0x15987cbb1971435a, + 0x107d1835999b07e3, 0xf732476824d89c5e, 0xa94cd4c11400549d, 0x8a5974601ee58869, + 0x262ef75c129f706a, 0xcc06595faeb69abc, 0x0705e98c14e5a060, 0xdee678347b922dda, + 0x3cd3f5134aee1f6e, 0xe93bc2495d65ab8c, 0x36845f106e713f01, 0x247a89cef8a32e58, + 0x2290576030c5f20b, 0x13495b875f9c3a10, 0x09a12e56a44eb809, 0x82d8945abf6d7ae7, + 0x5ce80a99e02a16c0, 0xe2f3df6054ff349c, 0x9828818e69e4cd1a, 0xbd926da43dad328c, + 0xe195d182fd86c4f0, 0x59e7905740689019, 0x4b12503fd098b6da, 0x15397f2b901f921b, + 0x7fc9ddcdc1c28022, 0x740f4fac209a4406, 0xe2e1f1491fc097ae, 0x1734501a90343ef1, + 0xdfe628f30ee7de60, 0x5c8046891b4a35eb, 0xab707f7842944f5b, 0x86a62e6a7fc852c9, + 0xcc8551a26a91f25e, 0x8ed1ea0a7a9f0021, 0x6c22c2632140bac9, 0x76b9c476670eed2a, + 0x4ebe8ce823035344, 0x00948e90d53a3929, 0xb66647c841a5e865, 0xf8aa70e94b4479f4, + 0x6afc21f81d81cd37, 0xbfd00914a190e9d6, 0x2864767d58eb6242, 0x6fa98a034b43d97b, + 0x08e78c3f17b321e8, 0xfb1e660044731ecf, 0x7244a26ca285a2ef, 0xf0b49c466e7d2b33, + 0x32a0e5da63dad5c2, 0x9d48f68729bfafaf, 0x0f9b88a231d0452b, 0x1a0ae555a68f7318, + 0x8814810ca9391395, 0x6d8509d09e1012de, 0x66e85aaa3e05438a, 0xc08d358576b867f0, +]; + +/// RSASVE.GENERATE (SP 800-56B Rev. 2 §7.2.1.2): the `nLen`-byte `Z`/`z` buffers and one +/// public-exponent `mod_pow` at the modulus width. +fn bench_2048_rsasve_encaps() { + eprintln!("RSA-2048/RSASVE encaps"); + let pk = rsa_2048::RSA2048KEMPublicKey::new(&N_2048, 0x10001).unwrap(); + let (ss, ct) = pk.encaps(&mut DefaultRNG::default(), ()).unwrap(); + println!("{:x?}", ct); + println!("{}", ss.key_len()); +} + +/// RSASVE.RECOVER (SP 800-56B Rev. 2 §7.2.1.3): the same CRT exponentiation as signing, plus +/// the `nLen`-byte `Z` buffer. +fn bench_2048_rsasve_decaps() { + eprintln!("RSA-2048/RSASVE decaps"); + let sk = rsa_2048::RSA2048KEMPrivateKey::from_bytes( + &genuine_2048_key().key::().encode(), + ) + .unwrap(); + let mut ct = [0x5Au8; rsa_2048::CT_LEN]; + ct[0] = 0x01; // well inside (1, n - 1) + let ss = sk.decaps(&ct, ()).unwrap(); + println!("{}", ss.key_len()); +} + +/// RSASVE.GENERATE (SP 800-56B Rev. 2 §7.2.1.2): the `nLen`-byte `Z`/`z` buffers and one +/// public-exponent `mod_pow` at the modulus width. +fn bench_8192_rsasve_encaps() { + eprintln!("RSA-8192/RSASVE encaps"); + let pk = rsa_8192::RSA8192KEMPublicKey::new(&N_8192, 0x10001).unwrap(); + let (ss, ct) = pk.encaps(&mut DefaultRNG::default(), ()).unwrap(); + println!("{:x?}", ct); + println!("{}", ss.key_len()); +} + +/// RSASVE.RECOVER (SP 800-56B Rev. 2 §7.2.1.3): the same CRT exponentiation as signing, plus +/// the `nLen`-byte `Z` buffer. +fn bench_8192_rsasve_decaps() { + eprintln!("RSA-8192/RSASVE decaps"); + let sk = rsa_8192::RSA8192KEMPrivateKey::from_bytes( + &genuine_8192_key().key::().encode(), + ) + .unwrap(); + let mut ct = [0x5Au8; rsa_8192::CT_LEN]; + ct[0] = 0x01; // well inside (1, n - 1) + let ss = sk.decaps(&ct, ()).unwrap(); + println!("{}", ss.key_len()); +} + +/// RSAES-OAEP encapsulation (RFC 8017 §7.1.1) with SHA-256: the EME-OAEP encoding and one +/// public-exponent `mod_pow` at the modulus width. +fn bench_2048_oaep_encaps() { + eprintln!("RSA-2048/OAEP encaps"); + let pk = rsa_2048::RSA2048KEMPublicKey::new(&N_2048, 0x10001).unwrap(); + let (ss, ct) = pk.encaps(&mut DefaultRNG::default(), OaepParams::::new(b"")).unwrap(); + println!("{:x?}", ct); + println!("{}", ss.key_len()); +} + +/// RSAES-OAEP decapsulation (RFC 8017 §7.1.2) with SHA-256: the CRT exponentiation and the +/// constant-time EME-OAEP decoding. The ciphertext is not a valid one, so the result is the +/// decryption error, which the decoding reaches only after doing all of its work. +fn bench_2048_oaep_decaps() { + eprintln!("RSA-2048/OAEP decaps"); + let sk = rsa_2048::RSA2048KEMPrivateKey::from_bytes( + &genuine_2048_key().key::().encode(), + ) + .unwrap(); + let mut ct = [0x5Au8; rsa_2048::CT_LEN]; + ct[0] = 0x01; // below n + let result = sk.decaps(&ct, OaepParams::::new(b"")); + println!("{}", result.is_err()); +} + +/// RSAES-OAEP encapsulation (RFC 8017 §7.1.1) with SHA-256: the EME-OAEP encoding and one +/// public-exponent `mod_pow` at the modulus width. +fn bench_8192_oaep_encaps() { + eprintln!("RSA-8192/OAEP encaps"); + let pk = rsa_8192::RSA8192KEMPublicKey::new(&N_8192, 0x10001).unwrap(); + let (ss, ct) = pk.encaps(&mut DefaultRNG::default(), OaepParams::::new(b"")).unwrap(); + println!("{:x?}", ct); + println!("{}", ss.key_len()); +} + +/// RSAES-OAEP decapsulation (RFC 8017 §7.1.2) with SHA-256: the CRT exponentiation and the +/// constant-time EME-OAEP decoding. The ciphertext is not a valid one, so the result is the +/// decryption error, which the decoding reaches only after doing all of its work. +fn bench_8192_oaep_decaps() { + eprintln!("RSA-8192/OAEP decaps"); + let sk = rsa_8192::RSA8192KEMPrivateKey::from_bytes( + &genuine_8192_key().key::().encode(), + ) + .unwrap(); + let mut ct = [0x5Au8; rsa_8192::CT_LEN]; + ct[0] = 0x01; // below n + let result = sk.decaps(&ct, OaepParams::::new(b"")); + println!("{}", result.is_err()); +} + +fn main() { + print_key_sizes() + // bench_do_nothing() + // bench_1024_verify() + // bench_2048_keygen() + // bench_2048_sign() + // bench_2048_verify() + // bench_8192_sign() + // bench_8192_verify() + // bench_2048_rsasve_encaps() + // bench_2048_rsasve_decaps() + // bench_8192_rsasve_encaps() + // bench_8192_rsasve_decaps() + // bench_2048_oaep_encaps() + // bench_2048_oaep_decaps() + // bench_8192_oaep_encaps() + // bench_8192_oaep_decaps() +} diff --git a/mem_usage_benches/src/bench_sha1_mem_usage.rs b/mem_usage_benches/src/bench_sha1_mem_usage.rs new file mode 100644 index 000000000..2105cc4b9 --- /dev/null +++ b/mem_usage_benches/src/bench_sha1_mem_usage.rs @@ -0,0 +1,161 @@ +//! Stack usage of the SHA-1 entry points, and the in-memory sizes printed by `print_struct_sizes`, +//! the source of the "Memory Usage" tables in the `bouncycastle_digest::sha1` module docs. +//! +//! As with Ascon, a call needs a few hundred bytes, below the floor of the process's own start-up +//! that `bench_aes_mem_usage` describes, so massif cannot see it. The figures in the crate docs +//! are read from the compiler the way `bench_ascon_mem_usage` describes: `-C remark=prologepilog` +//! gives each function's frame and `--emit=asm` its calls, after LTO, and a figure is the deepest +//! chain of frames below the entry point plus 8 bytes of return address per call, not following +//! the panic paths. With every bench called from `main`: +//! +//! ```text +//! cargo rustc --release -p mem_usage_benches --bin bench_sha1_mem_usage -- -C remark=prologepilog --emit=asm +//! ``` +//! +//! Each entry point is called through a `black_box`ed function pointer, which gives it an +//! out-of-line body of its own, so the frame being read is the entry point's and not the +//! harness closure's. The inputs are built in `#[inline(never)]` helpers, so their frames are +//! siblings of the operation's. + +#![allow(dead_code)] +#![allow(unused_imports)] + +use core::hint::black_box; + +use bouncycastle::core::traits::{Hash, HashOneShot, Suspendable}; +use bouncycastle::digest::sha1::{SHA1, SUSPENDED_SHA1_STATE_LEN}; + +/// Two full 64-byte blocks and a partial one. +const MSG_LEN: usize = 150; + +/// This exists so /usr/bin/time can measure the base memory footprint of the harness itself. +#[inline(never)] +fn bench_do_nothing() { + eprintln!("DoNothing"); + + print!("{}", 1 + 1); +} + +/// Prints the in-memory size of each value a caller holds between calls, and the size of its +/// suspended state. Neither depends on how much data has been processed. +#[inline(never)] +fn print_struct_sizes() { + use core::mem::size_of; + + println!("size_of: {}", size_of::()); + println!("SUSPENDED_SHA1_STATE_LEN: {}", SUSPENDED_SHA1_STATE_LEN); +} + +/// Runs the operation in its own frame. Returns nothing, so no result crosses the boundary. +#[inline(never)] +fn measure(f: impl FnOnce()) { + f() +} + +/// A message filled at run time, so that its contents are not a constant the compiler could fold +/// the whole computation over. +#[inline(never)] +fn message(fill: u8) -> [u8; N] { + let mut m = [0u8; N]; + m.fill(black_box(fill)); + m +} + +/// An SHA1 that has taken the message, so the final pads a partial block. +#[inline(never)] +fn sha1_after_data() -> SHA1 { + let mut h = SHA1::new(); + h.do_update(&message::(0xa5)); + h +} + +#[inline(never)] +fn bench_sha1_update() { + eprintln!("SHA1::do_update, {MSG_LEN} B"); + let h = black_box(SHA1::new()); + let msg = black_box(message::(0xa5)); + measure(move || { + let mut h = h; + let op = black_box(::do_update as fn(&mut SHA1, &[u8])); + op(&mut h, &msg); + black_box(&h); + }); +} + +#[inline(never)] +fn bench_sha1_final() { + eprintln!("SHA1::do_final_out"); + let h = black_box(sha1_after_data()); + measure(move || { + let mut out = [0u8; 20]; + let op = black_box(::do_final_out as fn(SHA1, &mut [u8]) -> usize); + let n = op(h, &mut out); + print!("{:x?}", &out[..n]); + }); +} + +#[inline(never)] +fn bench_sha1_final_partial_bits() { + eprintln!("SHA1::do_final_partial_bits_out"); + let h = black_box(sha1_after_data()); + measure(move || { + let mut out = [0u8; 20]; + let op = black_box( + ::do_final_partial_bits_out + as fn(SHA1, u8, usize, &mut [u8]) -> Result, + ); + let n = op(h, 0xa0, 3, &mut out).unwrap(); + print!("{:x?}", &out[..n]); + }); +} + +#[inline(never)] +fn bench_sha1_oneshot() { + eprintln!("SHA1::hash_out, {MSG_LEN} B"); + let msg = black_box(message::(0xa5)); + measure(move || { + let mut out = [0u8; 20]; + let op = black_box(::hash_out as fn(&[u8], &mut [u8]) -> usize); + let n = op(&msg, &mut out); + print!("{:x?}", &out[..n]); + }); +} + +#[inline(never)] +fn bench_sha1_suspend() { + eprintln!("SHA1::suspend"); + let h = black_box(sha1_after_data()); + measure(move || { + let op = black_box( + >::suspend + as fn(SHA1) -> [u8; SUSPENDED_SHA1_STATE_LEN], + ); + let state = op(h); + print!("{:x?}", &state[..]); + }); +} + +#[inline(never)] +fn bench_sha1_from_suspended() { + eprintln!("SHA1::from_suspended"); + let state = black_box(sha1_after_data().suspend()); + measure(move || { + let op = black_box( + >::from_suspended + as fn([u8; SUSPENDED_SHA1_STATE_LEN]) -> Result, + ); + let h = op(state).unwrap(); + black_box(&h); + }); +} + +fn main() { + print_struct_sizes() + // bench_do_nothing() + // bench_sha1_update() + // bench_sha1_final() + // bench_sha1_final_partial_bits() + // bench_sha1_oneshot() + // bench_sha1_suspend() + // bench_sha1_from_suspended() +} diff --git a/mem_usage_benches/src/lib.rs b/mem_usage_benches/src/lib.rs index 21b954363..45aa17638 100644 --- a/mem_usage_benches/src/lib.rs +++ b/mem_usage_benches/src/lib.rs @@ -25,7 +25,9 @@ mod bench_mlkem_mem_usage; mod bench_pbkdf2_mem_usage; mod bench_poly1305_mem_usage; mod bench_ripemd_mem_usage; +mod bench_rsa_mem_usage; mod bench_scrypt_mem_usage; +mod bench_sha1_mem_usage; mod bench_sha2_mem_usage; mod bench_sha3_mem_usage; mod bench_sm2_mem_usage; diff --git a/src/lib.rs b/src/lib.rs index 417743dc3..b9cce71cc 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -27,6 +27,7 @@ pub use bouncycastle_pqc::mldsa_lowmemory; pub use bouncycastle_pqc::mlkem; pub use bouncycastle_pqc::mlkem_lowmemory; pub use bouncycastle_rng as rng; +pub use bouncycastle_rsa as rsa; pub use bouncycastle_sha2 as sha2; pub use bouncycastle_sha3 as sha3; pub use bouncycastle_sm2 as sm2;