diff --git a/.github/workflows/oaep-ct.yml b/.github/workflows/oaep-ct.yml new file mode 100644 index 00000000..efaf1de7 --- /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/.gitignore b/.gitignore index 41d845b5..37bb4d39 100644 --- a/.gitignore +++ b/.gitignore @@ -22,3 +22,4 @@ custom_mutants_output/ .claude/settings.local.json .claude 2/ dev_scripts/aes_ct_harness/Cargo.lock +dev_scripts/oaep_ct_harness/Cargo.lock diff --git a/CLAUDE.md b/CLAUDE.md index 000049e3..a254e22a 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 @@ -437,7 +437,7 @@ external vector suites — is specified in QUALITY_AND_STYLE.md and CONTRIBUTING ## CI -Six workflows under `.github/workflows/`, all triggered by pull requests: +Seven 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-scrypt --no-default-features`, since `--all-features` never @@ -448,6 +448,10 @@ 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. - `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 diff --git a/Cargo.toml b/Cargo.toml index 29052463..09be0dc5 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -47,6 +47,8 @@ bouncycastle-mldsa-lowmemory = { path = "./crypto/mldsa-lowmemory" } bouncycastle-poly1305 = { path = "./crypto/poly1305" } bouncycastle-ripemd = { path = "./crypto/ripemd" } bouncycastle-rng = { path = "./crypto/rng" } +bouncycastle-rsa = { path = "./crypto/rsa" } +bouncycastle-sha1 = { path = "./crypto/sha1" } bouncycastle-sha2 = { path = "./crypto/sha2" } bouncycastle-sha3 = { path = "./crypto/sha3" } bouncycastle-sm2 = { path = "./crypto/sm2" } @@ -113,6 +115,8 @@ bouncycastle-mlkem-lowmemory.workspace = true bouncycastle-poly1305.workspace = true bouncycastle-ripemd.workspace = true bouncycastle-rng.workspace = true +bouncycastle-rsa.workspace = true +bouncycastle-sha1.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 ef895a49..a3b2b3ef 100644 --- a/alpha_0.1.4_release_notes.md +++ b/alpha_0.1.4_release_notes.md @@ -70,6 +70,16 @@ * `bouncycastle-dhkem` -- the generic DHKEM leaves `bouncycastle-hpke` for a crate of its own (`bouncycastle_hpke::dhkem::*` is now `bouncycastle_dhkem::*`), and gains `AuthEncap` and `AuthDecap`. Its `_out` functions return the number of bytes written. +* SHA-1 -- `bouncycastle-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`) and is reached only by name; `HashFactory` "SHA1" and the + `sha1` CLI command. Checked against NIST's CAVP SHAVS vectors and RFC 3174's. +* 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 fd6cc7d6..4cfebdc1 100644 --- a/cli/src/main.rs +++ b/cli/src/main.rs @@ -27,7 +27,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; @@ -58,6 +62,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; @@ -4412,6 +4419,414 @@ enum Subcommands { x: bool, }, + /// RSASVE over RSA-2048: the RSA KEM of SP 800-56B Rev. 2 SS7.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 SS7.1, SP 800-56B Rev. 2 SS7.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 SS8.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 SS8.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 SS8.2) or + /// RSASSA-PSS (RFC 8017 SS8.1, or RFC 8702 SS3.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 + /// `RsaPrivateKey`/`RsaPublicKey`'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 SS5). + 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 SS5'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 @@ -4473,6 +4888,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 { @@ -8191,6 +8615,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); } @@ -8206,6 +8744,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 c469d00f..bcadba48 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 00000000..30a53644 --- /dev/null +++ b/cli/src/rsa_cmd.rs @@ -0,0 +1,738 @@ +//! 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. `ctx` (accepted by the traits for +//! conformance) is not exposed as a flag: RSA has no context-string input, and `bouncycastle_rsa` +//! documents the parameter as ignored, 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: an RSA private key file (RFC 8017's CRT quintuple) does not carry +//! the public exponent `e`, so there is no `PkFromSk`/`CheckConsistency` here, 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 those types): 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); +} + +/// See `RsaPrivateKey`'s `# Encoding` docs for the expected layout; a wrong-length file is one of +/// the `DecodingError`s `PrivateKey::from_bytes` reports. +fn parse_sk, const SK_LEN: usize>(bytes: &[u8], alg_name: &str) -> SK { + match SK::from_bytes(bytes) { + 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 `RsaPublicKey`'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"); + + // `do_verify_init` is infallible for every `bouncycastle_rsa` verifier (it only stores the key + // and a fresh hash state), 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>; + +/// One (size, scheme, hash) pairing `S`, generating a key pair, or signing or verifying stdin, +/// per `action`. PSS pairings draw their salt from the library's default OS-backed RNG inside +/// `S::do_sign_final`; `keygen` is the size's FIPS 186-5 generator, independent of scheme and hash. +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 (an RSA \ + private key file does not carry e, so it cannot be derived 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 => { + let sk = parse_sk::, SK_LEN>( + require_secret(skfile, "skfile").ref_to_bytes(), + alg_name, + ); + let mut signer = SigningKey::::create_signer( + &sk, + &mut HashDRBG_SHA512::new_from_os(), + None, + ) + .unwrap(); + stream_stdin(|chunk| signer.do_update(chunk)); + let sig = signer.do_final().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 => { + let sk = parse_sk::, SK_LEN>( + require_secret(skfile, "skfile").ref_to_bytes(), + alg_name, + ); + let mut signer = + DeterministicSigningKey::::create_signer_deterministic(&sk, None) + .unwrap(); + stream_stdin(|chunk| signer.do_update(chunk)); + let sig = signer.do_final().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 00000000..f35cc57b --- /dev/null +++ b/cli/src/rsa_oaep_cmd.rs @@ -0,0 +1,279 @@ +//! 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::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::sha1::SHA1; +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 00000000..0fb89647 --- /dev/null +++ b/cli/src/rsasve_cmd.rs @@ -0,0 +1,216 @@ +//! 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`. Nothing +//! else would work, because an RSA private key file does not carry `e`. +//! +//! 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 (an RSA \ + private key file does not carry e, so it cannot be derived 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 sk = SK::from_bytes(require_secret(skfile, "skfile").ref_to_bytes()).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 ct = crate::mlkem_cmd::read_ciphertext::(ctfile, alg_name); + let ss = sk.decaps(&ct, ()).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 00000000..dd26c831 --- /dev/null +++ b/cli/src/sha1_cmd.rs @@ -0,0 +1,6 @@ +use crate::helpers::stream_hash; +use bouncycastle::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 00000000..4f98d448 --- /dev/null +++ b/cli/tests/rsa_cli_tests.rs @@ -0,0 +1,365 @@ +//! 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` 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", +); +/// Its public key, `n || e` with `e = 0x10001`. +const PK_2048_HEX: &str = concat!( + "a2b451a07d0aa5f96e455671513550514a8a5b462ebef717094fa1fee82224e6", + "37f9746d3f7cafd31878d80325b6ef5a1700f65903b469429e89d6eac8845097", + "b5ab393189db92512ed8a7711a1253facd20f79c15e8247f3d3e42e46e48c98e", + "254a2fe9765313a03eff8f17e1a029397a1fa26a8dce26f490ed81299615d981", + "4c22da610428e09c7d9658594266f5c021d0fceca08d945a12be82de4d1ece6b", + "4c03145b5d3495d4ed5411eb878daf05fd7afc3e09ada0f1126422f590975a19", + "69816f48698bcbba1b4d9cae79d460d8f9f85e7975005d9bc22c4e5ac0f7c1a4", + "5d12569a62807d3b9a02e5a530e773066f453d1f5b4c2e9cf7820283f742b9d5", + "00010001", +); +/// 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", + "00010001", +); +/// 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)[..639]); + let err = run_err( + &["rsa-2048", "sign", "--scheme", "pkcs1v15", "--hash", "sha256", "--skfile", &short_sk], + b"msg", + ); + assert!(err.contains("640 bytes"), "stderr: {err}"); + + let short_pk = temp_file("shortpk", &unhex(PK_2048_HEX)[..259]); + 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("260 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 640-byte private key to stdout and a 260-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 * 640, "private key on stdout, hex"); + let pk_hex = std::fs::read_to_string(&pkfile).unwrap(); + assert_eq!(pk_hex.trim().len(), 2 * 260, "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 00000000..6ab4a5aa --- /dev/null +++ b/cli/tests/rsa_oaep_cli_tests.rs @@ -0,0 +1,219 @@ +//! 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` 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", +); +/// Its public key, `n || e`. +const PK_HEX: &str = concat!( + "a2b451a07d0aa5f96e455671513550514a8a5b462ebef717094fa1fee82224e6", + "37f9746d3f7cafd31878d80325b6ef5a1700f65903b469429e89d6eac8845097", + "b5ab393189db92512ed8a7711a1253facd20f79c15e8247f3d3e42e46e48c98e", + "254a2fe9765313a03eff8f17e1a029397a1fa26a8dce26f490ed81299615d981", + "4c22da610428e09c7d9658594266f5c021d0fceca08d945a12be82de4d1ece6b", + "4c03145b5d3495d4ed5411eb878daf05fd7afc3e09ada0f1126422f590975a19", + "69816f48698bcbba1b4d9cae79d460d8f9f85e7975005d9bc22c4e5ac0f7c1a4", + "5d12569a62807d3b9a02e5a530e773066f453d1f5b4c2e9cf7820283f742b9d5", + "00010001", +); +/// 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 00000000..0980cd69 --- /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 be9a20ed..f16aa257 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 00000000..47961f48 --- /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::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_rng::FixedSeedRNG; +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 2d552f02..b646f2f0 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 839cc70f..fd849c9a 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 3805d092..a07e8bd1 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] @@ -385,3 +400,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 00000000..03816181 --- /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 f25ca05f..bdb09af1 100644 --- a/crypto/core/src/lib.rs +++ b/crypto/core/src/lib.rs @@ -13,6 +13,7 @@ pub mod hazmat; 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/factory/Cargo.toml b/crypto/factory/Cargo.toml index 626729e0..dac859c6 100644 --- a/crypto/factory/Cargo.toml +++ b/crypto/factory/Cargo.toml @@ -12,6 +12,7 @@ bouncycastle-kbkdf.workspace = true bouncycastle-core.workspace = true bouncycastle-hmac.workspace = true bouncycastle-ripemd.workspace = true +bouncycastle-sha1.workspace = true bouncycastle-sha2.workspace = true bouncycastle-sha3.workspace = true bouncycastle-sm3.workspace = true diff --git a/crypto/factory/src/hash_factory.rs b/crypto/factory/src/hash_factory.rs index 62813178..dcd7d034 100644 --- a/crypto/factory/src/hash_factory.rs +++ b/crypto/factory/src/hash_factory.rs @@ -40,6 +40,8 @@ use bouncycastle_core::security_strength::SecurityStrength; use bouncycastle_core::traits::{AlgorithmInfo, FinishToken, Hash}; use bouncycastle_ripemd as ripemd; use bouncycastle_ripemd::{RIPEMD128_NAME, RIPEMD160_NAME, RIPEMD256_NAME, RIPEMD320_NAME}; +use bouncycastle_sha1 as sha1; +use bouncycastle_sha1::SHA1_NAME; use bouncycastle_sha2 as sha2; use bouncycastle_sha2::{ SHA224_NAME, SHA256_NAME, SHA384_NAME, SHA512_224_NAME, SHA512_256_NAME, SHA512_NAME, @@ -84,6 +86,9 @@ pub enum HashFactory { RIPEMD256(ripemd::RIPEMD256), /// Legacy; see the `bouncycastle-ripemd` crate docs. RIPEMD320(ripemd::RIPEMD320), + /// SHA-1, by its name only: it is not collision resistant and carries no security + /// strength. For interoperation with what already uses it. + SHA1(sha1::SHA1), /// AsconHash256(ascon::AsconHash256), /// BLAKE2b with a 64-byte digest (RFC 7693), unkeyed. The keyed mode is in @@ -135,6 +140,7 @@ impl AlgorithmFactory for HashFactory { RIPEMD160_NAME => Ok(Self::RIPEMD160(ripemd::RIPEMD160::new())), RIPEMD256_NAME => Ok(Self::RIPEMD256(ripemd::RIPEMD256::new())), RIPEMD320_NAME => Ok(Self::RIPEMD320(ripemd::RIPEMD320::new())), + SHA1_NAME => Ok(Self::SHA1(sha1::SHA1::new())), ASCON_HASH256_NAME => Ok(Self::AsconHash256(ascon::AsconHash256::new())), BLAKE2B_512_NAME => Ok(Self::BLAKE2b_512(blake2::BLAKE2b_512::new())), BLAKE2S_256_NAME => Ok(Self::BLAKE2s_256(blake2::BLAKE2s_256::new())), @@ -165,6 +171,7 @@ impl AlgorithmInfo for HashFactory { Self::RIPEMD160(h) => h.alg_name(), Self::RIPEMD256(h) => h.alg_name(), Self::RIPEMD320(h) => h.alg_name(), + Self::SHA1(h) => h.alg_name(), Self::AsconHash256(h) => h.alg_name(), Self::BLAKE2b_512(h) => h.alg_name(), Self::BLAKE2s_256(h) => h.alg_name(), @@ -189,6 +196,7 @@ impl AlgorithmInfo for HashFactory { Self::RIPEMD160(h) => h.max_security_strength(), Self::RIPEMD256(h) => h.max_security_strength(), Self::RIPEMD320(h) => h.max_security_strength(), + Self::SHA1(h) => h.max_security_strength(), Self::AsconHash256(h) => h.max_security_strength(), Self::BLAKE2b_512(h) => h.max_security_strength(), Self::BLAKE2s_256(h) => h.max_security_strength(), @@ -215,6 +223,7 @@ impl Hash for HashFactory { Self::RIPEMD160(h) => h.block_bitlen(), Self::RIPEMD256(h) => h.block_bitlen(), Self::RIPEMD320(h) => h.block_bitlen(), + Self::SHA1(h) => h.block_bitlen(), Self::AsconHash256(h) => h.block_bitlen(), Self::BLAKE2b_512(h) => h.block_bitlen(), Self::BLAKE2s_256(h) => h.block_bitlen(), @@ -239,6 +248,7 @@ impl Hash for HashFactory { Self::RIPEMD160(h) => h.output_len(), Self::RIPEMD256(h) => h.output_len(), Self::RIPEMD320(h) => h.output_len(), + Self::SHA1(h) => h.output_len(), Self::AsconHash256(h) => h.output_len(), Self::BLAKE2b_512(h) => h.output_len(), Self::BLAKE2s_256(h) => h.output_len(), @@ -263,6 +273,7 @@ impl Hash for HashFactory { Self::RIPEMD160(h) => h.do_update(data), Self::RIPEMD256(h) => h.do_update(data), Self::RIPEMD320(h) => h.do_update(data), + Self::SHA1(h) => h.do_update(data), Self::AsconHash256(h) => h.do_update(data), Self::BLAKE2b_512(h) => h.do_update(data), Self::BLAKE2s_256(h) => h.do_update(data), @@ -289,6 +300,7 @@ impl Hash for HashFactory { Self::RIPEMD160(h) => h.finish_into(token, output), Self::RIPEMD256(h) => h.finish_into(token, output), Self::RIPEMD320(h) => h.finish_into(token, output), + Self::SHA1(h) => h.finish_into(token, output), Self::AsconHash256(h) => h.finish_into(token, output), Self::BLAKE2b_512(h) => h.finish_into(token, output), Self::BLAKE2s_256(h) => h.finish_into(token, output), @@ -323,6 +335,7 @@ impl Hash for HashFactory { Self::RIPEMD160(h) => h.finish_partial_bits_into(token, partial_byte, num_bits, output), Self::RIPEMD256(h) => h.finish_partial_bits_into(token, partial_byte, num_bits, output), Self::RIPEMD320(h) => h.finish_partial_bits_into(token, partial_byte, num_bits, output), + Self::SHA1(h) => h.finish_partial_bits_into(token, partial_byte, num_bits, output), Self::AsconHash256(h) => { h.finish_partial_bits_into(token, partial_byte, num_bits, output) } diff --git a/crypto/factory/tests/hash_factory_tests.rs b/crypto/factory/tests/hash_factory_tests.rs index 057a8354..b0a459c0 100644 --- a/crypto/factory/tests/hash_factory_tests.rs +++ b/crypto/factory/tests/hash_factory_tests.rs @@ -28,6 +28,7 @@ mod hash_factory_tests { (bouncycastle_ripemd::RIPEMD160_NAME, None), (bouncycastle_ripemd::RIPEMD256_NAME, None), (bouncycastle_ripemd::RIPEMD320_NAME, None), + (bouncycastle_sha1::SHA1_NAME, SecurityStrength::None), (bouncycastle_ascon::ASCON_HASH256_NAME, _128bit), ]; for (name, strength) in table { @@ -191,6 +192,25 @@ mod hash_factory_tests { } } + #[test] + fn sha1_hash_tests() { + // Expected values: RFC 3174 Section 7.3, TEST1 and TEST2. + for name in ["SHA1", bouncycastle_sha1::SHA1_NAME] { + let h = HashFactory::new(name).unwrap(); + assert_eq!(h.output_len(), 20); + assert_eq!(h.block_bitlen(), 512); + assert_eq!( + h.hash(b"abc"), + b"\xa9\x99\x3e\x36\x47\x06\x81\x6a\xba\x3e\x25\x71\x78\x50\xc2\x6c\x9c\xd0\xd8\x9d" + ); + let h = HashFactory::new(name).unwrap(); + assert_eq!( + h.hash(b"abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq"), + b"\x84\x98\x3e\x44\x1c\x3b\xd2\x6e\xba\xae\x4a\xa1\xf9\x51\x29\xe5\xe5\x46\x70\xf1" + ); + } + } + #[test] fn sm3_hash_tests() { use bouncycastle_sm3 as sm3; diff --git a/crypto/rsa/Cargo.toml b/crypto/rsa/Cargo.toml new file mode 100644 index 00000000..43d1aebb --- /dev/null +++ b/crypto/rsa/Cargo.toml @@ -0,0 +1,45 @@ +[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-rng.workspace = true +bouncycastle-sha1.workspace = true +bouncycastle-sha2.workspace = true +bouncycastle-sha3.workspace = true +bouncycastle-utils.workspace = true + +[dev-dependencies] +bouncycastle-core-test-framework.workspace = true +bouncycastle-hex.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 00000000..64034a00 --- /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_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 00000000..7a85fbce --- /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_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 00000000..e5f6c5b4 --- /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) + .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 00000000..56e3dd56 --- /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) + .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 00000000..a5e3f0fd --- /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) + .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 00000000..1c1df9d4 --- /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) + .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 00000000..1b37d959 --- /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 00000000..51044e7d --- /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 00000000..3f71f701 --- /dev/null +++ b/crypto/rsa/src/emsa_pkcs1_v1_5.rs @@ -0,0 +1,447 @@ +//! 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::traits::{AlgorithmOID, HashAlgParams}; + +/// `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. +/// 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; + +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 digest is one hash output"); + 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`. +pub fn emsa_pkcs1_v1_5_encode_from_hash( + digest: &[u8], +) -> [u8; K_LEN] { + 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]); + 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. +pub fn emsa_pkcs1_v1_5_verify_from_hash( + digest: &[u8], + em: &[u8; K_LEN], +) -> bool { + 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 + // SS9.2 note 1's structure enforced at line 109 above), 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) + } + + /// [`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 (line 119) 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 2: `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 2: `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 00000000..17e9c6a5 --- /dev/null +++ b/crypto/rsa/src/emsa_pss.rs @@ -0,0 +1,370 @@ +//! 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, so `modBits` (and therefore `emLen = K_LEN`) is always a multiple of 8; that +//! makes `8 * K_LEN - emBits = 8 * K_LEN - (8 * K_LEN - 1) = 1` for every concrete instantiation +//! here, so 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::mgf1::MAX_HASH_LEN; +use crate::rsassa_pss::PssParams; +use bouncycastle_core::traits::{HashAlgParams, HashOneShot}; + +/// EMSA-PSS-ENCODE (RFC 8017 §9.1.1) from step 3 onward, with `emBits` fixed to `8 * K_LEN - 1` +/// (see the module docs), steps 1-2's `mHash = Hash(M)` supplied by the caller (either +/// [`crate::rsassa_pss`] hashing a whole message in one call, or a streaming `Signer` that hashed +/// it incrementally -- this function itself never sees the message), and the salt supplied +/// rather than generated here -- [`crate::rsassa_pss`] draws it from an RNG; this function stays +/// deterministic so it can be tested directly against a known salt. Step 3's error ("encoding +/// error", `emLen < hLen + sLen + 2`) is a `debug_assert`, since every (hash, modulus size) +/// pairing this crate wires up has a modulus far wider than any hash-plus-salt combination it +/// offers. +/// 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`. +pub fn emsa_pss_encode_from_hash( + m_hash: &[u8], + salt: &[u8], +) -> [u8; K_LEN] +where + H: HashOneShot + HashAlgParams, + P: PssParams, +{ + let h_len = H::OUTPUT_LEN; + let s_len = P::SALT_LEN; + debug_assert_eq!(m_hash.len(), h_len, "emsa_pss_encode: mHash is one hash output"); + debug_assert_eq!(salt.len(), s_len, "emsa_pss_encode: the salt is the parameters' length"); + debug_assert!( + K_LEN >= h_len + s_len + 2, + "emsa_pss_encode: modulus too short for this hash/salt" + ); + 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; + 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. +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; + debug_assert_eq!(m_hash.len(), h_len, "emsa_pss_verify: mHash is one hash output"); + // 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) + } + + 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) + } + + 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 00000000..b4e3a437 --- /dev/null +++ b/crypto/rsa/src/keygen.rs @@ -0,0 +1,630 @@ +//! 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 concrete sizes wire this up as `keygen(rng)` in their own modules +//! (`RsaSigningSize::keygen`, which the size markers' generators wrap): `nlen` is fixed by the width, `e` by +//! [`PUBLIC_EXPONENT`], and the Miller-Rabin round count and required RNG strength by each size's +//! row of FIPS 186-5 Table B.1 and 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 same construction +//! `rsa_core::rsasp1` already builds over the secret primes on every signature. + +use crate::keys::{RsaPrivateComponents, RsaPublicComponents}; +use crate::modexp::{MontgomeryContext, mod_pow, mul_mod, reduce_wide}; +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: u32 = 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 93% of odd composites are caught here, 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 prime `e` and `0 < r < e`, as `r^(e - 2) mod e` (Fermat), by a fixed 32-step +/// square-and-multiply. +fn inv_mod_u64_prime(r: u64, e: u64) -> u64 { + debug_assert!(r != 0 && r < e); + let exp = e - 2; + let mut acc: u128 = 1; + let base = u128::from(r); + let m = u128::from(e); + for bit in (0..32).rev() { + acc = (acc * acc) % m; + if (exp >> bit) & 1 == 1 { + acc = (acc * base) % m; + } + } + acc as u64 +} + +/// `e^-1 mod m` for `m > 1` with `GCD(m, e) = 1`, where `e` is [`PUBLIC_EXPONENT`]. +/// +/// 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 small and prime, 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]) -> [u64; N] { + let e = u64::from(PUBLIC_EXPONENT); + 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. + debug_assert_ne!(r, 0, "e must not divide m"); + let k = e - inv_mod_u64_prime(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 `out` with `64 * N` bits from `rng` (FIPS 186-5 Appendix B.2.1: the string is read as a +/// big-endian integer; here limb `N - 1` holds its most significant 64 bits). +fn fill_random( + rng: &mut dyn RNG, + out: &mut [u64; N], +) -> Result<(), SignatureError> { + let mut buf = [0u8; 8]; + for limb in out.iter_mut() { + rng.next_bytes_out(&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. +/// +/// `rounds` must be at least the value FIPS 186-5 Table B.1 gives for the candidate's length and +/// the caller's target error probability (see each size module's `keygen` for the value it uses); +/// its 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. +pub fn is_probable_prime( + 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 nonzero here (both checked above), which is all `MontgomeryContext::new` + // requires, so this cannot fail. + let mut ctx = Secret::>::new(); + *ctx = MontgomeryContext::new(w).expect("w is odd and nonzero"); + + // 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, u64::from(PUBLIC_EXPONENT)) == 1 { + continue; + } + if is_probable_prime::(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.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 +/// (Table B.1) 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. +pub fn keygen_from_rng( + rng: &mut dyn RNG, + rounds: NonZeroUsize, + required_strength: SecurityStrength, +) -> Result<(RsaPublicComponents, RsaPrivateComponents), SignatureError> +where + K: RsaSigningSize + RsaSize, +{ + debug_assert_eq!(HALF2, 2 * HALF); + // 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); + 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); + let d_high = &d[HALF..]; + let d_low = &d[..HALF]; + let mut one_high = [0u64; HALF]; + one_high[0] = 1; + let d_exceeds_half = d_high.iter().any(|&l| l != 0) + && !(d_high == one_high && d_low.iter().all(|&l| l == 0)); + if !d_exceeds_half { + // "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); + let mut d_q = Secret::<[u64; HALF]>::new(); + *d_q = inverse_of_e_mod(&q_minus_1); + // 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), so the context exists. + let mut ctx_p = Secret::>::new(); + *ctx_p = MontgomeryContext::new(&p).expect("p is odd"); + *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)?; + 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. +#[cfg(test)] +mod tests { + use super::*; + + 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 00000000..ab8d51b0 --- /dev/null +++ b/crypto/rsa/src/keys.rs @@ -0,0 +1,474 @@ +//! 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`), 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::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}; +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 4 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: u32, +} + +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) or `e` is even or below 3 (RFC 8017 §3.1: `e` is odd and at least 3). + pub fn new(n: &K::Limbs, e: u32) -> Result { + if n.as_ref()[0] & 1 == 0 { + return Err(SignatureError::DecodingError("RSA modulus must be odd")); + } + if e < 3 || e & 1 == 0 { + return Err(SignatureError::DecodingError( + "RSA public exponent must be odd and at least 3", + )); + } + 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) -> u32 { + 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; 4] = bytes[K::K_LEN..].try_into().expect("PK_LEN is K_LEN + 4"); + Self::new(&n, u32::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`). +/// Not a key: the keys over it are [`RsaPrivateKey`] and [`crate::rsasve::RsaKEMPrivateKey`]. +/// +/// `p` and `q` need not be the same bit length: RFC 8017 §3.2 requires only that both are prime +/// and `p * q = n`, nothing about their relative magnitude. An earlier version of this type +/// required equal bit length anyway, so its CRT recombination could reduce one residue mod the +/// other prime with a single conditional subtraction (valid only when the smaller prime's residue +/// is `< 2 *` the larger prime, which equal bit length guarantees but does not itself require). +/// [`crate::modexp::reduce_wide`]'s general bit-serial reduction handles any magnitude +/// relationship instead, at the same asymptotic cost this crate already pays to reduce the +/// `n`-width message down to each prime's width, so the extra restriction bought nothing and is +/// not reimposed here. +/// +/// # Encoding +/// +/// The keys' `PrivateKey::encode`/`from_bytes`, at a signing size, use the raw layout +/// `p || q || dP || dQ || qInv`, each `K::K_LEN / 2` big-endian bytes, `K::SK_LEN` in all. Not an +/// RFC 8017 or ASN.1 format -- see [`RsaPublicKey`]'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 five components the same way [`Self::from_crt_components`] does. +#[derive(Clone, 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 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, computing `n = p * q`. Returns + /// `Err(`[`SignatureError::DecodingError`]`)` if `p` or `q` is even, `p == q`, or `dP`, + /// `dQ` or `qInv` is not below its prime. Primality is not checked (see the crate's + /// `# Security Considerations`). + pub fn from_crt_components( + p: &K::HalfLimbs, + q: &K::HalfLimbs, + d_p: &K::HalfLimbs, + d_q: &K::HalfLimbs, + q_inv: &K::HalfLimbs, + ) -> Result { + 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. + let n = K::modulus_from_primes(p, q); + + let mut key = Self { + p: Secret::new(), + q: Secret::new(), + d_p: Secret::new(), + d_q: Secret::new(), + q_inv: Secret::new(), + n, + }; + *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 { + /// The modulus `n = p * q`, as little-endian limbs. + pub fn n(&self) -> &K::Limbs { + &self.n + } + + /// A copy of these components as the private key of `A`. + pub fn key>(&self) -> RsaPrivateKey { + RsaPrivateKey::from_components(self.clone()) + } + + /// 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 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 + } + + /// 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. + pub(crate) fn from_bytes_raw(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; + Self::from_crt_components(p, q, d_p, d_q, q_inv) + } +} + +/// 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: u32) -> 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) -> u32 { + 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 four 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, 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, + ) -> Result { + Ok(Self::from_components(RsaPrivateComponents::from_crt_components(p, q, d_p, d_q, q_inv)?)) + } +} + +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() + } +} + +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 { + *out = self.components.encode_raw(); + 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") + })?; + Ok(Self::from_components( + RsaPrivateComponents::from_bytes_raw(bytes).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"), + } +} diff --git a/crypto/rsa/src/lib.rs b/crypto/rsa/src/lib.rs new file mode 100644 index 00000000..6429088f --- /dev/null +++ b/crypto/rsa/src/lib.rs @@ -0,0 +1,413 @@ +//! 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 and the signing roles); [`RSA1024`] and [`RSA1536`] implement `RsaSize` only, so +//! a private key, `keygen` and every signing-role impl are absent for them at compile time +//! rather than refused at run time. +//! +//! 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)?; +//! let pk = RsaPublicKey::::new(sk.n(), 0x10001)?; +//! let mut rng = HashDRBG_SHA512::new_from_os(); +//! +//! // One-shot. RSA has no context string, so `ctx` is `None` (a `Some` is accepted and ignored). +//! // 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_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)?; +//! let pk = RSA2048KEMPublicKey::new(sk.n(), 65537)?; +//! +//! // 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 for every modulus size this crate offers -- 1024 +//! and 1536 (verification only, per `# Scope` above) and 2048/3072/4096/8192 (both directions) -- +//! 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 each `rsa_*.rs` module's +//! own tests 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) | 132 | 136 | -- | -- | +//! | RSA-1536 (verify-only) | 196 | 200 | -- | -- | +//! | RSA-2048 | 260 | 264 | 640 | 896 | +//! | RSA-3072 | 388 | 392 | 960 | 1344 | +//! | RSA-4096 | 516 | 520 | 1280 | 1792 | +//! | RSA-8192 | 1028 | 1032 | 2560 | 3584 | +//! +//! 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) | 10120 | 34216 | +//! | RSASVE encaps | 10696 | 35464 | +//! | RSASVE decaps | 10744 | 40776 | +//! | OAEP encaps (SHA-256) | 10280 | 31000 | +//! | OAEP decaps (SHA-256) | 10264 | 39976 | +//! +//! All values are in bytes. "On disk" is the `PublicKey`/`PrivateKey` raw +//! layout ([`keys::RsaPublicKey`]'s and [`keys::RsaPrivateKey`]'s `# Encoding`: `n || e`, and +//! `p || q || dP || dQ || qInv` 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. +//! - **Imported keys are not validated for primality.** [`keys::RsaPrivateKey::from_crt_components`] +//! checks that `p`/`q` are odd and distinct and that `dP`/`dQ`/`qInv` are in range, but does +//! not test `p` and `q` for primality or `e` for coprimality with `λ(n)`. Supplying non-prime or +//! otherwise malformed CRT components produces a key that computes *something*, silently, +//! rather than being rejected -- validating imported key material's number-theoretic properties +//! before construction is the caller's responsibility (`keygen::is_probable_prime` is available +//! for the primality part). 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` is accepted but ignored.** RSASSA-PKCS1-v1_5 and RSASSA-PSS (RFC 8017 §8) have no +//! context-string input; the key traits' `ctx` parameter is accepted for trait +//! conformance and silently ignored, as `bouncycastle-ecdsa` does for ECDSA. A caller relying +//! on `ctx` to bind a signature to an application context gets no such binding here and must +//! fold the context into 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 (see `# Scope`) +//! precisely so they can only be used to check signatures against legacy/third-party data, not +//! to produce new ones. +//! - **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. +//! - **RSASVE public exponents are limited to 32 bits.** SP 800-56B §6.2.1 allows +//! `65,537 <= e < 2^256`, but [`keys::RsaPublicKey`] holds `e` as a `u32`, so an RSASVE public +//! key with a larger `e` cannot be constructed. (ACVP's RSADP vectors use exponents of up to 56 +//! bits, which is why only their decapsulation side is tested here: decapsulation never needs +//! `e`.) +//! - **RSASVE key validation is partial.** The KEM key types check `e >= 65,537` and that `n` has +//! exactly the size's bit length, on top of the signature keys' checks. They 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; + +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 00000000..4ef3b63c --- /dev/null +++ b/crypto/rsa/src/mgf1.rs @@ -0,0 +1,148 @@ +//! 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; + +/// MGF1 (RFC 8017 Appendix B.2.1), with `mgfSeed` fixed at `H_LEN` bytes and `maskLen` fixed at +/// `MASK_LEN` (a compile-time constant here, since every call site in this crate knows its output +/// width in advance -- `emLen - hLen - 1` for a concrete modulus/hash pairing). Step 1's error +/// ("mask too long", `maskLen > 2^32 hLen`) cannot occur for any `MASK_LEN` this crate reaches +/// (at most a few KiB, for an 8192-bit modulus), so it is not checked. `SEED_LEN` is `H_LEN + 4` +/// (the seed plus the 4-octet counter `C`), a separate const parameter for the same reason +/// [`bouncycastle_ec::montgomery`]'s `L2 = 2 * L` is: stable Rust cannot compute one const +/// generic from another. +/// 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 00000000..0d3109a1 --- /dev/null +++ b/crypto/rsa/src/modexp.rs @@ -0,0 +1,308 @@ +//! 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::new`] additionally derives `R mod n` and `R^2 mod n` (`R = 2^(64L)`) by +//! repeated doubling-and-reduction, rather than requiring them precomputed. +//! +//! Both of these operate on the modulus alone, which is public in RSA (shared between the public +//! and private key), so they run in variable time -- the same reasoning +//! [`bouncycastle_ec::inverse_vartime`] documents for operating on public curve/scalar values. +//! [`mod_pow`] is the one piece here that operates on a value 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. +//! +//! # 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-based `rsasp1` (the only caller that +//! exponentiates with a secret exponent) 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}; + +/// `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`). +fn double_mod_n(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`, by `bits` repeated doublings from `1`. Variable time, like +/// `double_mod_n`: the modulus is public. +fn pow2_mod(bits: u32, n: &[u64; L]) -> [u64; L] { + let mut acc = [0u64; L]; + acc[0] = 1; + for _ in 0..bits { + acc = double_mod_n(&acc, 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 -- see the module docs' note on [`montgomery::redc`]'s precondition. +pub fn mul_mod( + a: &[u64; L], + b: &[u64; L], + ctx: &MontgomeryContext, +) -> [u64; L] { + 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`'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` and odd `modulus`, in constant time: see +/// [`reduce_wide`] for why (the modulus can be secret, unlike `pow2_mod`'s). +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 odd `modulus`, in constant +/// time with respect to `modulus`. Unlike `pow2_mod`/`double_mod_n`, which assume 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) -- `s2 < q` gives no useful bound +/// relative to `p` in general (RFC 8017 does not require `p` and `q` to be close in magnitude), +/// so this does not special-case a single conditional subtraction the way `double_mod_n` does +/// for the (public, and by construction `< n`) doubling case. 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 +} + +/// 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] }; +} + +impl MontgomeryContext { + /// Builds the Montgomery context for `modulus`. Returns `None` if `modulus` is even or zero; + /// Montgomery reduction requires an odd modulus, and RSA's is always odd (a product of two + /// odd primes). + pub fn new(modulus: &[u64; L]) -> Option { + if modulus[0] & 1 == 0 || nat::is_zero(modulus).to_bool() { + return None; + } + let n_prime = mont_n_prime(modulus[0]); + let r_mod_n = pow2_mod(64 * L as u32, modulus); + let r2_mod_n = pow2_mod(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). +pub fn mod_pow( + base: &[u64; L], + exponent: &[u64; L], + ctx: &MontgomeryContext, +) -> [u64; L] { + 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 +} diff --git a/crypto/rsa/src/rsa_1024.rs b/crypto/rsa/src/rsa_1024.rs new file mode 100644 index 00000000..8d76162c --- /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 00000000..1a09572b --- /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 00000000..983f10ac --- /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`. +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 00000000..b9ee4143 --- /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`. +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 00000000..68e1d129 --- /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`. +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 00000000..aa88f7a3 --- /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`. +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 00000000..ed98c12d --- /dev/null +++ b/crypto/rsa/src/rsa_core.rs @@ -0,0 +1,252 @@ +//! RSASP1 and RSAVP1 (RFC 8017 §5.2.1, §5.2.2): the raw signature and verification primitives. +//! Crate-private -- never exposed directly, only reachable through a padding scheme +//! (RSASSA-PKCS1-v1_5 or RSASSA-PSS, a later addition to this crate). RFC 8017's introduction to +//! §5 is explicit about 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, so this crate does not let a caller reach [`rsasp1`]/[`rsavp1`] without +//! going through a scheme that fixes that. +//! +//! 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, mul_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::secret::{Secret, 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. +pub(crate) fn public_exp( + n: &[u64; L], + e: u32, + x: &[u64; L], +) -> [u64; L] { + let ctx = MontgomeryContext::::new(n) + .expect("RsaPublicComponents::new already validated n is odd and nonzero"); + let mut e_limbs = [0u64; L]; + e_limbs[0] = e as u64; + mod_pow::(x, &e_limbs, &ctx) +} + +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")); + } + Ok(K::crt_exp(sk, m)) +} + +/// RFC 8017 §5.2.1 step 2.b, the CRT form of `m^d mod n`, over the five components: the size +/// marker's `crt_exp` forwards here with the size's widths. Constant time in the key: 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(); + *ctx_p = MontgomeryContext::::new(p) + .expect("RsaPrivateComponents::from_crt_components already validated p is odd and nonzero"); + let mut ctx_q = Secret::>::new(); + *ctx_q = MontgomeryContext::::new(q) + .expect("RsaPrivateComponents::from_crt_components already validated q is odd and nonzero"); + // Step 2.b.i: 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.iii: h = (s_1 - s_2) * qInv mod p, with s_2 reduced mod p first (the primes need + // not be the same length; see RsaPrivateComponents' docs). + 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.iv: 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. Every value below is a genuine 2048-bit RSA keypair + //! (two independently generated, Miller-Rabin-tested ~1024-bit primes, `e = 65537`), and every + //! expected signature was cross-checked two ways in Python 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] = [ + 0xfec673c1b07d4997, 0x98c9e3737faecc8b, 0x01369d6bebcfd19b, 0x8aadc1799d493a6e, + 0x958ca74fe2a455a1, 0x686e62c9e375661d, 0xbf73814b7bf6fe14, 0x791ffe2d364719e4, + 0xc82e25af581825a1, 0x716d239de20732c7, 0xdb517e266b0c15bc, 0xe92c721464fa1e50, + 0x683e7fcc3898a002, 0xc7f69cb8c57e630f, 0xc467ab3a006acdf7, 0xe189725eddf8ccb3, + ]; + let q: [u64; 16] = [ + 0x7b4cf8c928cc535f, 0x59f055409b91aa89, 0xcd0ba689661c56d5, 0xe4659bfb595039f4, + 0x751842ab04e21054, 0xe2c2655760ebb5fc, 0xb2f71094e48dc76b, 0x2efed995e680919d, + 0x83c35ffcfdb9ee9d, 0xfe4a5fdb9f28a01b, 0x0ebf4a61e23c7524, 0x8cc355a69e45d7e6, + 0x9589828fca436940, 0x4cd1bfe875cddd70, 0x203e0d5e8d4d3acb, 0x86278c27281306ec, + ]; + let d_p: [u64; 16] = [ + 0xa7c48ae44e99dd99, 0xa6794425077c6c01, 0x0f7f8dfabf278380, 0xb481c3d6cf359f60, + 0xa5b5efbc5d9f744a, 0x91b95de874b741a1, 0xea3152a3da97ddf5, 0xe180bda330e9eba0, + 0xbcbfcc51e73a7a34, 0x019d0405e258c3c0, 0x0b08c52c187e3667, 0x84a723999981f7c1, + 0x5e50dc3287b126ff, 0xd0204fd4674f4ac6, 0x6e786ef11d0686f6, 0xa82c39200c1c4d67, + ]; + let d_q: [u64; 16] = [ + 0x0bc1fcecb5c853bf, 0x2000c1caf24e96d2, 0xb423419c07e0736a, 0x90bcb6fb03d68029, + 0xd811d2e24994ff2e, 0x5a89a6b7c7c83737, 0xbdea803dc4157f87, 0xffe93a09240b9b65, + 0xe6f584c8dc80c30a, 0x5e66076e22c91c3c, 0xb41221e6b67af91b, 0x2e3d8c36b1d9d161, + 0x7b1309bb3857cb1f, 0xee8de5186c920235, 0x5e4785a534bec7a3, 0x85883dd007ea907c, + ]; + let q_inv: [u64; 16] = [ + 0xf1be36246c217ae1, 0x079e038ceb7506d7, 0x2021f982bc5f6713, 0x55fa8fdd926a4d0f, + 0xb927b5edab1a24b8, 0xc2a1d37632cfb70e, 0x9ef39b4a3f144e8a, 0x70efa5974ed43d2f, + 0x6ea50741414ce321, 0x7df35889e34d4f38, 0x859106459f51850b, 0xd59e422a92f4a7a2, + 0x0c1e16e70fcbe362, 0xcf95cadb6a1f450d, 0x106a4e948e405012, 0x95a3415bfb9b5ff6, + ]; + RsaPrivateComponents::from_crt_components(&p, &q, &d_p, &d_q, &q_inv) + .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] = [ + 0x364cc26d0358bbf4, 0xe66706a5c785ddb2, 0x988d10d740263405, 0x8730f3278e45205e, + 0xaf89fbc49c9a1249, 0x9eb8f7a84273ca48, 0xabaf5851d3f5426c, 0x0ba36a5d9c8c66a3, + 0x4ed17840c5f6e1da, 0x9e2acb65a840fecb, 0x738ba4ec9cdd22f7, 0x9f55aaf16f290bac, + 0x0882623816565d42, 0x0377a272e9477155, 0x479e6d3b5fc7cdf0, 0x982fc26936177b5a, + 0x0b5865236931b18c, 0xf013b20ea0f2a40b, 0xa30f42ffc4e00f37, 0xac385621648ddc31, + 0x1516eadafe0e2d2e, 0xa1241270647a6b51, 0x682d73ffca96c494, 0x6f2ab34339689b72, + 0x9cc67858bfcb237c, 0x3ca10b66cf56d9dc, 0x9e2aecc899fa34b9, 0x87ae32e45faca1d8, + 0xe6407b5fa454d3c9, 0x7c66144074c5739e, 0x72db535464e48005, 0x3e7bf2011ccdf96c, + ]; + + 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] = [ + 0xbc9607fe59ae13d0, 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, + ]; + let expected_s2: [u64; 32] = [ + 0x279fb473681292dc, 0x90dd3361616e1fba, 0x4be153bf0cc9bc54, 0xc182310ffe516be1, + 0xde08597f0526ba7f, 0x0ecf2548fd2becbd, 0xf100a0d8ab9cac48, 0x7e79521337c90850, + 0x642ecb9c26db1f8b, 0x888c707e26d47319, 0x3fe925626dabfde5, 0x5e374b37fa2875b2, + 0x57afec45ed3a06de, 0xa2184c3a6deb8156, 0x466017505ec5110d, 0x6b462b5d6f8c46f8, + 0x22b90fde8ff49648, 0xe6b9526894cfffba, 0xf5193a402a3c063c, 0xdc2d25c6ec27f87b, + 0x272f960bef731aed, 0xb8d7c2a5e9ef52cf, 0x5e82a247d76a2bbe, 0x018d6155cbc9c0fd, + 0x16f1861e4a32fa83, 0xab553b4f2fe5e561, 0x1c55445d8e2e8530, 0xa08e2522099e36e7, + 0xbcda0d67e80f74f5, 0xe8b549b81d5eb31d, 0xf1d74cf682145c5d, 0x74643dc08434c3e1, + ]; + + 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(_)) + )); + } +} diff --git a/crypto/rsa/src/rsaes_oaep.rs b/crypto/rsa/src/rsaes_oaep.rs new file mode 100644 index 00000000..3f27e453 --- /dev/null +++ b/crypto/rsa/src/rsaes_oaep.rs @@ -0,0 +1,467 @@ +//! 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 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::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_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. +#[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 +/// 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: 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(); + rng.next_bytes_out(&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, +{ + 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; + } + // m = RSADP(K, c), constant time in the key; step 2.c: EM = I2OSP(m, k). + let mut m = Secret::::new(); + *m = K::crt_exp(&sk.0, &c); + let mut em = Secret::<[u8; N]>::new(); + *em = K::be_bytes_from_limbs(&m); + // 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: 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(); + rng.next_bytes_out(&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: 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: 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 00000000..ca33291a --- /dev/null +++ b/crypto/rsa/src/rsassa.rs @@ -0,0 +1,404 @@ +//! 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::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. +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. + 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. + fn emsa_encode(m_hash: &[u8]) -> [u8; K_LEN]; +} + +/// 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. + fn emsa_encode(m_hash: &[u8], salt: &[u8]) -> [u8; K_LEN]; +} + +/// 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` is accepted and ignored, RSA having no context string. + /// + /// # Errors + /// [`SignatureError::RNGError`] if the RNG fails to deliver. + 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") }; + let mut salt = [0u8; MAX_HASH_LEN]; + rng.next_bytes_out(&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; + + /// Cannot fail; `ctx` is accepted and ignored, RSA having no context string. + fn create_signer_deterministic<'k>( + &'k self, + _ctx: Option<&[u8]>, + ) -> Result, SignatureError> { + 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; + + /// Cannot fail; `ctx` is accepted and ignored. + fn create_verifier<'k>( + &'k self, + _ctx: Option<&[u8]>, + ) -> Result, SignatureError> { + 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::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::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") }; + let mut salt = [0u8; MAX_HASH_LEN]; + rng.next_bytes_out(&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`]. +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::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, +{ + 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 00000000..7955509a --- /dev/null +++ b/crypto/rsa/src/rsassa_pkcs1_v1_5.rs @@ -0,0 +1,60 @@ +//! 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::security_strength::SecurityStrength; +use bouncycastle_core::signature_key::SignatureAlgorithm; +use bouncycastle_core::traits::{Algorithm, AlgorithmOID, 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. One key type serves every +/// scheme and hash, so a call names the marker: +/// a key over it signs through `DeterministicSigningKey`, `sk.sign_deterministic(msg, None)`. +/// `ctx` is accepted and ignored, since RSA has no context string. +#[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 { + emsa_pkcs1_v1_5_verify_from_hash::(m_hash, em) + } +} + +impl RsaDeterministicSignatureAlgorithm + for RSASSA_PKCS1_v1_5 +{ + fn emsa_encode(m_hash: &[u8]) -> [u8; K_LEN] { + 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 00000000..9e7f755e --- /dev/null +++ b/crypto/rsa/src/rsassa_pss.rs @@ -0,0 +1,218 @@ +//! 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::security_strength::SecurityStrength; +use bouncycastle_core::signature_key::SignatureAlgorithm; +use bouncycastle_core::traits::{Algorithm, 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` is accepted and ignored, since RSA has no context +/// string. +#[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 { + emsa_pss_verify_from_hash::(m_hash, em) + } +} + +impl + SaltedPss> + RsaRandomizedSignatureAlgorithm for RSASSA_PSS +{ + const SALT_LEN: usize = P::SALT_LEN; + + fn emsa_encode(m_hash: &[u8], salt: &[u8]) -> [u8; K_LEN] { + emsa_pss_encode_from_hash::(m_hash, salt) + } +} + +impl + UnsaltedPss> + RsaDeterministicSignatureAlgorithm for RSASSA_PSS +{ + fn emsa_encode(m_hash: &[u8]) -> [u8; K_LEN] { + 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 00000000..57986695 --- /dev/null +++ b/crypto/rsa/src/rsasve.rs @@ -0,0 +1,403 @@ +//! 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 key types enforce two things: +//! +//! * `65,537 <= e` (§6.2.1 item 2, "65,537 ≤ e < 2^256"; the upper bound holds by construction, +//! because `e` is a `u32`). This applies to the public key only: the CRT private key does not +//! carry `e`. +//! * `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::keys::{RsaPrivateComponents, RsaPublicComponents, decoding_error}; +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: u32 = 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 the modulus's top bit is set: `n` has exactly the size's bit length. +fn has_full_bit_length(n: &K::Limbs) -> bool { + n.as_ref()[n.as_ref().len() - 1] >> 63 == 1 +} + +/// Whether `1 < x < n - 1` (§7.2.1.2 step 2's range, §7.2.1.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. +#[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` or `n`'s top bit is clear (see the module docs' `# Key validation`). + pub fn new(n: &K::Limbs, e: u32) -> 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(KEMError::DecodingError( + "RSA key-establishment public exponent must be at least 65537", + )); + } + if !has_full_bit_length::(pk.n()) { + return Err(KEMError::DecodingError("RSA modulus must have its top bit set")); + } + 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) -> u32 { + 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. Returns + /// `Err(`[`KEMError::DecodingError`]`)` in the cases [`RsaPrivateComponents::from_crt_components`] + /// rejects, and also if `n = p * q`'s top bit is clear (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, + ) -> Result { + Self::from_rsa_key( + RsaPrivateComponents::from_crt_components(p, q, d_p, d_q, q_inv).map_err(kem_error)?, + ) + } + + pub(crate) fn from_rsa_key(sk: RsaPrivateComponents) -> Result { + if !has_full_bit_length::(sk.n()) { + return Err(KEMError::DecodingError("RSA modulus must have its top bit set")); + } + Ok(Self(sk)) + } + + /// The modulus `n = p * q`, as little-endian limbs. + pub fn n(&self) -> &K::Limbs { + self.0.n() + } +} + +/// 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_from::(K::keygen(rng)) + } +} + +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 + K: 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; + rng.next_bytes_out(&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 1), `z = C^d mod n` by the CRT (step 2) and `Z = I2BS(z, nLen)` into `ss` (step 3), + /// zeroized first and left so on error. + #[allow(non_snake_case)] + fn decaps_out(&self, ct: &[u8; N], ss: &mut KeyMaterial) -> Result { + 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(); + *z = K::crt_exp(&self.sk.0, &c); + 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: 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 { + *out = self.0.encode_raw(); + 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") + })?; + Self::from_rsa_key(RsaPrivateComponents::from_bytes_raw(bytes).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 four 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 00000000..1892c7c1 --- /dev/null +++ b/crypto/rsa/src/rsasve_kdf.rs @@ -0,0 +1,219 @@ +//! 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::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). +#[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: 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. + #[allow(non_snake_case)] + fn encaps_out( + &self, + rng: &mut dyn RNG, + ct: &mut [u8; N], + ss: &mut KeyMaterial, + ) -> Result { + 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. + #[allow(non_snake_case)] + fn decaps_out(&self, ct: &[u8; N], ss: &mut KeyMaterial) -> Result { + 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: 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 00000000..38a9f9fe --- /dev/null +++ b/crypto/rsa/src/size.rs @@ -0,0 +1,655 @@ +//! 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_from_rng; +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::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 + 4`: the public key's encoding, `n || e`. + const PK_LEN: usize; + /// `5 * K_LEN / 2`: the private key's encoding, `p || q || dP || dQ || qInv`. + 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`. + fn public_exp(n: &Self::Limbs, e: u32, x: &Self::Limbs) -> Self::Limbs; +} + +/// A size this crate signs and generates keys at: RSA-2048 and up (SP 800-131A's 112-bit floor). +pub trait RsaSigningSize: RsaSize { + /// The Miller-Rabin rounds FIPS 186-5 Table B.1 asks of a prime of this size. + const 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, or + /// if no prime was found within the candidate budget. + 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; + /// `m^d mod n` by the CRT (RSASP1 / RSADP's exponentiation), `m < n`, constant time in the + /// key. + fn crt_exp(sk: &RsaPrivateComponents, m: &Self::Limbs) -> Self::Limbs; +} + +/// 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 the crate'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, + > { + let (pk, sk) = K::keygen(rng)?; + Ok((RsaPublicKey::from_components(pk), RsaPrivateKey::from_components(sk))) + } + + fn generate_pss_signature_key_pair( + rng: &mut dyn RNG, + ) -> Result<(RsaPublicKey>, RsaPrivateKey>), SignatureError> + { + let (pk, sk) = K::keygen(rng)?; + Ok((RsaPublicKey::from_components(pk), RsaPrivateKey::from_components(sk))) + } + + fn generate_pss_signature_key_pair_with>( + rng: &mut dyn RNG, + ) -> Result< + (RsaPublicKey>, RsaPrivateKey>), + SignatureError, + > { + let (pk, sk) = K::keygen(rng)?; + 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> { + crate::rsasve::keygen_from::(K::keygen(rng)) + } +} + +/// 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 + 4, "PK_LEN is n || e"); + assert!( + >::LEN == K::PK_LEN, + "PublicKeyEncoded is PK_LEN bytes" + ); + assert!(K::SK_LEN == 5 * K::K_LEN / 2, "SK_LEN is the five CRT components"); + 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 = 132; + const SK_LEN: usize = 320; + 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; 132]; + type PrivateKeyEncoded = [u8; 320]; + + 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: u32, 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 = 196; + const SK_LEN: usize = 480; + 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; 196]; + type PrivateKeyEncoded = [u8; 480]; + + 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: u32, 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 = 260; + const SK_LEN: usize = 640; + 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; 260]; + type PrivateKeyEncoded = [u8; 640]; + + 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: u32, 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(5).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 + } + + fn crt_exp(sk: &RsaPrivateComponents, m: &Self::Limbs) -> Self::Limbs { + rsa_core::crt_exp::<32, 64, 65, 16, 32, 33>( + sk.p(), + sk.q(), + sk.d_p(), + sk.d_q(), + sk.q_inv(), + m, + ) + } +} + +/// 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 = 388; + const SK_LEN: usize = 960; + 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; 388]; + type PrivateKeyEncoded = [u8; 960]; + + 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: u32, 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(4).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 + } + + fn crt_exp(sk: &RsaPrivateComponents, m: &Self::Limbs) -> Self::Limbs { + rsa_core::crt_exp::<48, 96, 97, 24, 48, 49>( + sk.p(), + sk.q(), + sk.d_p(), + sk.d_q(), + sk.q_inv(), + m, + ) + } +} + +/// 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 = 516; + const SK_LEN: usize = 1280; + 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; 516]; + type PrivateKeyEncoded = [u8; 1280]; + + 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: u32, 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(4).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 + } + + fn crt_exp(sk: &RsaPrivateComponents, m: &Self::Limbs) -> Self::Limbs { + rsa_core::crt_exp::<64, 128, 129, 32, 64, 65>( + sk.p(), + sk.q(), + sk.d_p(), + sk.d_q(), + sk.q_inv(), + m, + ) + } +} + +/// 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 = 1028; + const SK_LEN: usize = 2560; + 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; 1028]; + type PrivateKeyEncoded = [u8; 2560]; + + 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: u32, 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(4).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 + } + + fn crt_exp(sk: &RsaPrivateComponents, m: &Self::Limbs) -> Self::Limbs { + rsa_core::crt_exp::<128, 256, 257, 64, 128, 129>( + sk.p(), + sk.q(), + sk.d_p(), + sk.d_q(), + sk.q_inv(), + m, + ) + } +} + +mod sealed { + pub trait Sealed {} +} diff --git a/crypto/rsa/tests/keygen_tests.rs b/crypto/rsa/tests/keygen_tests.rs new file mode 100644 index 00000000..c8e6ec0d --- /dev/null +++ b/crypto/rsa/tests/keygen_tests.rs @@ -0,0 +1,324 @@ +//! 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::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) 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::new(false).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(&mut self, len: usize) -> Result, RNGError> { + Ok(vec![self.fill; len]) + } + 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)) + )); +} + +/// 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 00000000..e62dfd25 --- /dev/null +++ b/crypto/rsa/tests/keys_tests.rs @@ -0,0 +1,310 @@ +//! 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::{KeyDecodingError, SignatureError}; +use bouncycastle_core::traits::{PrivateKey, PublicKey}; +use bouncycastle_rsa::keys::{ + RsaPrivateComponents, RsaPrivateKey, RsaPublicComponents, RsaPublicKey, +}; +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; + +const P: [u64; 16] = [ + 0xfec673c1b07d4997, 0x98c9e3737faecc8b, 0x01369d6bebcfd19b, 0x8aadc1799d493a6e, + 0x958ca74fe2a455a1, 0x686e62c9e375661d, 0xbf73814b7bf6fe14, 0x791ffe2d364719e4, + 0xc82e25af581825a1, 0x716d239de20732c7, 0xdb517e266b0c15bc, 0xe92c721464fa1e50, + 0x683e7fcc3898a002, 0xc7f69cb8c57e630f, 0xc467ab3a006acdf7, 0xe189725eddf8ccb3, +]; +const Q: [u64; 16] = [ + 0x7b4cf8c928cc535f, 0x59f055409b91aa89, 0xcd0ba689661c56d5, 0xe4659bfb595039f4, + 0x751842ab04e21054, 0xe2c2655760ebb5fc, 0xb2f71094e48dc76b, 0x2efed995e680919d, + 0x83c35ffcfdb9ee9d, 0xfe4a5fdb9f28a01b, 0x0ebf4a61e23c7524, 0x8cc355a69e45d7e6, + 0x9589828fca436940, 0x4cd1bfe875cddd70, 0x203e0d5e8d4d3acb, 0x86278c27281306ec, +]; +const D_P: [u64; 16] = [ + 0xa7c48ae44e99dd99, 0xa6794425077c6c01, 0x0f7f8dfabf278380, 0xb481c3d6cf359f60, + 0xa5b5efbc5d9f744a, 0x91b95de874b741a1, 0xea3152a3da97ddf5, 0xe180bda330e9eba0, + 0xbcbfcc51e73a7a34, 0x019d0405e258c3c0, 0x0b08c52c187e3667, 0x84a723999981f7c1, + 0x5e50dc3287b126ff, 0xd0204fd4674f4ac6, 0x6e786ef11d0686f6, 0xa82c39200c1c4d67, +]; +const D_Q: [u64; 16] = [ + 0x0bc1fcecb5c853bf, 0x2000c1caf24e96d2, 0xb423419c07e0736a, 0x90bcb6fb03d68029, + 0xd811d2e24994ff2e, 0x5a89a6b7c7c83737, 0xbdea803dc4157f87, 0xffe93a09240b9b65, + 0xe6f584c8dc80c30a, 0x5e66076e22c91c3c, 0xb41221e6b67af91b, 0x2e3d8c36b1d9d161, + 0x7b1309bb3857cb1f, 0xee8de5186c920235, 0x5e4785a534bec7a3, 0x85883dd007ea907c, +]; +const Q_INV: [u64; 16] = [ + 0xf1be36246c217ae1, 0x079e038ceb7506d7, 0x2021f982bc5f6713, 0x55fa8fdd926a4d0f, + 0xb927b5edab1a24b8, 0xc2a1d37632cfb70e, 0x9ef39b4a3f144e8a, 0x70efa5974ed43d2f, + 0x6ea50741414ce321, 0x7df35889e34d4f38, 0x859106459f51850b, 0xd59e422a92f4a7a2, + 0x0c1e16e70fcbe362, 0xcf95cadb6a1f450d, 0x106a4e948e405012, 0x95a3415bfb9b5ff6, +]; +const 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, +]; + +#[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) + .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), + 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), + 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), + 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), + 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), + 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() { + assert!(matches!( + RsaPublicComponents::::new(&N, 65536), + Err(SignatureError::DecodingError(_)) + )); +} + +#[test] +fn public_key_rejects_exponent_below_three() { + assert!(matches!( + RsaPublicComponents::::new(&N, 1), + Err(SignatureError::DecodingError(_)) + )); +} + +#[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() { + let pk = RsaPublicComponents::::new(&N, 0x10001).unwrap().into_key::(); + let bytes: [u8; 260] = pk.encode(); + let decoded = RsaPublicKey::::from_bytes(&bytes).expect("must decode"); + assert_eq!(decoded, pk); +} + +/// `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. +#[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..], [0x00, 0x01, 0x00, 0x01]); + + let mut out = [0xaau8; 260]; + assert_eq!(pk.encode_out(&mut out), 260); + 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; 260] = 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[..259]), 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) + .unwrap() + .into_key::(); + let bytes: [u8; 640] = sk.encode(); + let decoded = RsaPrivateKey::::from_bytes(&bytes).expect("must decode"); + assert_eq!(decoded, sk); +} + +/// `PrivateKey`'s `p || q || dP || dQ || qInv` layout, each field 128 bytes big-endian. +#[test] +fn private_key_encode_layout_is_five_big_endian_fields() { + let sk = RsaPrivateComponents::::from_crt_components(&P, &Q, &D_P, &D_Q, &Q_INV) + .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"); + } + + let mut out = [0xaau8; 640]; + assert_eq!(sk.encode_out(&mut out), 640); + 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) + .unwrap() + .into_key::(); + let mut bytes: [u8; 640] = 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) + .unwrap() + .into_key::(); + let bytes = sk.encode(); + assert!(matches!(RsaPrivateKey::::from_bytes(&bytes[..639]), Err(KeyDecodingError(_)))); + let mut too_long = bytes.to_vec(); + too_long.push(0); + assert!(matches!(RsaPrivateKey::::from_bytes(&too_long), Err(KeyDecodingError(_)))); +} + +/// The CRT range checks run through the size's own forwarders: at every signing size a `dP` +/// not below `p` and a `qInv` not below `p` are refused (no primality check, so tiny odd +/// values 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 mut small = ::HalfLimbs::ZEROED; + small.as_mut()[0] = 3; + assert!(RsaPrivateComponents::::from_crt_components(&p, &q, &small, &small, &small).is_ok()); + assert!(matches!( + RsaPrivateComponents::::from_crt_components(&p, &q, &p, &small, &small), + Err(SignatureError::DecodingError(_)) + )); + assert!(matches!( + RsaPrivateComponents::::from_crt_components(&p, &q, &small, &q, &small), + Err(SignatureError::DecodingError(_)) + )); + assert!(matches!( + RsaPrivateComponents::::from_crt_components(&p, &q, &small, &small, &p), + Err(SignatureError::DecodingError(_)) + )); +} + +#[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::(); +} + +/// 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) + .unwrap() + .into_key::(); + let shown = format!("{sk:?}"); + assert!(shown.starts_with("RsaPrivateKey { algorithm: \"RSASSA-PSS-SHA256\", components: ")); + let mut q_inv_other = Q_INV; + q_inv_other[0] ^= 1; + let sk_other = + RsaPrivateComponents::::from_crt_components(&P, &Q, &D_P, &D_Q, &q_inv_other) + .unwrap() + .into_key::(); + assert_eq!(sk, sk.clone()); + assert_ne!(sk, sk_other); +} diff --git a/crypto/rsa/tests/modexp_tests.rs b/crypto/rsa/tests/modexp_tests.rs new file mode 100644 index 00000000..ec659170 --- /dev/null +++ b/crypto/rsa/tests/modexp_tests.rs @@ -0,0 +1,210 @@ +//! 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::modexp::{ + MontgomeryContext, mod_pow, mont_n_prime, mul_mod, reduce_wide, sub_mod, +}; + +/// `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]; + + let ctx = MontgomeryContext::<1>::new(&n).expect("3233 is odd"); + 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]; + + let ctx = MontgomeryContext::<1>::new(&n).expect("modulus is odd"); + 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]; + + let ctx = MontgomeryContext::<2>::new(&n).expect("modulus is odd"); + 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]; + + let ctx = MontgomeryContext::<4>::new(&n).expect("modulus is odd"); + 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]; + + let ctx = MontgomeryContext::<2>::new(&n).expect("modulus is odd"); + + // 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, + ]; + + let ctx = MontgomeryContext::<32>::new(&n).expect("modulus is odd"); + assert_eq!(mod_pow::<32, 64, 65>(&base, &exp, &ctx), expected); +} + +/// An even modulus is never valid for Montgomery reduction; RSA moduli are always odd, so this +/// is purely a defensive boundary check. +#[test] +fn even_modulus_is_rejected() { + let n: [u64; 1] = [4]; + assert!(MontgomeryContext::<1>::new(&n).is_none()); +} + +/// `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]; + + let ctx = MontgomeryContext::<2>::new(&n).expect("modulus is odd"); + assert_eq!(mul_mod::<2, 4, 5>(&a, &b, &ctx), expected); +} diff --git a/crypto/rsa/tests/rsa_1024_tests.rs b/crypto/rsa/tests/rsa_1024_tests.rs new file mode 100644 index 00000000..85a9b890 --- /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::signature_key::OneShotVerifyingKey; +use bouncycastle_core::traits::PublicKey; +use bouncycastle_hex::decode as hex_decode; +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 = + u32::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 = + u32::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 = + u32::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 00000000..8cb8d815 --- /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::signature_key::OneShotVerifyingKey; +use bouncycastle_core::traits::PublicKey; +use bouncycastle_hex::decode as hex_decode; +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 = + u32::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 = + u32::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 = + u32::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 00000000..2fc1fa1c --- /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::signature_key::{DeterministicOneShotSigningKey, OneShotVerifyingKey}; +use bouncycastle_core_test_framework::signature::TestFrameworkSignature; +use bouncycastle_hex::decode as hex_decode; +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) + .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 = u32::from_str_radix(group["publicKey"]["publicExponent"].as_str().unwrap(), 16) + .expect("publicExponent fits in u32 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::new(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); +} 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 00000000..e9642868 --- /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::signature_key::{ + DeterministicOneShotSigningKey, DeterministicSigningKey, OneShotVerifyingKey, +}; +use bouncycastle_core::traits::{HashOneShot, SignatureSigner}; +use bouncycastle_core_test_framework::signature::{ + TestFrameworkSignature, TestFrameworkSignatureKeys, +}; +use bouncycastle_hex::decode as hex_decode; +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) + .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::new(false).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 = u32::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 00000000..bb17a0db --- /dev/null +++ b/crypto/rsa/tests/rsa_2048_pss_params_tests.rs @@ -0,0 +1,267 @@ +//! 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::security_strength::SecurityStrength; +use bouncycastle_core::signature_key::{ + DeterministicOneShotSigningKey, DeterministicSigningKey, OneShotSigningKey, + OneShotVerifyingKey, SigningKey, +}; +use bouncycastle_core::traits::{Algorithm, AlgorithmInfo, SignatureSigner, XOF}; +use bouncycastle_hex::decode as hex_decode; +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_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 = u32::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), + ); +} + +#[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).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(); +} 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 00000000..cc4f72b9 --- /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::signature_key::{OneShotSigningKey, OneShotVerifyingKey, SigningKey}; +use bouncycastle_core::traits::SignatureSigner; +use bouncycastle_core_test_framework::signature::TestFrameworkSignature; +use bouncycastle_hex::decode as hex_decode; +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) + .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 = u32::from_str_radix(group["publicKey"]["publicExponent"].as_str().unwrap(), 16) + .expect("publicExponent fits in u32 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::new(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 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 00000000..4a1ec48b --- /dev/null +++ b/crypto/rsa/tests/rsa_2048_pss_shake128_tests.rs @@ -0,0 +1,311 @@ +//! 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::signature_key::{ + OneShotSigningKey, OneShotVerifyingKey, SigningKey, VerifyingKey, +}; +use bouncycastle_core::traits::RNG; +use bouncycastle_core::traits::{HashOneShot, SignatureSigner, SignatureVerifier}; +use bouncycastle_core_test_framework::signature::TestFrameworkSignature; +use bouncycastle_hex::decode as hex_decode; +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) + .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 = u32::from_str_radix(group["publicKey"]["publicExponent"].as_str().unwrap(), 16) + .expect("publicExponent fits in u32 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::new(false) + .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(&mut self, len: usize) -> Result, bouncycastle_core::errors::RNGError> { + Ok(vec![0x42u8; len]) + } + 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 00000000..5924e35f --- /dev/null +++ b/crypto/rsa/tests/rsa_2048_pss_tests.rs @@ -0,0 +1,310 @@ +//! 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::signature_key::{ + OneShotSigningKey, OneShotVerifyingKey, SigningKey, VerifyingKey, +}; +use bouncycastle_core::traits::RNG; +use bouncycastle_core::traits::{HashOneShot, SignatureSigner, SignatureVerifier}; +use bouncycastle_core_test_framework::signature::TestFrameworkSignature; +use bouncycastle_hex::decode as hex_decode; +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) + .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 = u32::from_str_radix(group["publicKey"]["publicExponent"].as_str().unwrap(), 16) + .expect("publicExponent fits in u32 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::new(false) + .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(&mut self, len: usize) -> Result, bouncycastle_core::errors::RNGError> { + Ok(vec![0x42u8; len]) + } + 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 00000000..482ecb6a --- /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::signature_key::{OneShotSigningKey, OneShotVerifyingKey, SigningKey}; +use bouncycastle_core::traits::SignatureSigner; +use bouncycastle_core_test_framework::signature::TestFrameworkSignature; +use bouncycastle_hex::decode as hex_decode; +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) + .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 = u32::from_str_radix(group["publicKey"]["publicExponent"].as_str().unwrap(), 16) + .expect("publicExponent fits in u32 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::new(false) + .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 00000000..006163c3 --- /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::signature_key::{ + DeterministicOneShotSigningKey, OneShotSigningKey, OneShotVerifyingKey, SigningKey, +}; +use bouncycastle_core::traits::SignatureSigner; +use bouncycastle_core_test_framework::signature::{ + TestFrameworkSignature, TestFrameworkSignatureKeys, +}; +use bouncycastle_hex::decode as hex_decode; +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) + .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 = u32::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 = u32::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::new(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); + 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::new(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, + ); + 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 00000000..2708fbe3 --- /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::signature_key::{OneShotSigningKey, OneShotVerifyingKey, SigningKey}; +use bouncycastle_core::traits::SignatureSigner; +use bouncycastle_hex::decode as hex_decode; +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) + .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 = u32::from_str_radix(group["publicKey"]["publicExponent"].as_str().unwrap(), 16) + .expect("publicExponent fits in u32 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 00000000..bc749b8f --- /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::signature_key::{ + DeterministicOneShotSigningKey, DeterministicSigningKey, OneShotSigningKey, + OneShotVerifyingKey, SigningKey, +}; +use bouncycastle_core::traits::SignatureSigner; +use bouncycastle_core_test_framework::signature::{ + TestFrameworkSignature, TestFrameworkSignatureKeys, +}; +use bouncycastle_hex::decode as hex_decode; +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) + .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 = u32::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 = u32::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::new(false).test_deterministic_signature::, RsaPrivateKey, SIG_LEN>( + || fixed_keypair().map(|(pk, sk)| (pk.into_key::(), sk.into_key::())), false); + TestFrameworkSignature::new(false) + .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 00000000..55060cb3 --- /dev/null +++ b/crypto/rsa/tests/rsa_8192_tests.rs @@ -0,0 +1,482 @@ +//! 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, sampled.** `rsa_signature_8192_sha{256,384,512}_test.json` +//! exist (verify-only, with their own unrelated key) and are used here, but not exhaustively: +//! each has on the order of 260 vectors, and at `L = 128` a single verify costs roughly 19x +//! what one costs at RSA-3072 (`(128/48)^3`), which would make a full run of three such files +//! alone take on the order of an hour. Every *distinct* `(result, flags)` combination present +//! in each file is still exercised at least once (deduplicated below), so every failure mode +//! Wycheproof encodes for this hash is checked -- just not every repetition of it. + +use bouncycastle_core::errors::SignatureError; +use bouncycastle_core::signature_key::{ + DeterministicOneShotSigningKey, DeterministicSigningKey, OneShotSigningKey, + OneShotVerifyingKey, SigningKey, +}; +use bouncycastle_core::traits::SignatureSigner; +use bouncycastle_core_test_framework::signature::{ + TestFrameworkSignature, TestFrameworkSignatureKeys, +}; +use bouncycastle_hex::decode as hex_decode; +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::collections::HashSet; +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) + .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"); +} + +/// Every distinct `(result, flags)` combination in `filename`'s (single) test group, in file +/// order -- see this file's module docs for why this is a deliberate sample, not the full vector +/// set. +fn distinct_cases(tests: &[Value]) -> Vec<&Value> { + let mut seen = HashSet::new(); + let mut out = Vec::new(); + for test in tests { + let mut flags: Vec<&str> = + test["flags"].as_array().unwrap().iter().map(|f| f.as_str().unwrap()).collect(); + flags.sort_unstable(); + let key = (test["result"].as_str().unwrap().to_string(), flags); + if seen.insert(key) { + out.push(test); + } + } + out +} + +fn run_sampled_pkcs1_v1_5_verify_vectors( + filename: &str, + verify: impl Fn(&RsaPublicComponents, &[u8], &[u8; 1024]) -> bool, + expected_sha: &str, +) { + let doc: Value = serde_json::from_str(&get_test_data(filename)).expect("valid JSON"); + let group = &doc["testGroups"][0]; + assert_eq!(group["sha"], expected_sha); + let n: [u64; 128] = limbs_from_hex(group["publicKey"]["modulus"].as_str().unwrap()); + let e = + u32::from_str_radix(group["publicKey"]["publicExponent"].as_str().unwrap(), 16).unwrap(); + let pk = RsaPublicComponents::::new(&n, e).unwrap(); + + let tests = group["tests"].as_array().unwrap(); + let sample = distinct_cases(tests); + assert!(sample.len() >= 10, "expected a rich sample of distinct cases, got {}", sample.len()); + + for test in sample { + 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"); + continue; + }; + let verified = verify(&pk, &msg, &sig); + match test["result"].as_str().unwrap() { + "valid" => assert!(verified, "tcId {tc_id}: expected valid, got invalid"), + "invalid" => assert!(!verified, "tcId {tc_id}: expected invalid, got valid"), + "acceptable" => { + assert_eq!(flags, vec!["MissingNull"], "tcId {tc_id}: unreviewed acceptable"); + assert!(verified, "tcId {tc_id}: MissingNull must be accepted"); + } + other => panic!("tcId {tc_id}: unknown result {other:?}"), + } + } +} + +#[test] +fn rsa_signature_8192_sha256_wycheproof_vectors_sampled() { + run_sampled_pkcs1_v1_5_verify_vectors( + "rsa_signature_8192_sha256_test.json", + |pk, msg, sig| pk.key::().verify(msg, None, sig).is_ok(), + "SHA-256", + ); +} + +#[test] +fn rsa_signature_8192_sha384_wycheproof_vectors_sampled() { + run_sampled_pkcs1_v1_5_verify_vectors( + "rsa_signature_8192_sha384_test.json", + |pk, msg, sig| pk.key::().verify(msg, None, sig).is_ok(), + "SHA-384", + ); +} + +#[test] +fn rsa_signature_8192_sha512_wycheproof_vectors_sampled() { + run_sampled_pkcs1_v1_5_verify_vectors( + "rsa_signature_8192_sha512_test.json", + |pk, msg, sig| pk.key::().verify(msg, None, sig).is_ok(), + "SHA-512", + ); +} + +// ---- 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::new(false).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 00000000..05a4e4ce --- /dev/null +++ b/crypto/rsa/tests/rsaes_oaep_tests.rs @@ -0,0 +1,560 @@ +//! 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::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_hex::decode as hex_decode; +use bouncycastle_rng::{FixedSeedRNG, 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_sha1::SHA1; +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`, 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", +); +/// Its public key, `n || e`. +#[allow(dead_code)] +const KAT_PK_HEX: &str = concat!( + "a2b451a07d0aa5f96e455671513550514a8a5b462ebef717094fa1fee82224e6", + "37f9746d3f7cafd31878d80325b6ef5a1700f65903b469429e89d6eac8845097", + "b5ab393189db92512ed8a7711a1253facd20f79c15e8247f3d3e42e46e48c98e", + "254a2fe9765313a03eff8f17e1a029397a1fa26a8dce26f490ed81299615d981", + "4c22da610428e09c7d9658594266f5c021d0fceca08d945a12be82de4d1ece6b", + "4c03145b5d3495d4ed5411eb878daf05fd7afc3e09ada0f1126422f590975a19", + "69816f48698bcbba1b4d9cae79d460d8f9f85e7975005d9bc22c4e5ac0f7c1a4", + "5d12569a62807d3b9a02e5a530e773066f453d1f5b4c2e9cf7820283f742b9d5", + "00010001", +); +/// 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. + let key = &group["privateKey"]; + 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)); + } + 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 e = u32::from_str_radix(key["publicExponent"].as_str().unwrap(), 16).unwrap(); + 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(&mut self, _: usize) -> Result, RNGError> { + 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 00000000..ab49ad21 --- /dev/null +++ b/crypto/rsa/tests/rsassa_worker_tests.rs @@ -0,0 +1,156 @@ +//! The signature workers name their algorithm, and the random-salt `sign_from_hash` entry +//! points of the PSS schemes sign what `verify_from_hash` accepts. + +use bouncycastle_core::signature_key::{DeterministicSigningKey, SigningKey, VerifyingKey}; +use bouncycastle_core::traits::{AlgorithmInfo, HashOneShot}; +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).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(); +} diff --git a/crypto/rsa/tests/rsasve_hkdf_tests.rs b/crypto/rsa/tests/rsasve_hkdf_tests.rs new file mode 100644 index 00000000..2f8fcee0 --- /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)?; + 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 00000000..b3a79c95 --- /dev/null +++ b/crypto/rsa/tests/rsasve_tests.rs @@ -0,0 +1,600 @@ +//! 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. 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::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_hex::decode as hex_decode; +use bouncycastle_rng::DefaultRNG; +use bouncycastle_rng::FixedSeedRNG; +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()), + ) + .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 + 4); + assert_eq!(SK_LEN, 5 * $bits / 16); + } + + #[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); + } + + #[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 [3u32, 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 - 4..].copy_from_slice(&3u32.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()), + ), + 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), + 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(_)))); + } + } + }; +} + +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 sk = RSA2048KEMPrivateKey::from_crt_components( + &limbs(s("iutP")), + &limbs(s("iutQ")), + &limbs(s("iutDmp1")), + &limbs(s("iutDmq1")), + &limbs(s("iutIqmp")), + ) + .unwrap(); + let e = u32::from_str_radix(s("iutE"), 16).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 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"))), + ) + .unwrap(); + let e = u32::from_str_radix(s(&format!("{who}E")), 16).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. +macro_rules! acvp_rsadp { + ($name:ident, $size:ident, $marker:ident, $bits:literal) => { + #[test] + fn $name() { + use bouncycastle_rsa::$size::CT_LEN; + type SK = bouncycastle_rsa::rsasve::RsaKEMPrivateKey; + 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) = (0, 0); + for t in group["tests"].as_array().unwrap() { + let s = |k: &str| t[k].as_str().unwrap(); + let sk = SK::from_crt_components( + &limbs(s("p")), + &limbs(s("q")), + &limbs(s("dmp1")), + &limbs(s("dmq1")), + &limbs(s("iqmp")), + ) + .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"] + ); + passed += 1; + } else { + assert!( + matches!(sk.decaps(&ct, ()), Err(KEMError::DecapsulationFailed)), + "tcId {}", + t["tcId"] + ); + failed += 1; + } + } + assert_eq!(passed + failed, 15); + assert!(failed > 0, "the group's out-of-range cases must have been exercised"); + } + }; +} + +acvp_rsadp!(acvp_rsadp_crt_2048, rsa_2048, RSA2048, 2048); +acvp_rsadp!(acvp_rsadp_crt_3072, rsa_3072, RSA3072, 3072); +acvp_rsadp!(acvp_rsadp_crt_4096, rsa_4096, RSA4096, 4096); + +/// `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/sha1/Cargo.toml b/crypto/sha1/Cargo.toml new file mode 100644 index 00000000..c42125eb --- /dev/null +++ b/crypto/sha1/Cargo.toml @@ -0,0 +1,18 @@ +[package] +name = "bouncycastle-sha1" +version.workspace = true +edition.workspace = true + +[dependencies] +bouncycastle-core.workspace = true +bouncycastle-utils.workspace = true + +[dev-dependencies] +criterion.workspace = true +bouncycastle-core-test-framework.workspace = true +bouncycastle-hex.workspace = true +bouncycastle-rng.workspace = true + +[[bench]] +name = "sha1_benches" +harness = false diff --git a/crypto/sha1/benches/sha1_benches.rs b/crypto/sha1/benches/sha1_benches.rs new file mode 100644 index 00000000..2b8de55b --- /dev/null +++ b/crypto/sha1/benches/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_rng as rng; +use bouncycastle_sha1::SHA1; + +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/sha1/src/lib.rs b/crypto/sha1/src/lib.rs new file mode 100644 index 00000000..771e121a --- /dev/null +++ b/crypto/sha1/src/lib.rs @@ -0,0 +1,123 @@ +//! 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_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_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, which the library's signature schemes and +//! strength checks will refuse. +//! * 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. + +// todo #![no_std] +// waiting for the no_std refactor that removes the `-> Vec` from core::traits::Hash + +#![forbid(unsafe_code)] +#![forbid(missing_docs)] + +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 factories and CLI. +pub const SHA1_NAME: &str = "SHA1"; + +/// SHA-1 is credited with no security strength: see the crate'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/sha1/src/sha1.rs b/crypto/sha1/src/sha1.rs new file mode 100644 index 00000000..381c2f61 --- /dev/null +++ b/crypto/sha1/src/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 crate 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/sha1/tests/sha1_bc-test-data.rs b/crypto/sha1/tests/sha1_bc-test-data.rs new file mode 100644 index 00000000..8b25cefc --- /dev/null +++ b/crypto/sha1/tests/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::traits::HashOneShot; +use bouncycastle_core_test_framework::test_data_loaders::bc_test_data; +use bouncycastle_hex as hex; +use bouncycastle_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/sha1/tests/sha1_tests.rs b/crypto/sha1/tests/sha1_tests.rs new file mode 100644 index 00000000..6c5d91a2 --- /dev/null +++ b/crypto/sha1/tests/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::security_strength::SecurityStrength; +use bouncycastle_core::traits::{ + Algorithm, AlgorithmInfo, AlgorithmOID, Hash, HashAlgParams, HashOneShot, +}; +use bouncycastle_core_test_framework::hash::TestFrameworkHash; +use bouncycastle_hex as hex; +use bouncycastle_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/utils/src/const_str.rs b/crypto/utils/src/const_str.rs index 1603d448..ad4f9d93 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 61398290..a534fb96 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 00000000..d8d8dd24 --- /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/cli_ccm_cfb_examples.sh b/dev_scripts/cli_ccm_cfb_examples.sh new file mode 100755 index 00000000..08348e65 --- /dev/null +++ b/dev_scripts/cli_ccm_cfb_examples.sh @@ -0,0 +1,200 @@ +#!/usr/bin/env bash +# Builds the `bc-rust` CLI and runs it through AES-CCM, AES-CFB128 and AES-CFB8 examples. +# +# Each example is checked, not just shown: CCM against SP 800-38C Appendix C Examples 1 and 2 +# (nonce supplied, so the output is a known answer) and the round trips, AAD binding and tamper +# detection the subcommand help promises; CFB128 and CFB8 against SP 800-38A Appendix F.3 with +# the IV supplied through `--iv`, and with the default generated IV for round trip, output +# length, pipeline composition and the tamper-propagation behaviour each mode's help describes. +# +# Usage: ./dev_scripts/cli_ccm_cfb_examples.sh [--release] +# Exit status is non-zero if any check fails. Needs `xxd` and `cmp`. + +set -u +cd "$(dirname "$0")/.." + +PROFILE=debug +CARGO_FLAGS=() +if [ "${1:-}" = "--release" ]; then + PROFILE=release + CARGO_FLAGS=(--release) +fi + +export PATH="$HOME/.cargo/bin:$PATH" +echo "## building bc-rust ($PROFILE)" +cargo build -p cli "${CARGO_FLAGS[@]}" || exit 1 +BC="./target/$PROFILE/bc-rust" + +WORK=$(mktemp -d) +trap 'rm -rf "$WORK"' EXIT + +FAILURES=0 +pass() { printf ' ok %s\n' "$1"; } +fail() { printf ' FAIL %s\n' "$1"; FAILURES=$((FAILURES + 1)); } +check() { # check ; passes if the command exits 0 + local desc=$1; shift + if "$@"; then pass "$desc"; else fail "$desc"; fi +} +hex() { xxd -p | tr -d '\n'; } +unhex() { xxd -r -p; } + +# A throwaway key for the round-trip examples. Never put a real key on a command line; the +# commands take `--key-file` for that, and the CFB examples below use it. +KEY=000102030405060708090a0b0c0d0e0f +KEY_FILE="$WORK/key.bin" +echo -n "$KEY" | unhex > "$KEY_FILE" + +############################################################################################### +echo +echo "## AES-128-CCM: known answers from SP 800-38C Appendix C" +echo "# (nonce is supplied, not generated, so the output is reproducible)" + +# C.1 Example 1: Klen = 128, Tlen = 32, Nlen = 56, Alen = 64, Plen = 32. +K1=404142434445464748494a4b4c4d4e4f +N1=10111213141516 +A1=0001020304050607 +P1=20212223 +C1=7162015b4dac255d # ciphertext || 4-byte tag +out=$(echo -n "$P1" | unhex | $BC aes128-ccm -d encrypt --key $K1 --nonce $N1 --aad $A1 --tag-len 4 -x) +check "Example 1 encrypt: $out" [ "$out" = "$C1" ] +out=$(echo -n "$C1" | unhex | $BC aes128-ccm -d decrypt --key $K1 --nonce $N1 --aad $A1 --tag-len 4 -x) +check "Example 1 decrypt: $out" [ "$out" = "$P1" ] + +# C.2 Example 2: Klen = 128, Tlen = 48, Nlen = 64, Alen = 128, Plen = 128. +N2=1011121314151617 +A2=000102030405060708090a0b0c0d0e0f +P2=202122232425262728292a2b2c2d2e2f +C2=d2a1f0e051ea5f62081a7792073d593d1fc64fbfaccd # ciphertext || 6-byte tag +out=$(echo -n "$P2" | unhex | $BC aes128-ccm -d encrypt --key $K1 --nonce $N2 --aad $A2 --tag-len 6 -x) +check "Example 2 encrypt: $out" [ "$out" = "$C2" ] +out=$(echo -n "$C2" | unhex | $BC aes128-ccm -d decrypt --key $K1 --nonce $N2 --aad $A2 --tag-len 6 -x) +check "Example 2 decrypt: $out" [ "$out" = "$P2" ] + +echo +echo "## AES-128-CCM: round trip, AAD binding, tamper detection (12-byte nonce, 16-byte tag)" +NONCE=000000000000000000000001 # a message counter; MUST be unique per key +MSG="$WORK/msg.txt" +printf 'The quick brown fox jumps over the lazy dog. %s\n' "$(date -u +%FT%TZ)" > "$MSG" +AAD_FILE="$WORK/aad.bin" +printf 'header: v1, msg 1' > "$AAD_FILE" + +$BC aes128-ccm -d encrypt -k "$KEY_FILE" --nonce $NONCE --aad-file "$AAD_FILE" < "$MSG" > "$WORK/msg.ccm" +check "ciphertext is input + 16 tag bytes ($(stat -c %s "$WORK/msg.ccm") = $(stat -c %s "$MSG") + 16)" \ + [ "$(stat -c %s "$WORK/msg.ccm")" -eq $(( $(stat -c %s "$MSG") + 16 )) ] + +$BC aes128-ccm -d decrypt -k "$KEY_FILE" --nonce $NONCE --aad-file "$AAD_FILE" < "$WORK/msg.ccm" > "$WORK/msg.out" +check "decrypt round-trips" cmp -s "$MSG" "$WORK/msg.out" + +# AAD is authenticated: a different AAD must fail, and must write nothing. +if $BC aes128-ccm -d decrypt -k "$KEY_FILE" --nonce $NONCE --aad 00 < "$WORK/msg.ccm" > "$WORK/bad.out" 2>/dev/null; then + fail "decrypt with the wrong AAD was accepted" +else + check "decrypt with the wrong AAD fails and writes no plaintext" [ ! -s "$WORK/bad.out" ] +fi + +# Tamper: flip one bit of the first ciphertext byte. +python3 -c " +import sys; d = bytearray(open(sys.argv[1], 'rb').read()); d[0] ^= 1; open(sys.argv[2], 'wb').write(d) +" "$WORK/msg.ccm" "$WORK/msg.tampered" +if $BC aes128-ccm -d decrypt -k "$KEY_FILE" --nonce $NONCE --aad-file "$AAD_FILE" < "$WORK/msg.tampered" > "$WORK/bad.out" 2>/dev/null; then + fail "tampered ciphertext was accepted" +else + check "tampered ciphertext fails and writes no plaintext" [ ! -s "$WORK/bad.out" ] +fi + +# Shorter tag, 7-byte nonce (the largest payload limit), encrypt | decrypt in one pipeline. +out=$($BC aes128-ccm -d encrypt -k "$KEY_FILE" --nonce 01020304050607 --tag-len 8 < "$MSG" \ + | $BC aes128-ccm -d decrypt -k "$KEY_FILE" --nonce 01020304050607 --tag-len 8) +check "7-byte nonce, 8-byte tag, encrypt | decrypt pipeline round-trips" [ "$out" = "$(cat "$MSG")" ] + +############################################################################################### +# SP 800-38A Appendix F.3, AES-128: the same key and IV for both modes; CFB8 uses the first 18 +# plaintext bytes (F.3.7, 18 segments), CFB128 all 64 (F.3.13, 4 segments). +K38A=2b7e151628aed2a6abf7158809cf4f3c +IV38A=000102030405060708090a0b0c0d0e0f +P38A=6bc1bee22e409f96e93d7e117393172aae2d8a571e03ac9c9eb76fac45af8e5130c81c46a35ce411e5fbc1191a0a52eff69f2445df4f9b17ad2b417be66c3710 +C_CFB=3b3fd92eb72dad20333449f8e83cfb4ac8a64537a0b3a93fcde3cdad9f1ce58b26751f67a3cbb140b1808cf187a4f4dfc04b05357c5d1c0eeac4c66f9ff7f2e6 +P_CFB8=${P38A:0:36} +C_CFB8=3b79424c9c0dd436bace9e0ed4586a4f32b9 + +for MODE in cfb cfb8; do + CMD="aes128-$MODE" + if [ "$MODE" = cfb ]; then P=$P38A; C=$C_CFB; SEC="F.3.13 / F.3.14"; else P=$P_CFB8; C=$C_CFB8; SEC="F.3.7 / F.3.8"; fi + + echo + echo "## AES-128-${MODE^^}: known answers from SP 800-38A Appendix $SEC, IV supplied with --iv" + echo "# (with --iv, encrypt writes only ciphertext and decrypt reads only ciphertext)" + out=$(echo -n "$P" | unhex | $BC $CMD -d encrypt --key $K38A --iv $IV38A -x) + check "encrypt: $out" [ "$out" = "$C" ] + out=$(echo -n "$C" | unhex | $BC $CMD -d decrypt --key $K38A --iv $IV38A -x) + check "decrypt: $out" [ "$out" = "$P" ] + + # The same IV from a file of raw bytes, and --iv on both ends of a pipeline. + echo -n "$IV38A" | unhex > "$WORK/iv.bin" + out=$(echo -n "$P" | unhex | $BC $CMD -d encrypt --key $K38A --iv-file "$WORK/iv.bin" -x) + check "encrypt with --iv-file gives the same answer" [ "$out" = "$C" ] + out=$($BC $CMD -d encrypt -k "$KEY_FILE" --iv $IV38A < "$MSG" | $BC $CMD -d decrypt -k "$KEY_FILE" --iv $IV38A) + check "encrypt --iv | decrypt --iv round-trips, ciphertext only in the pipe" [ "$out" = "$(cat "$MSG")" ] + check "ciphertext with --iv is exactly the input length" \ + [ "$($BC $CMD -d encrypt -k "$KEY_FILE" --iv $IV38A < "$MSG" | wc -c)" -eq "$(stat -c %s "$MSG")" ] + + # A wrong-length IV is refused before anything is read. + if echo -n 00 | $BC $CMD -d encrypt --key $K38A --iv 0001 > /dev/null 2>&1; then + fail "a 2-byte IV was accepted" + else + pass "a 2-byte IV is refused" + fi + + echo + echo "## AES-128-${MODE^^}: default, IV generated and prepended (first 16 bytes of output)" + + $BC $CMD -d encrypt -k "$KEY_FILE" < "$MSG" > "$WORK/msg.$MODE" + check "ciphertext is 16-byte IV + input ($(stat -c %s "$WORK/msg.$MODE") = 16 + $(stat -c %s "$MSG"))" \ + [ "$(stat -c %s "$WORK/msg.$MODE")" -eq $(( 16 + $(stat -c %s "$MSG") )) ] + + $BC $CMD -d decrypt -k "$KEY_FILE" < "$WORK/msg.$MODE" > "$WORK/msg.out" + check "decrypt round-trips" cmp -s "$MSG" "$WORK/msg.out" + + # Two encryptions of the same message differ: the IV is fresh each time. + $BC $CMD -d encrypt -k "$KEY_FILE" < "$MSG" > "$WORK/msg2.$MODE" + check "a second encryption has a different IV and ciphertext" [ "$(hex < "$WORK/msg.$MODE")" != "$(hex < "$WORK/msg2.$MODE")" ] + + # Pipeline: encrypt | decrypt with no file in between, any length (here 1 byte and 100 KiB). + out=$(printf 'x' | $BC $CMD -d encrypt -k "$KEY_FILE" | $BC $CMD -d decrypt -k "$KEY_FILE") + check "1-byte message through an encrypt | decrypt pipeline" [ "$out" = "x" ] + head -c 102400 /dev/urandom > "$WORK/big.bin" + $BC $CMD -d encrypt -k "$KEY_FILE" < "$WORK/big.bin" | $BC $CMD -d decrypt -k "$KEY_FILE" > "$WORK/big.out" + check "100 KiB through an encrypt | decrypt pipeline" cmp -s "$WORK/big.bin" "$WORK/big.out" + + # No integrity: a flipped ciphertext bit decrypts "successfully" to corrupted plaintext. + # CFB128: the same bit of the same block flips and the NEXT block is garbled, then it resyncs. + # CFB8: the same bit of the same byte flips and the next 16 bytes are garbled, then it resyncs. + # Flip bit 0 of plaintext byte 20 (ciphertext byte 16 + 20). + python3 -c " +import sys; d = bytearray(open(sys.argv[1], 'rb').read()); d[16 + 20] ^= 1; open(sys.argv[2], 'wb').write(d) +" "$WORK/msg.$MODE" "$WORK/msg.$MODE.tampered" + $BC $CMD -d decrypt -k "$KEY_FILE" < "$WORK/msg.$MODE.tampered" > "$WORK/tampered.out" + check "tampering is NOT detected (exit 0, output produced)" [ -s "$WORK/tampered.out" ] + if [ "$MODE" = cfb ]; then garble_from=32; garble_to=48; else garble_from=21; garble_to=37; fi + python3 - "$MSG" "$WORK/tampered.out" $garble_from $garble_to <<'EOF' +import sys +a = open(sys.argv[1], 'rb').read(); b = open(sys.argv[2], 'rb').read() +lo, hi = int(sys.argv[3]), int(sys.argv[4]) +diff = [i for i in range(len(a)) if a[i] != b[i]] +assert len(a) == len(b), "length changed" +assert diff[0] == 20 and a[20] ^ b[20] == 1, f"byte 20 should differ by exactly bit 0, got {diff[:3]}" +assert all(lo <= i < hi for i in diff[1:]), f"corruption outside [{lo},{hi}): {diff}" +assert all(a[i] == b[i] for i in range(hi, len(a))), "did not resynchronise" +print(f" ok flipped bit lands on plaintext byte 20, bytes {lo}..{hi-1} garbled, then resynchronised") +EOF + [ $? -eq 0 ] || fail "tamper propagation did not match the mode's description" +done + +############################################################################################### +echo +if [ $FAILURES -eq 0 ]; then + echo "all checks passed" +else + echo "$FAILURES check(s) FAILED" + exit 1 +fi diff --git a/dev_scripts/oaep_ct_harness/Cargo.toml b/dev_scripts/oaep_ct_harness/Cargo.toml new file mode 100644 index 00000000..6b0c6e2a --- /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 00000000..b8afd447 --- /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 00000000..d4db942a --- /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 00000000..13924bfb --- /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 00000000..5e404bb1 --- /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/mem_usage_benches/Cargo.toml b/mem_usage_benches/Cargo.toml index 38947e5b..e4822e28 100644 --- a/mem_usage_benches/Cargo.toml +++ b/mem_usage_benches/Cargo.toml @@ -43,6 +43,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" @@ -91,6 +95,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 00000000..b4a0ccba --- /dev/null +++ b/mem_usage_benches/src/bench_rsa_mem_usage.rs @@ -0,0 +1,515 @@ +//! 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", 132); + println!( + "size_of>: {} bytes", + size_of::>() + ); + println!("signature: {} bytes", 128); + + println!("\nRSA-1536 (verification only)"); + println!("public key on disk (n || e): {} bytes", 196); + println!( + "size_of>: {} bytes", + size_of::>() + ); + println!("signature: {} bytes", 192); + + println!("\nRSA-2048"); + println!("private key on disk (p||q||dP||dQ||qInv): {} bytes", 640); + println!( + "size_of>: {} bytes", + size_of::>() + ); + println!("public key on disk (n || e): {} bytes", 260); + 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", 256); + + println!("\nRSA-3072"); + println!("private key on disk (p||q||dP||dQ||qInv): {} bytes", 960); + println!( + "size_of>: {} bytes", + size_of::>() + ); + println!("public key on disk (n || e): {} bytes", 388); + 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", 384); + + println!("\nRSA-4096"); + println!("private key on disk (p||q||dP||dQ||qInv): {} bytes", 1280); + println!( + "size_of>: {} bytes", + size_of::>() + ); + println!("public key on disk (n || e): {} bytes", 516); + 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", 512); + + println!("\nRSA-8192"); + println!("private key on disk (p||q||dP||dQ||qInv): {} bytes", 2560); + println!( + "size_of>: {} bytes", + size_of::>() + ); + println!("public key on disk (n || e): {} bytes", 1028); + 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", 1024); +} + +/// 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).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).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"); + } +} + +/// 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 sk = genuine_2048_key(); + let pk = RsaPublicComponents::::new(sk.n(), 0x10001).unwrap(); + let pk = rsa_2048::RSA2048KEMPublicKey::from_bytes( + &pk.key::().encode(), + ) + .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 sk = genuine_8192_key(); + let pk = RsaPublicComponents::::new(sk.n(), 0x10001).unwrap(); + let pk = rsa_8192::RSA8192KEMPublicKey::from_bytes( + &pk.key::().encode(), + ) + .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 sk = genuine_2048_key(); + let pk = RsaPublicComponents::::new(sk.n(), 0x10001).unwrap(); + let pk = rsa_2048::RSA2048KEMPublicKey::from_bytes( + &pk.key::().encode(), + ) + .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 sk = genuine_8192_key(); + let pk = RsaPublicComponents::::new(sk.n(), 0x10001).unwrap(); + let pk = rsa_8192::RSA8192KEMPublicKey::from_bytes( + &pk.key::().encode(), + ) + .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 00000000..d7dbaf31 --- /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-sha1 crate 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::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 508f7960..0b3fafc1 100644 --- a/mem_usage_benches/src/lib.rs +++ b/mem_usage_benches/src/lib.rs @@ -22,7 +22,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 5b21a698..f20dd1b7 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -29,7 +29,9 @@ pub use bouncycastle_pbkdf2 as pbkdf2; pub use bouncycastle_poly1305 as poly1305; pub use bouncycastle_ripemd as ripemd; pub use bouncycastle_rng as rng; +pub use bouncycastle_rsa as rsa; pub use bouncycastle_scrypt as scrypt; +pub use bouncycastle_sha1 as sha1; pub use bouncycastle_sha2 as sha2; pub use bouncycastle_sha3 as sha3; pub use bouncycastle_sm2 as sm2;