From ab991ee505b311467dabb0360da648663e38bda4 Mon Sep 17 00:00:00 2001 From: David Hook Date: Sat, 19 Sep 2026 17:06:36 +1000 Subject: [PATCH 01/55] Scaffold bouncycastle-rsa crate Empty crate for RSASSA-PKCS1-v1_5 and RSASSA-PSS (RFC 8017), depending on bouncycastle-ec for its constant-time limb arithmetic (nat/montgomery) rather than a dedicated bignum type. No algorithms yet -- this is step 1 of the RSA signature plan on this branch. Co-Authored-By: Claude Sonnet 5 --- Cargo.toml | 1 + crypto/rsa/Cargo.toml | 15 +++++++++++++++ crypto/rsa/src/lib.rs | 21 +++++++++++++++++++++ 3 files changed, 37 insertions(+) create mode 100644 crypto/rsa/Cargo.toml create mode 100644 crypto/rsa/src/lib.rs diff --git a/Cargo.toml b/Cargo.toml index 2aaf8236..cc2a93e5 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -33,6 +33,7 @@ bouncycastle-mldsa-common = { path = "./crypto/mldsa-common" } bouncycastle-mldsa-lowmemory = { path = "./crypto/mldsa-lowmemory" } bouncycastle-poly1305 = { path = "./crypto/poly1305" } bouncycastle-rng = { path = "./crypto/rng" } +bouncycastle-rsa = { path = "./crypto/rsa" } bouncycastle-sha2 = { path = "./crypto/sha2" } bouncycastle-sha3 = { path = "./crypto/sha3" } bouncycastle-sm2 = { path = "./crypto/sm2" } diff --git a/crypto/rsa/Cargo.toml b/crypto/rsa/Cargo.toml new file mode 100644 index 00000000..511126b2 --- /dev/null +++ b/crypto/rsa/Cargo.toml @@ -0,0 +1,15 @@ +[package] +name = "bouncycastle-rsa" +version.workspace = true +edition.workspace = true + +[dependencies] +bouncycastle-core.workspace = true +bouncycastle-ec.workspace = true +bouncycastle-rng.workspace = true +bouncycastle-utils.workspace = true + +[dev-dependencies] +bouncycastle-core-test-framework.workspace = true +bouncycastle-hex.workspace = true +criterion.workspace = true diff --git a/crypto/rsa/src/lib.rs b/crypto/rsa/src/lib.rs new file mode 100644 index 00000000..4d3a96d5 --- /dev/null +++ b/crypto/rsa/src/lib.rs @@ -0,0 +1,21 @@ +//! RSA digital signatures: RSASSA-PKCS1-v1_5 and RSASSA-PSS (RFC 8017 §8), 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 only -- no RSAES-OAEP or RSAES-PKCS1-v1_5 encryption. Modulus sizes 2048 +//! through 8192 bits support both signing and verification; 1024-bit moduli support verification +//! only, enforced by the absence of a private-key/signer type for that size rather than a runtime +//! check. +//! +//! # Status +//! +//! Scaffold only -- no algorithms are implemented yet. + +#![no_std] +#![forbid(unsafe_code)] +#![forbid(missing_docs)] From f7f2f1284a6e556192e27096d1cbf3d060f4ab4c Mon Sep 17 00:00:00 2001 From: David Hook Date: Sat, 19 Sep 2026 17:15:09 +1000 Subject: [PATCH 02/55] rsa: constant-time modular exponentiation over a runtime modulus Adds modexp.rs: a Montgomery-based mod_pow generic over limb count L, built on bouncycastle-ec's nat/montgomery primitives. Unlike every curve in that crate, RSA's modulus arrives at runtime rather than as a compile-time constant, so this derives its own Montgomery setup (n' by Newton's method, R mod n and R^2 mod n by repeated doubling-and-reduction) instead of using precomputed per-curve constants -- both operate on the modulus alone, which is public in RSA, so they run in variable time. mod_pow itself is constant time in the exponent via Joye & Yen's Montgomery powering ladder (CHES 2002): one multiply and one square per modulus bit, moved into place with a branch-free conditional swap. Validated against known-answer vectors computed with Python's arbitrary- precision pow() (not from recall) at L=1, 2, 4, and 32 (2048-bit, the actual RSA-2048 limb count), plus a genuine 128-bit toy RSA keypair's sign/verify round trip and the classic textbook n=3233 example. cargo mutants -p bouncycastle-rsa --jobs 3: 26 mutants, 23 caught, 2 unviable, 1 missed (an OR/XOR equivalence in redc_normalize's subtraction mask -- documented inline, not reachable given montgomery::redc's own <2n postcondition). Co-Authored-By: Claude Sonnet 5 --- crypto/rsa/src/lib.rs | 6 +- crypto/rsa/src/modexp.rs | 205 +++++++++++++++++++++++++++++++ crypto/rsa/tests/modexp_tests.rs | 160 ++++++++++++++++++++++++ 3 files changed, 370 insertions(+), 1 deletion(-) create mode 100644 crypto/rsa/src/modexp.rs create mode 100644 crypto/rsa/tests/modexp_tests.rs diff --git a/crypto/rsa/src/lib.rs b/crypto/rsa/src/lib.rs index 4d3a96d5..b08f1fee 100644 --- a/crypto/rsa/src/lib.rs +++ b/crypto/rsa/src/lib.rs @@ -14,8 +14,12 @@ //! //! # Status //! -//! Scaffold only -- no algorithms are implemented yet. +//! [`modexp`] (constant-time modular exponentiation over a runtime-supplied modulus) is +//! implemented. The RSA-specific layers on top of it -- keys, CRT, PKCS#1 v1.5 and PSS -- are +//! not yet. #![no_std] #![forbid(unsafe_code)] #![forbid(missing_docs)] + +pub mod modexp; diff --git a/crypto/rsa/src/modexp.rs b/crypto/rsa/src/modexp.rs new file mode 100644 index 00000000..9132136c --- /dev/null +++ b/crypto/rsa/src/modexp.rs @@ -0,0 +1,205 @@ +//! 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). RSA's private-key signing operation (a later addition to this crate) applies +//! message blinding on top of this primitive; this module does not do that itself; it is a +//! general-purpose engine, not the full defence. + +use bouncycastle_ec::montgomery; +use bouncycastle_ec::nat; +use bouncycastle_utils::ct::Condition; + +/// `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) +} + +/// 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. +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], +} + +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 }) + } + + /// The modulus this context was built for. + pub fn modulus(&self) -> &[u64; L] { + &self.modulus + } +} + +/// `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 base_padded = [0u64; L2]; + base_padded[..L].copy_from_slice(base); + let base_bar = redc_normalize::( + &montgomery::widening_mul::(base, &ctx.r2_mod_n), + &ctx.modulus, + ctx.n_prime, + ); + + let mut r0 = ctx.r_mod_n; + let mut r1 = base_bar; + + 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); + let new_r1 = mont_mul::(&r0, &r1, &ctx.modulus, ctx.n_prime); + let 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 mut r0_padded = [0u64; L2]; + r0_padded[..L].copy_from_slice(&r0); + redc_normalize::(&r0_padded, &ctx.modulus, ctx.n_prime) +} diff --git a/crypto/rsa/tests/modexp_tests.rs b/crypto/rsa/tests/modexp_tests.rs new file mode 100644 index 00000000..3edff01c --- /dev/null +++ b/crypto/rsa/tests/modexp_tests.rs @@ -0,0 +1,160 @@ +//! 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}; + +/// `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()); +} From 182eb3c4f1ca60e4f2525fd226f3c60ab1693416 Mon Sep 17 00:00:00 2001 From: David Hook Date: Sat, 19 Sep 2026 17:39:53 +1000 Subject: [PATCH 03/55] rsa: CRT key types and RSASP1/RSAVP1 (RFC 8017 SS5.2) Adds keys.rs: RsaPublicKey (n, e) and RsaPrivateKey in RFC 8017 SS3.2's CRT ("second representation") form -- p, q, dP, dQ, qInv, held in Secret. This crate does not generate keys; both types are built from externally supplied CRT components (test vectors, or a key produced elsewhere). RsaPrivateKey requires p and q to be the same bit length, which the CRT recombination in rsa_core.rs depends on for a single-subtraction reduction rather than a general one. Adds rsa_core.rs: RSASP1 (SS5.2.1) and RSAVP1 (SS5.2.2), crate-private -- never exposed directly, only reachable through a padding scheme (PKCS#1 v1.5 or PSS, not yet added) per RFC 8017's own warning that these primitives are not secure on their own. Since rsasp1/rsavp1 are deliberately unreachable from the public API, they're covered by an in-crate unit test (the documented "high-risk code that cannot be reached through the public API" exception) rather than tests/, using a genuine 2048-bit RSA keypair whose expected signatures were cross-checked in Python two ways: CRT recombination against plain pow(m, d, n), and pow(pow(m, d, n), e, n) == m. Extends modexp.rs with the primitives CRT needs: mul_mod, sub_mod, reduce_once, and reduce_wide. reduce_wide/reduce_once/sub_mod are constant time with respect to their modulus, unlike modexp.rs's existing double_mod_n/pow2_mod -- RSA's own modulus n is public, but p and q (used as moduli during CRT recombination) are private key material. While adding tests for RsaPrivateKey::from_crt_components' validation, found and removed two redundant checks (is_zero(p)/is_zero(q): a zero value's low limb is already even, so the existing oddness check subsumes them) and split the remaining OR-chain into independent if-statements -- several of its mutants could only be killed by a test that didn't also accidentally trip a *later* check (e.g. shrinking p to test the bit-length guard also breaks the unrelated dP < p check unless dP is chosen small enough to stay valid either way). cargo mutants -p bouncycastle-rsa --jobs 3: 101 mutants, 75 caught, 23 unviable, 3 missed (the same class of accepted OR/XOR equivalence as the prior commit, now also in ct_shift_in_bit_mod -- documented inline). Co-Authored-By: Claude Sonnet 5 --- crypto/rsa/src/keys.rs | 173 ++++++++++++++++++++++++ crypto/rsa/src/lib.rs | 9 +- crypto/rsa/src/modexp.rs | 108 +++++++++++++-- crypto/rsa/src/rsa_core.rs | 231 +++++++++++++++++++++++++++++++++ crypto/rsa/tests/keys_tests.rs | 160 +++++++++++++++++++++++ 5 files changed, 666 insertions(+), 15 deletions(-) create mode 100644 crypto/rsa/src/keys.rs create mode 100644 crypto/rsa/src/rsa_core.rs create mode 100644 crypto/rsa/tests/keys_tests.rs diff --git a/crypto/rsa/src/keys.rs b/crypto/rsa/src/keys.rs new file mode 100644 index 00000000..92bd0817 --- /dev/null +++ b/crypto/rsa/src/keys.rs @@ -0,0 +1,173 @@ +//! RSA key types: [`RsaPublicKey`] (RFC 8017 §3.1's `(n, e)`) and [`RsaPrivateKey`] (§3.2's +//! "second representation", the CRT quintuple `p`, `q`, `dP`, `dQ`, `qInv`), generic over the +//! modulus's limb count `L` and each prime's limb count `HALF`. +//! +//! This crate does not generate keys: callers construct these from externally supplied key +//! material (e.g. loaded from CAVP/wycheproof test vectors, or a key produced by another +//! implementation), not from primes generated here. 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. + +use bouncycastle_core::errors::SignatureError; +use bouncycastle_ec::montgomery; +use bouncycastle_ec::nat; +use bouncycastle_utils::secret::Secret; + +/// An RSA public key: RFC 8017 §3.1's `(n, e)`. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct RsaPublicKey { + n: [u64; L], + e: u32, +} + +impl RsaPublicKey { + /// Builds a public key from its modulus and exponent. Returns + /// `Err(`[`SignatureError::DecodingError`]`)` if `n` is even, or if `e` is even or less than 3 + /// (RFC 8017 §3.1: "the RSA public exponent e is an integer between 3 and n - 1"; the upper + /// bound is not checked here -- it needs a full multi-limb comparison against `n` for a + /// boundary no key from a real implementation will ever hit). There is no separate all-zero + /// check on `n`: a zero value's low limb is `0`, which the oddness check already rejects. + pub fn new(n: &[u64; L], e: u32) -> Result { + if n[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`. + pub fn n(&self) -> &[u64; L] { + &self.n + } + + /// The public exponent `e`. + pub fn e(&self) -> u32 { + self.e + } +} + +/// An RSA private key in RFC 8017 §3.2's CRT ("second representation") form: `p`, `q`, `dP`, +/// `dQ`, `qInv`. `L` (the modulus's limb count) must be exactly `2 * HALF`; like +/// `bouncycastle_ec::montgomery`'s `L2 = 2 * L`, that relationship is enforced at construction +/// (see [`Self::from_crt_components`]) rather than expressed in the type, because stable Rust has +/// no way to compute one const generic from another. +/// +/// # Why `p` and `q` must be the same bit length +/// +/// RFC 8017's CRT recombination (§5.2.1 step 2.b.3) computes `h = (s1 - s2) * qInv mod p`, which +/// needs `s2` (a residue mod `q`) reduced mod `p` first. This crate does that with a single +/// constant-time conditional subtraction ([`crate::modexp::reduce_once`]), which is only correct +/// when `s2 < 2p`, i.e. `q < 2p` -- guaranteed whenever `p` and `q` occupy the same number of bits +/// (true of any balanced RSA key, which every real-world generator produces), but not true in +/// general for two arbitrary primes. [`Self::from_crt_components`] enforces exactly that: both +/// primes' top limb must have its top bit set. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct RsaPrivateKey { + p: Secret<[u64; HALF]>, + q: Secret<[u64; HALF]>, + d_p: Secret<[u64; HALF]>, + d_q: Secret<[u64; HALF]>, + q_inv: Secret<[u64; HALF]>, + /// `n = p * q`, computed once here. Public: `n` is shared with the matching public key (RFC + /// 8017 §3.2, "the RSA modulus n is the same as in the corresponding RSA public key"). + n: [u64; L], +} + +impl RsaPrivateKey { + /// Builds a private key from its CRT components. Returns + /// `Err(`[`SignatureError::DecodingError`]`)` if: + /// + /// * `L != 2 * HALF` (a caller programming error -- every concrete instantiation in this + /// crate pairs a fixed `L` with a fixed `HALF`, so this cannot happen through the crate's + /// own public API, only through an explicit, wrong turbofish); + /// * `p` or `q` is even, equal to each other, or not exactly `HALF * 64` bits (top bit of the + /// top limb clear) -- see the type's docs for why equal bit length matters. There is no + /// separate all-zero check: a zero value's low limb is `0`, which the oddness check already + /// rejects. + /// * `dP >= p`, `dQ >= q`, or `qInv >= p` (RFC 8017 §3.2: `dP`/`dQ`/`qInv` are each "a + /// positive integer less than" their modulus). + pub fn from_crt_components( + p: &[u64; HALF], + q: &[u64; HALF], + d_p: &[u64; HALF], + d_q: &[u64; HALF], + q_inv: &[u64; HALF], + ) -> Result { + if L != 2 * HALF { + return Err(SignatureError::DecodingError("RSA modulus width must be 2 * prime width")); + } + let top_bit_set = |x: &[u64; HALF]| x[HALF - 1] >> 63 == 1; + if p[0] & 1 == 0 { + return Err(SignatureError::DecodingError("p must be odd")); + } + if q[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 !top_bit_set(p) { + return Err(SignatureError::DecodingError("p must be exactly HALF * 64 bits")); + } + if !top_bit_set(q) { + return Err(SignatureError::DecodingError("q must be exactly HALF * 64 bits")); + } + if nat::sub(d_p, p).1 != 1 { + return Err(SignatureError::DecodingError("dP must be less than p")); + } + if nat::sub(d_q, q).1 != 1 { + return Err(SignatureError::DecodingError("dQ must be less than q")); + } + if nat::sub(q_inv, p).1 != 1 { + return Err(SignatureError::DecodingError("qInv must be less than p")); + } + + // `L == 2 * HALF` (checked above), so this widening multiply's `L2 = L` output is exactly + // the modulus width -- `p * q` is exact, never reduced, since it is the modulus itself. + let n = montgomery::widening_mul::(p, q); + + let mut key = Self { + p: Secret::default(), + q: Secret::default(), + d_p: Secret::default(), + d_q: Secret::default(), + q_inv: Secret::default(), + n, + }; + *key.p = *p; + *key.q = *q; + *key.d_p = *d_p; + *key.d_q = *d_q; + *key.q_inv = *q_inv; + Ok(key) + } + + /// The modulus `n = p * q`. + pub fn n(&self) -> &[u64; L] { + &self.n + } + + pub(crate) fn p(&self) -> &[u64; HALF] { + &self.p + } + + pub(crate) fn q(&self) -> &[u64; HALF] { + &self.q + } + + pub(crate) fn d_p(&self) -> &[u64; HALF] { + &self.d_p + } + + pub(crate) fn d_q(&self) -> &[u64; HALF] { + &self.d_q + } + + pub(crate) fn q_inv(&self) -> &[u64; HALF] { + &self.q_inv + } +} diff --git a/crypto/rsa/src/lib.rs b/crypto/rsa/src/lib.rs index b08f1fee..87602fbd 100644 --- a/crypto/rsa/src/lib.rs +++ b/crypto/rsa/src/lib.rs @@ -14,12 +14,15 @@ //! //! # Status //! -//! [`modexp`] (constant-time modular exponentiation over a runtime-supplied modulus) is -//! implemented. The RSA-specific layers on top of it -- keys, CRT, PKCS#1 v1.5 and PSS -- are -//! not yet. +//! [`modexp`] (constant-time modular exponentiation over a runtime-supplied modulus), [`keys`] +//! (the CRT key types), and the CRT-based RSASP1/RSAVP1 primitives (crate-private, in +//! `rsa_core`) are implemented. PKCS#1 v1.5 and PSS, the schemes that make those primitives safe +//! to expose, are not yet. #![no_std] #![forbid(unsafe_code)] #![forbid(missing_docs)] +pub mod keys; pub mod modexp; +mod rsa_core; diff --git a/crypto/rsa/src/modexp.rs b/crypto/rsa/src/modexp.rs index 9132136c..96e55869 100644 --- a/crypto/rsa/src/modexp.rs +++ b/crypto/rsa/src/modexp.rs @@ -129,6 +129,100 @@ fn mont_square( 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); + redc_normalize::(&padded, &ctx.modulus, ctx.n_prime) +} + +/// `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 b_bar = to_montgomery::(b, ctx); + let t = montgomery::widening_mul::(a, &b_bar); + redc_normalize::(&t, &ctx.modulus, ctx.n_prime) +} + +/// `(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) +} + +/// `x mod modulus` for `x < 2 * modulus`, in constant time with respect to `modulus`. RSA's CRT +/// recombination needs `s2 mod p` before it can subtract (RFC 8017 §5.2.1 step 2.b.3), and +/// `s2 < q < 2p` whenever `p` and `q` are the same bit length, which +/// [`crate::keys::RsaPrivateKey::from_crt_components`] requires of every key it builds. +pub fn reduce_once(x: &[u64; N], modulus: &[u64; N]) -> [u64; N] { + let (diff, borrow) = nat::sub(x, modulus); + let subtract = Condition::::from_lsb(borrow ^ 1); + ct_select_array(subtract, &diff, x) +} + +/// `(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; + 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` (`WIDE > +/// NARROW`), 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 message down to one CRT +/// prime's width (RFC 8017 §5.2.1 step 2.b.1's `m^dP mod p` needs `m mod p` first, since `m` can +/// be as wide as `n`), 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`. 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 @@ -176,16 +270,8 @@ pub fn mod_pow( ) -> [u64; L] { debug_assert_eq!(nat::sub(base, &ctx.modulus).1, 1, "mod_pow needs base < modulus"); - let mut base_padded = [0u64; L2]; - base_padded[..L].copy_from_slice(base); - let base_bar = redc_normalize::( - &montgomery::widening_mul::(base, &ctx.r2_mod_n), - &ctx.modulus, - ctx.n_prime, - ); - let mut r0 = ctx.r_mod_n; - let mut r1 = base_bar; + let mut r1 = to_montgomery::(base, ctx); for limb_index in (0..L).rev() { for bit_index in (0..64u32).rev() { @@ -199,7 +285,5 @@ pub fn mod_pow( } } - let mut r0_padded = [0u64; L2]; - r0_padded[..L].copy_from_slice(&r0); - redc_normalize::(&r0_padded, &ctx.modulus, ctx.n_prime) + from_montgomery::(&r0, ctx) } diff --git a/crypto/rsa/src/rsa_core.rs b/crypto/rsa/src/rsa_core.rs new file mode 100644 index 00000000..413177ea --- /dev/null +++ b/crypto/rsa/src/rsa_core.rs @@ -0,0 +1,231 @@ +//! 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::RsaPrivateKey`] has no representation for +//! multi-prime RSA, so there is nothing here to extend to `u > 2`. + +use crate::keys::{RsaPrivateKey, RsaPublicKey}; +use crate::modexp::{MontgomeryContext, mod_pow, mul_mod, reduce_once, reduce_wide, sub_mod}; +use bouncycastle_core::errors::SignatureError; +use bouncycastle_ec::montgomery; +use bouncycastle_ec::nat; + +/// 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: &RsaPublicKey, + s: &[u64; L], +) -> Result<[u64; L], SignatureError> { + if nat::sub(s, pk.n()).1 != 1 { + return Err(SignatureError::DecodingError("signature representative out of range")); + } + let ctx = MontgomeryContext::::new(pk.n()) + .expect("RsaPublicKey::new already validated n is odd and nonzero"); + + let mut e_limbs = [0u64; L]; + e_limbs[0] = pk.e() as u64; + + Ok(mod_pow::(s, &e_limbs, &ctx)) +} + +/// RSASP1 (RFC 8017 §5.2.1), CRT form (step 2.b, two-prime case): `s1 = m^dP mod p`, `s2 = m^dQ +/// mod q`, `h = (s1 - s2) * qInv mod p`, `s = s2 + q * h`. +/// +/// Step 1's range check ("If the message representative m is not between 0 and n - 1, output +/// 'message representative out of range'") is `Err(`[`SignatureError::DecodingError`]`)` here. +pub(crate) fn rsasp1< + const L: usize, + const L2: usize, + const L21: usize, + const HALF: usize, + const HALF2: usize, + const HALF21: usize, +>( + sk: &RsaPrivateKey, + m: &[u64; L], +) -> Result<[u64; L], SignatureError> { + if nat::sub(m, sk.n()).1 != 1 { + return Err(SignatureError::DecodingError("message representative out of range")); + } + + let ctx_p = MontgomeryContext::::new(sk.p()) + .expect("RsaPrivateKey::from_crt_components already validated p is odd and nonzero"); + let ctx_q = MontgomeryContext::::new(sk.q()) + .expect("RsaPrivateKey::from_crt_components already validated q is odd and nonzero"); + + // RFC 8017 §5.2.1 step 2.b.1: reducing `m` (n-width) down to each prime's width is not itself + // part of the RFC's stated steps, which write "m^dP mod p" as if `m` already fit -- but `m` + // is as wide as `n = p * q`, so a real implementation must reduce it first. `p`/`q` are + // private key material, so this uses the constant-time (in the modulus) `reduce_wide`, not + // `bouncycastle_ec`-style variable-time reduction (which is only safe for RSA's *public* `n`). + let m_mod_p = reduce_wide::(m, sk.p()); + let m_mod_q = reduce_wide::(m, sk.q()); + + let s1 = mod_pow::(&m_mod_p, sk.d_p(), &ctx_p); + let s2 = mod_pow::(&m_mod_q, sk.d_q(), &ctx_q); + + // Step 2.b.3: `h = (s1 - s2) * qInv mod p`. `s2 < q`, and `q < 2p` because + // `RsaPrivateKey::from_crt_components` requires `p` and `q` to be the same bit length (see + // that type's docs), so one constant-time conditional subtraction reduces it mod `p`. + let s2_mod_p = reduce_once::(&s2, sk.p()); + let diff = sub_mod::(&s1, &s2_mod_p, sk.p()); + let h = mul_mod::(&diff, sk.q_inv(), &ctx_p); + + // Step 2.b.4: `s = s2 + q * h`. `h < p` and `q * h < q * p = n`, and CRT recombination + // guarantees `s2 + q*h < n` (Garner's algorithm's own correctness property), so this widening + // multiply-then-add cannot overflow `L` limbs. + let q_h = montgomery::widening_mul::(sk.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"); + + Ok(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::*; + + fn keypair() -> RsaPrivateKey<32, 16> { + 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, + ]; + RsaPrivateKey::from_crt_components(&p, &q, &d_p, &d_q, &q_inv) + .expect("genuine CRT components must be accepted") + } + + fn public_key(sk: &RsaPrivateKey<32, 16>) -> RsaPublicKey<32> { + RsaPublicKey::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::<32, 64, 65, 16, 32, 33>(&sk, &m).expect("m is in range"); + assert_eq!(s, expected_s); + + let recovered = rsavp1::<32, 64, 65>(&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::<32, 64, 65, 16, 32, 33>(&sk, &m2).expect("m2 is in range"); + assert_eq!(s2, expected_s2); + assert_eq!(rsavp1::<32, 64, 65>(&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::<32, 64, 65, 16, 32, 33>(&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::<32, 64, 65>(&pk, &out_of_range), + Err(SignatureError::DecodingError(_)) + )); + } +} diff --git a/crypto/rsa/tests/keys_tests.rs b/crypto/rsa/tests/keys_tests.rs new file mode 100644 index 00000000..f7bfc3bb --- /dev/null +++ b/crypto/rsa/tests/keys_tests.rs @@ -0,0 +1,160 @@ +//! Validation tests for [`bouncycastle_rsa::keys`]'s public API. + +use bouncycastle_core::errors::SignatureError; +use bouncycastle_rsa::keys::{RsaPrivateKey, RsaPublicKey}; + +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 = RsaPrivateKey::<32, 16>::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_mismatched_widths() { + // L = 31 != 2 * 16. + assert!(matches!( + RsaPrivateKey::<31, 16>::from_crt_components(&P, &Q, &D_P, &D_Q, &Q_INV), + Err(SignatureError::DecodingError(_)) + )); +} + +#[test] +fn from_crt_components_rejects_equal_primes() { + assert!(matches!( + RsaPrivateKey::<32, 16>::from_crt_components(&P, &P, &D_P, &D_Q, &Q_INV), + Err(SignatureError::DecodingError(_)) + )); +} + +/// Trivially `< ` any nonzero `HALF`-limb prime, real or shrunk by a test -- used below to keep +/// a test isolated to the one condition it names, instead of also (accidentally) tripping the +/// separate `dP`/`dQ`/`qInv` range checks that come after it. +const SMALL: [u64; 16] = [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]; + +#[test] +fn from_crt_components_rejects_even_prime() { + let mut even_p = P; + even_p[0] &= !1; + assert!(matches!( + RsaPrivateKey::<32, 16>::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!( + RsaPrivateKey::<32, 16>::from_crt_components(&P, &even_q, &D_P, &D_Q, &Q_INV), + Err(SignatureError::DecodingError(_)) + )); +} + +#[test] +fn from_crt_components_rejects_short_prime() { + // Clearing the top bit makes p occupy fewer than HALF * 64 bits, violating the + // equal-bit-length invariant CRT recombination depends on. dP/qInv are replaced with a + // trivially-in-range value so this test isolates the bit-length check: the real D_P/Q_INV + // are close to p's own magnitude, so against a p shrunk by half they would (correctly, but + // for the wrong reason from this test's point of view) also fail the later dP/qInv range + // checks. + let mut short_p = P; + short_p[15] &= !(1u64 << 63); + assert!(matches!( + RsaPrivateKey::<32, 16>::from_crt_components(&short_p, &Q, &SMALL, &D_Q, &SMALL), + Err(SignatureError::DecodingError(_)) + )); +} + +#[test] +fn from_crt_components_rejects_short_q() { + let mut short_q = Q; + short_q[15] &= !(1u64 << 63); + assert!(matches!( + RsaPrivateKey::<32, 16>::from_crt_components(&P, &short_q, &D_P, &SMALL, &SMALL), + Err(SignatureError::DecodingError(_)) + )); +} + +#[test] +fn from_crt_components_rejects_dp_out_of_range() { + assert!(matches!( + RsaPrivateKey::<32, 16>::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!( + RsaPrivateKey::<32, 16>::from_crt_components(&P, &Q, &D_P, &D_Q, &P), + Err(SignatureError::DecodingError(_)) + )); +} + +#[test] +fn public_key_accepts_e_65537() { + let pk = RsaPublicKey::<32>::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!(RsaPublicKey::<32>::new(&N, 65536), Err(SignatureError::DecodingError(_)))); +} + +#[test] +fn public_key_rejects_exponent_below_three() { + assert!(matches!(RsaPublicKey::<32>::new(&N, 1), Err(SignatureError::DecodingError(_)))); +} + +#[test] +fn public_key_rejects_even_modulus() { + let mut even_n = N; + even_n[0] &= !1; + assert!(matches!(RsaPublicKey::<32>::new(&even_n, 3), Err(SignatureError::DecodingError(_)))); +} From c27655f7cbd34c1e9a7a61d4dc6b1807bcdb2ce4 Mon Sep 17 00:00:00 2001 From: David Hook Date: Sat, 19 Sep 2026 19:47:08 +1000 Subject: [PATCH 04/55] rsa: RSASSA-PKCS1-v1_5 sign/verify for RSA-2048/SHA-256 Adds the first end-to-end vertical slice: codec.rs (OS2IP/I2OSP-style byte<->limb conversion), emsa_pkcs1_v1_5.rs (RFC 8017 SS9.2 encode/decode), rsassa_pkcs1_v1_5.rs (SS8.2 sign/verify orchestration), and rsa_2048.rs (the concrete RSA-2048/SHA-256 wrapper). digest_info is built directly from bouncycastle-sha2's AlgorithmOID::OID_DER rather than a hand-copied prefix table, reproducing RFC 8017's nine listed DigestInfo prefixes exactly. Verification decodes EM rather than re-encoding and comparing bytes, per explicit instruction: a DigestInfo whose AlgorithmIdentifier omits the NULL parameters (legal ASN.1 -- the field is ANY DEFINED BY algorithm -- but not what RFC 8017 itself produces) must be accepted, since real implementations ship that way; generation always includes NULL. Confirmed against Wycheproof's one MissingNull "acceptable" vector. The decoder is written to withstand adversarial input, not just malformed input: DER lengths must be single-byte short form (BER long-form rejected outright), and every byte of the DigestInfo must be accounted for by the parse (no trailing garbage). Mutation testing caught a real gap here, not just a style question: relaxing inner_end > t.len() to == let a crafted EM reach an unguarded slice and panic, a genuine crash-on-malformed- signature DoS vector given verification runs on adversarial input by definition. Fixed by keeping the check and adding a regression test that exercises it directly. Validated against genuine Wycheproof RSA-2048/SHA-256 vectors: rsa_pkcs1_2048_sig_gen_test.json (8/8 signatures match exactly) and rsa_signature_2048_sha256_test.json (all 259 verify vectors across its three groups, including every forgery-shaped invalid case and the one acceptable case). Building this test data surfaced and fixed a real bug in the CRT recombination added in the previous commit: RsaPrivateKey required p and q to be the same bit length, justified by "a genuine wycheproof key has q about 7x p" -- that claim was itself a hex-transcription bug (concatenating little-endian limbs in array order reverses significance), and the real key's p and q are both genuinely 1024 bits. The requirement was still wrong to have, independent of that: RFC 8017 SS3.2 never requires it, and reduce_wide's general bit-serial reduction handles any magnitude relationship at the same asymptotic cost already paid to reduce the n-width message down to each prime's width. Replaced the single-conditional- subtraction reduce_once with reduce_wide (WIDE == NARROW is a valid case, not just WIDE > NARROW) and removed the bit-length requirement. Added direct tests for reduce_wide/sub_mod/mul_mod, including a deliberately unbalanced case (~4.9 billion times the modulus) neither the removed requirement nor the real key exercised. cargo mutants -p bouncycastle-rsa --jobs 3: 230 mutants, 186 caught, 31 unviable, and 8 not caught outright, all individually investigated by hand (applying each mutation and re-running the real test suite, since the machine was too loaded for repeated automated mutants runs to be reliable -- load average peaked above 90 from unrelated concurrent work): 4 were genuine gaps, now fixed with dedicated regression tests (the inner_end panic above; accepting the encryption block-type 0x02 where only 0x01 is valid, which Wycheproof's own vectors for that case did not happen to isolate; and the RFC's own "PS is at least 8 octets" boundary, which the threshold check's comparison operator could be weakened without any existing test noticing). The remaining 4, plus the 3 already-documented OR/XOR equivalences in modexp.rs, are accepted equivalents for this crate's fixed instantiations, documented inline at each site with the specific reason they cannot produce a different outcome. One further timeout (i += 1 mutated to i *= 1) is a genuine infinite loop, correctly a kill. Co-Authored-By: Claude Sonnet 5 --- crypto/rsa/Cargo.toml | 2 + crypto/rsa/src/codec.rs | 33 ++ crypto/rsa/src/emsa_pkcs1_v1_5.rs | 407 ++++++++++++++++++ crypto/rsa/src/keys.rs | 31 +- crypto/rsa/src/lib.rs | 36 +- crypto/rsa/src/modexp.rs | 31 +- crypto/rsa/src/rsa_2048.rs | 34 ++ crypto/rsa/src/rsa_core.rs | 13 +- crypto/rsa/src/rsassa_pkcs1_v1_5.rs | 76 ++++ crypto/rsa/tests/keys_tests.rs | 31 -- crypto/rsa/tests/modexp_tests.rs | 52 ++- crypto/rsa/tests/rsa_2048_pkcs1_v1_5_tests.rs | 217 ++++++++++ 12 files changed, 885 insertions(+), 78 deletions(-) create mode 100644 crypto/rsa/src/codec.rs create mode 100644 crypto/rsa/src/emsa_pkcs1_v1_5.rs create mode 100644 crypto/rsa/src/rsa_2048.rs create mode 100644 crypto/rsa/src/rsassa_pkcs1_v1_5.rs create mode 100644 crypto/rsa/tests/rsa_2048_pkcs1_v1_5_tests.rs diff --git a/crypto/rsa/Cargo.toml b/crypto/rsa/Cargo.toml index 511126b2..f0d97d2e 100644 --- a/crypto/rsa/Cargo.toml +++ b/crypto/rsa/Cargo.toml @@ -7,9 +7,11 @@ edition.workspace = true bouncycastle-core.workspace = true bouncycastle-ec.workspace = true bouncycastle-rng.workspace = true +bouncycastle-sha2.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" 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/emsa_pkcs1_v1_5.rs b/crypto/rsa/src/emsa_pkcs1_v1_5.rs new file mode 100644 index 00000000..004b2238 --- /dev/null +++ b/crypto/rsa/src/emsa_pkcs1_v1_5.rs @@ -0,0 +1,407 @@ +//! EMSA-PKCS1-v1_5 (RFC 8017 §9.2): deterministic signature encoding, generic over the hash +//! function `H` via its [`Hash`]/[`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. + +use bouncycastle_core::traits::{AlgorithmOID, Hash, 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. +fn digest_info( + digest: &[u8; H_LEN], +) -> [u8; T_LEN] { + debug_assert_eq!(H_LEN, H::OUTPUT_LEN, "digest_info: H_LEN must match H::OUTPUT_LEN"); + 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 " + debug_assert_eq!(T_LEN, 2 + outer_len, "digest_info: T_LEN must match the computed DER length"); + + let mut t = [0u8; 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 +} + +/// EMSA-PKCS1-V1_5-ENCODE (RFC 8017 §9.2), with `emLen` fixed to `K_LEN` (see the module docs). +/// +/// Steps 1-2: hash `message` and wrap it in [`digest_info`]. Step 3's error ("intended encoded +/// message length too short", `emLen < tLen + 11`) is a `debug_assert` here, not a runtime error: +/// every (hash, modulus size) pairing this crate actually wires up has a modulus thousands of +/// bits wider than any hash's `DigestInfo`, so it can only fire on a deliberately-wrong generic +/// instantiation, never on real input. Steps 4-5 build `EM = 0x00 || 0x01 || PS || 0x00 || T`, +/// where `PS` is `K_LEN - T_LEN - 3` bytes of `0xff` (at least 8, per step 3's bound). +pub fn emsa_pkcs1_v1_5_encode< + H: Hash + HashAlgParams + AlgorithmOID + Default, + const H_LEN: usize, + const T_LEN: usize, + const K_LEN: usize, +>( + message: &[u8], +) -> [u8; K_LEN] { + let mut digest = [0u8; H_LEN]; + H::default().hash_out(message, &mut digest); + let t: [u8; T_LEN] = digest_info::(&digest); + + 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); + 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`]) 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 `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`]'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], + message: &[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; + 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: `t[pos..]` at line 145 + // already fails its own comparison against `computed` (a fixed `[u8; H_LEN]`) 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 != H_LEN || pos + digest_len != t.len() { + return false; + } + + let mut computed = [0u8; H_LEN]; + H::default().hash_out(message, &mut computed); + t[pos..] == computed +} + +/// EMSA-PKCS1-v1_5 verification: 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 `message` and comparing bytes (this crate's [`emsa_pkcs1_v1_5_encode`]) only ever +/// produces one canonical `EM`, and [`decode_digest_info`] must accept two. +/// +/// 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< + H: Hash + HashAlgParams + AlgorithmOID + Default, + const H_LEN: usize, + const K_LEN: usize, +>( + message: &[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..], message) +} + +#[cfg(test)] +mod tests { + //! `digest_info` is crate-private (only [`emsa_pkcs1_v1_5_encode`] 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_sha2::{SHA256, SHA384, SHA512}; + + #[test] + fn digest_info_matches_rfc8017_sha256_prefix() { + let digest = [0xabu8; 32]; + let t = digest_info::(&digest); + 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 t = digest_info::(&digest); + 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 t = digest_info::(&digest); + 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 = emsa_pkcs1_v1_5_encode::(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 = emsa_pkcs1_v1_5_encode::(b"same message"); + let b = emsa_pkcs1_v1_5_encode::(b"same message"); + assert_eq!(a, b); + } + + #[test] + fn encode_differs_for_different_messages() { + let a = emsa_pkcs1_v1_5_encode::(b"message one"); + let b = emsa_pkcs1_v1_5_encode::(b"message two"); + assert_ne!(a, b); + } + + #[test] + fn verify_accepts_what_encode_produces() { + let em = emsa_pkcs1_v1_5_encode::(b"hello"); + assert!(emsa_pkcs1_v1_5_verify::(b"hello", &em)); + } + + #[test] + fn verify_rejects_wrong_message() { + let em = emsa_pkcs1_v1_5_encode::(b"hello"); + assert!(!emsa_pkcs1_v1_5_verify::(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`] always includes. + #[test] + fn verify_accepts_digest_info_with_null_parameters_absent() { + let mut digest = [0u8; 32]; + SHA256::default().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!(emsa_pkcs1_v1_5_verify::(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 = emsa_pkcs1_v1_5_encode::(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!(!emsa_pkcs1_v1_5_verify::(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 = emsa_pkcs1_v1_5_encode::(b"hello"); + let t_start = 256 - 51; + em[t_start + 1] += 1; + assert!(!emsa_pkcs1_v1_5_verify::(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 = emsa_pkcs1_v1_5_encode::(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!(!emsa_pkcs1_v1_5_verify::(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!(!emsa_pkcs1_v1_5_verify::(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 = emsa_pkcs1_v1_5_encode::(b"hello"); + let t_start = 256 - 51; + em[t_start + 4] ^= 0xff; // flip a byte inside the OID + assert!(!emsa_pkcs1_v1_5_verify::(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!(!emsa_pkcs1_v1_5_verify::(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`]'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 = emsa_pkcs1_v1_5_encode::(b"hello"); + assert_eq!(em[2..2 + 8], [0xff; 8], "this construction must exercise ps_len == 8 exactly"); + assert!(emsa_pkcs1_v1_5_verify::(b"hello", &em)); + } +} diff --git a/crypto/rsa/src/keys.rs b/crypto/rsa/src/keys.rs index 92bd0817..d630bf24 100644 --- a/crypto/rsa/src/keys.rs +++ b/crypto/rsa/src/keys.rs @@ -56,15 +56,15 @@ impl RsaPublicKey { /// (see [`Self::from_crt_components`]) rather than expressed in the type, because stable Rust has /// no way to compute one const generic from another. /// -/// # Why `p` and `q` must be the same bit length -/// -/// RFC 8017's CRT recombination (§5.2.1 step 2.b.3) computes `h = (s1 - s2) * qInv mod p`, which -/// needs `s2` (a residue mod `q`) reduced mod `p` first. This crate does that with a single -/// constant-time conditional subtraction ([`crate::modexp::reduce_once`]), which is only correct -/// when `s2 < 2p`, i.e. `q < 2p` -- guaranteed whenever `p` and `q` occupy the same number of bits -/// (true of any balanced RSA key, which every real-world generator produces), but not true in -/// general for two arbitrary primes. [`Self::from_crt_components`] enforces exactly that: both -/// primes' top limb must have its top bit set. +/// `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. #[derive(Clone, Debug, PartialEq, Eq)] pub struct RsaPrivateKey { p: Secret<[u64; HALF]>, @@ -84,10 +84,8 @@ impl RsaPrivateKey { /// * `L != 2 * HALF` (a caller programming error -- every concrete instantiation in this /// crate pairs a fixed `L` with a fixed `HALF`, so this cannot happen through the crate's /// own public API, only through an explicit, wrong turbofish); - /// * `p` or `q` is even, equal to each other, or not exactly `HALF * 64` bits (top bit of the - /// top limb clear) -- see the type's docs for why equal bit length matters. There is no - /// separate all-zero check: a zero value's low limb is `0`, which the oddness check already - /// rejects. + /// * `p` or `q` is even or equal to each other. There is no separate all-zero check: a zero + /// value's low limb is `0`, which the oddness check already rejects. /// * `dP >= p`, `dQ >= q`, or `qInv >= p` (RFC 8017 §3.2: `dP`/`dQ`/`qInv` are each "a /// positive integer less than" their modulus). pub fn from_crt_components( @@ -100,7 +98,6 @@ impl RsaPrivateKey { if L != 2 * HALF { return Err(SignatureError::DecodingError("RSA modulus width must be 2 * prime width")); } - let top_bit_set = |x: &[u64; HALF]| x[HALF - 1] >> 63 == 1; if p[0] & 1 == 0 { return Err(SignatureError::DecodingError("p must be odd")); } @@ -110,12 +107,6 @@ impl RsaPrivateKey { if p == q { return Err(SignatureError::DecodingError("p and q must be distinct")); } - if !top_bit_set(p) { - return Err(SignatureError::DecodingError("p must be exactly HALF * 64 bits")); - } - if !top_bit_set(q) { - return Err(SignatureError::DecodingError("q must be exactly HALF * 64 bits")); - } if nat::sub(d_p, p).1 != 1 { return Err(SignatureError::DecodingError("dP must be less than p")); } diff --git a/crypto/rsa/src/lib.rs b/crypto/rsa/src/lib.rs index 87602fbd..bc8b320e 100644 --- a/crypto/rsa/src/lib.rs +++ b/crypto/rsa/src/lib.rs @@ -12,17 +12,47 @@ //! only, enforced by the absence of a private-key/signer type for that size rather than a runtime //! check. //! +//! # Usage Examples +//! +//! RSA-2048 with SHA-256, the one concrete pairing wired up so far ([`rsa_2048`]): +//! +//! ``` +//! use bouncycastle_rsa::rsa_2048::{Rsa2048PrivateKey, Rsa2048PublicKey, pkcs1_v1_5_sign_sha256, pkcs1_v1_5_verify_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). +//! # 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 = Rsa2048PrivateKey::from_crt_components(&P, &Q, &D_P, &D_Q, &Q_INV)?; +//! let pk = Rsa2048PublicKey::new(sk.n(), 0x10001)?; +//! +//! let signature = pkcs1_v1_5_sign_sha256(&sk, b"the message to sign")?; +//! pkcs1_v1_5_verify_sha256(&pk, b"the message to sign", &signature)?; +//! +//! // A signature does not verify against a different message. +//! assert!(pkcs1_v1_5_verify_sha256(&pk, b"a different message", &signature).is_err()); +//! # Ok::<(), bouncycastle_core::errors::SignatureError>(()) +//! ``` +//! //! # Status //! //! [`modexp`] (constant-time modular exponentiation over a runtime-supplied modulus), [`keys`] -//! (the CRT key types), and the CRT-based RSASP1/RSAVP1 primitives (crate-private, in -//! `rsa_core`) are implemented. PKCS#1 v1.5 and PSS, the schemes that make those primitives safe -//! to expose, are not yet. +//! (the CRT key types), the CRT-based RSASP1/RSAVP1 primitives (crate-private, in `rsa_core`), +//! and RSASSA-PKCS1-v1_5 ([`rsassa_pkcs1_v1_5`], wired up for RSA-2048/SHA-256 in [`rsa_2048`]) +//! are implemented, validated against genuine Wycheproof RSA-2048/SHA-256 vectors (both +//! `rsa_pkcs1_2048_sig_gen_test.json` and `rsa_signature_2048_sha256_test.json`). RSASSA-PSS, +//! the remaining modulus sizes, and the remaining hash functions are not yet. #![no_std] #![forbid(unsafe_code)] #![forbid(missing_docs)] +mod codec; +mod emsa_pkcs1_v1_5; pub mod keys; pub mod modexp; +pub mod rsa_2048; mod rsa_core; +pub mod rsassa_pkcs1_v1_5; diff --git a/crypto/rsa/src/modexp.rs b/crypto/rsa/src/modexp.rs index 96e55869..a10f6b7f 100644 --- a/crypto/rsa/src/modexp.rs +++ b/crypto/rsa/src/modexp.rs @@ -172,16 +172,6 @@ pub fn sub_mod(a: &[u64; N], b: &[u64; N], modulus: &[u64; N]) - ct_select_array(mask, &corrected, &diff) } -/// `x mod modulus` for `x < 2 * modulus`, in constant time with respect to `modulus`. RSA's CRT -/// recombination needs `s2 mod p` before it can subtract (RFC 8017 §5.2.1 step 2.b.3), and -/// `s2 < q < 2p` whenever `p` and `q` are the same bit length, which -/// [`crate::keys::RsaPrivateKey::from_crt_components`] requires of every key it builds. -pub fn reduce_once(x: &[u64; N], modulus: &[u64; N]) -> [u64; N] { - let (diff, borrow) = nat::sub(x, modulus); - let subtract = Condition::::from_lsb(borrow ^ 1); - ct_select_array(subtract, &diff, x) -} - /// `(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] { @@ -201,14 +191,19 @@ fn ct_shift_in_bit_mod(acc: &[u64; N], bit: u64, modulus: &[u64; ct_select_array(subtract, &diff, &doubled) } -/// `value mod modulus` for a `WIDE`-limb `value` and a `NARROW`-limb odd `modulus` (`WIDE > -/// NARROW`), 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 message down to one CRT -/// prime's width (RFC 8017 §5.2.1 step 2.b.1's `m^dP mod p` needs `m mod p` first, since `m` can -/// be as wide as `n`), 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`. Bit-serial schoolbook -/// long division: every one of `value`'s `64 * WIDE` bits contributes one constant-time -/// doubling-and-conditional-subtract step. +/// `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], diff --git a/crypto/rsa/src/rsa_2048.rs b/crypto/rsa/src/rsa_2048.rs new file mode 100644 index 00000000..449c3ec5 --- /dev/null +++ b/crypto/rsa/src/rsa_2048.rs @@ -0,0 +1,34 @@ +//! RSA-2048: the generic engine ([`crate::modexp`], [`crate::rsa_core`], [`crate::rsassa_pkcs1_v1_5`]) +//! wired to concrete widths -- `L = 32` (2048 bits), `HALF = 16` (1024-bit CRT primes) -- so a +//! caller using this size doesn't thread six const-generic width parameters through every call. +//! One file per modulus size, matching [`crate::keys::RsaPrivateKey`]'s own `` shape; +//! `rsa_1024`/`rsa_3072`/`rsa_4096`/`rsa_8192` are the same pattern at their own widths. + +use crate::keys::{RsaPrivateKey, RsaPublicKey}; +use crate::rsassa_pkcs1_v1_5; +use bouncycastle_core::errors::SignatureError; +use bouncycastle_sha2::SHA256; + +/// An RSA-2048 private key (`p`, `q` each 1024 bits). +pub type Rsa2048PrivateKey = RsaPrivateKey<32, 16>; +/// An RSA-2048 public key. +pub type Rsa2048PublicKey = RsaPublicKey<32>; + +/// RSASSA-PKCS1-v1_5 (RFC 8017 §8.2) signing, `s = m^d mod n` over an EMSA-PKCS1-v1_5/SHA-256 +/// encoded message. See [`rsassa_pkcs1_v1_5::sign`] for what each error means. +pub fn pkcs1_v1_5_sign_sha256( + sk: &Rsa2048PrivateKey, + message: &[u8], +) -> Result<[u8; 256], SignatureError> { + rsassa_pkcs1_v1_5::sign::(sk, message) +} + +/// RSASSA-PKCS1-v1_5 (RFC 8017 §8.2) verification against a SHA-256 digest. See +/// [`rsassa_pkcs1_v1_5::verify`] for what each error means. +pub fn pkcs1_v1_5_verify_sha256( + pk: &Rsa2048PublicKey, + message: &[u8], + signature: &[u8; 256], +) -> Result<(), SignatureError> { + rsassa_pkcs1_v1_5::verify::(pk, message, signature) +} diff --git a/crypto/rsa/src/rsa_core.rs b/crypto/rsa/src/rsa_core.rs index 413177ea..4a081456 100644 --- a/crypto/rsa/src/rsa_core.rs +++ b/crypto/rsa/src/rsa_core.rs @@ -11,7 +11,7 @@ //! multi-prime RSA, so there is nothing here to extend to `u > 2`. use crate::keys::{RsaPrivateKey, RsaPublicKey}; -use crate::modexp::{MontgomeryContext, mod_pow, mul_mod, reduce_once, reduce_wide, sub_mod}; +use crate::modexp::{MontgomeryContext, mod_pow, mul_mod, reduce_wide, sub_mod}; use bouncycastle_core::errors::SignatureError; use bouncycastle_ec::montgomery; use bouncycastle_ec::nat; @@ -73,10 +73,13 @@ pub(crate) fn rsasp1< let s1 = mod_pow::(&m_mod_p, sk.d_p(), &ctx_p); let s2 = mod_pow::(&m_mod_q, sk.d_q(), &ctx_q); - // Step 2.b.3: `h = (s1 - s2) * qInv mod p`. `s2 < q`, and `q < 2p` because - // `RsaPrivateKey::from_crt_components` requires `p` and `q` to be the same bit length (see - // that type's docs), so one constant-time conditional subtraction reduces it mod `p`. - let s2_mod_p = reduce_once::(&s2, sk.p()); + // Step 2.b.3: `h = (s1 - s2) * qInv mod p`, which needs `s2` reduced mod `p` first. RFC 8017 + // does not require `p` and `q` to be close in magnitude (only that both are the modulus's two + // prime factors), so `s2 < q` gives no useful bound relative to `p` in general -- see + // `RsaPrivateKey`'s docs. `reduce_wide` (built for exactly this: reducing a value wider than + // its target modulus, constant-time in that modulus) handles the general case; it does not + // require its first width to exceed its second. + let s2_mod_p = reduce_wide::(&s2, sk.p()); let diff = sub_mod::(&s1, &s2_mod_p, sk.p()); let h = mul_mod::(&diff, sk.q_inv(), &ctx_p); 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..f2982030 --- /dev/null +++ b/crypto/rsa/src/rsassa_pkcs1_v1_5.rs @@ -0,0 +1,76 @@ +//! RSASSA-PKCS1-v1_5 (RFC 8017 §8.2): sign and verify, built on [`crate::rsa_core`]'s +//! RSASP1/RSAVP1 and [`crate::emsa_pkcs1_v1_5`]'s deterministic encoding. Generic over every +//! width this crate's arithmetic needs (`L`/`L2`/`L21` for the modulus, `HALF`/`HALF2`/`HALF21` +//! for each CRT prime, `K_LEN = 8 * L` for the encoded message/signature byte length) and over +//! the hash function `H` (`H_LEN`/`T_LEN` sized to it) -- a concrete modulus size wires these to +//! literals (e.g. RSA-2048/SHA-256 in [`crate::rsa_2048`]) rather than a caller choosing them. + +use crate::codec::{be_bytes_from_limbs, limbs_from_be_bytes}; +use crate::emsa_pkcs1_v1_5::{emsa_pkcs1_v1_5_encode, emsa_pkcs1_v1_5_verify}; +use crate::keys::{RsaPrivateKey, RsaPublicKey}; +use crate::rsa_core::{rsasp1, rsavp1}; +use bouncycastle_core::errors::SignatureError; +use bouncycastle_core::traits::{AlgorithmOID, Hash, HashAlgParams}; + +/// RSASSA-PKCS1-V1_5-SIGN (RFC 8017 §8.2.1): `S = I2OSP(RSASP1(K, OS2IP(EM)), k)`, where +/// `EM = EMSA-PKCS1-V1_5-ENCODE(M, k)`. Step 1's two errors ("message too long" -- unreachable +/// here, since [`emsa_pkcs1_v1_5_encode`]'s own length is fixed at compile time by `K_LEN`, never +/// computed from `message`'s length -- and "RSA modulus too short") are folded into +/// [`emsa_pkcs1_v1_5_encode`]'s `debug_assert`, not raised here as a runtime error, for the same +/// reason given there. +pub fn sign< + H: Hash + HashAlgParams + AlgorithmOID + Default, + const H_LEN: usize, + const T_LEN: usize, + const L: usize, + const L2: usize, + const L21: usize, + const HALF: usize, + const HALF2: usize, + const HALF21: usize, + const K_LEN: usize, +>( + sk: &RsaPrivateKey, + message: &[u8], +) -> Result<[u8; K_LEN], SignatureError> { + let em = emsa_pkcs1_v1_5_encode::(message); + let m = limbs_from_be_bytes::(&em); + let s = rsasp1::(sk, &m)?; + Ok(be_bytes_from_limbs::(&s)) +} + +/// RSASSA-PKCS1-V1_5-VERIFY (RFC 8017 §8.2.2): recovers `EM' = I2OSP(RSAVP1((n, e), OS2IP(S)), +/// k)` and checks it against `message` via [`emsa_pkcs1_v1_5_verify`] -- a decode, not RFC 8017's +/// own step 4 (re-encode `message` and compare bytes to `EM'`), because a byte comparison against +/// this crate's own (always-`NULL`-including) encoding would reject an otherwise-valid signature +/// whose `DigestInfo` omits the `AlgorithmIdentifier`'s `NULL` parameters -- a real-world +/// leniency [`emsa_pkcs1_v1_5_verify`]'s docs explain. Step 1's length check (`S` must be exactly +/// `k` octets) doesn't apply: `signature` is already a fixed `K_LEN`-byte array, not an +/// arbitrary-length octet string, so a wrong length is a compile-time type error at the call site +/// instead. Step 2's "signature representative out of range" surfaces as [`rsavp1`]'s own `Err`, +/// propagated directly rather than folded into "invalid signature": a caller working through +/// CAVP/wycheproof-style vectors needs to tell "malformed input" apart from "well-formed but +/// wrong", the same distinction RFC 8017 itself draws by giving the range check its own error +/// text. +pub fn verify< + H: Hash + HashAlgParams + AlgorithmOID + Default, + const H_LEN: usize, + const L: usize, + const L2: usize, + const L21: usize, + const K_LEN: usize, +>( + pk: &RsaPublicKey, + message: &[u8], + signature: &[u8; K_LEN], +) -> Result<(), SignatureError> { + let s = limbs_from_be_bytes::(signature); + let m = rsavp1::(pk, &s)?; + let em_prime = be_bytes_from_limbs::(&m); + + if emsa_pkcs1_v1_5_verify::(message, &em_prime) { + Ok(()) + } else { + Err(SignatureError::SignatureVerificationFailed) + } +} diff --git a/crypto/rsa/tests/keys_tests.rs b/crypto/rsa/tests/keys_tests.rs index f7bfc3bb..af53a842 100644 --- a/crypto/rsa/tests/keys_tests.rs +++ b/crypto/rsa/tests/keys_tests.rs @@ -68,11 +68,6 @@ fn from_crt_components_rejects_equal_primes() { )); } -/// Trivially `< ` any nonzero `HALF`-limb prime, real or shrunk by a test -- used below to keep -/// a test isolated to the one condition it names, instead of also (accidentally) tripping the -/// separate `dP`/`dQ`/`qInv` range checks that come after it. -const SMALL: [u64; 16] = [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]; - #[test] fn from_crt_components_rejects_even_prime() { let mut even_p = P; @@ -93,32 +88,6 @@ fn from_crt_components_rejects_even_q() { )); } -#[test] -fn from_crt_components_rejects_short_prime() { - // Clearing the top bit makes p occupy fewer than HALF * 64 bits, violating the - // equal-bit-length invariant CRT recombination depends on. dP/qInv are replaced with a - // trivially-in-range value so this test isolates the bit-length check: the real D_P/Q_INV - // are close to p's own magnitude, so against a p shrunk by half they would (correctly, but - // for the wrong reason from this test's point of view) also fail the later dP/qInv range - // checks. - let mut short_p = P; - short_p[15] &= !(1u64 << 63); - assert!(matches!( - RsaPrivateKey::<32, 16>::from_crt_components(&short_p, &Q, &SMALL, &D_Q, &SMALL), - Err(SignatureError::DecodingError(_)) - )); -} - -#[test] -fn from_crt_components_rejects_short_q() { - let mut short_q = Q; - short_q[15] &= !(1u64 << 63); - assert!(matches!( - RsaPrivateKey::<32, 16>::from_crt_components(&P, &short_q, &D_P, &SMALL, &SMALL), - Err(SignatureError::DecodingError(_)) - )); -} - #[test] fn from_crt_components_rejects_dp_out_of_range() { assert!(matches!( diff --git a/crypto/rsa/tests/modexp_tests.rs b/crypto/rsa/tests/modexp_tests.rs index 3edff01c..ec659170 100644 --- a/crypto/rsa/tests/modexp_tests.rs +++ b/crypto/rsa/tests/modexp_tests.rs @@ -4,7 +4,9 @@ //! (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}; +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, @@ -158,3 +160,51 @@ 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_2048_pkcs1_v1_5_tests.rs b/crypto/rsa/tests/rsa_2048_pkcs1_v1_5_tests.rs new file mode 100644 index 00000000..7b8f3334 --- /dev/null +++ b/crypto/rsa/tests/rsa_2048_pkcs1_v1_5_tests.rs @@ -0,0 +1,217 @@ +//! 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_hex::decode as hex_decode; +use bouncycastle_rsa::rsa_2048::{ + Rsa2048PrivateKey, Rsa2048PublicKey, pkcs1_v1_5_sign_sha256, pkcs1_v1_5_verify_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() -> Rsa2048PrivateKey { + // 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, + ]; + Rsa2048PrivateKey::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 = pkcs1_v1_5_sign_sha256(&sk, &msg).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 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_missing_null = 0usize; + + for group in doc["testGroups"].as_array().unwrap() { + assert_eq!(group["sha"], "SHA-256"); + 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 = Rsa2048PublicKey::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(); + + // A signature of the wrong length cannot even be represented as this crate's fixed + // [u8; 256] type; that is itself correct rejection (RFC 8017 SS8.2.2 step 1). + 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 = pkcs1_v1_5_verify_sha256(&pk, &msg, &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; + } + "acceptable" => { + // The only "acceptable" verdict in this file is MissingNull (RFC 8017's + // AlgorithmIdentifier `parameters` field omitted rather than NULL); per this + // crate's explicit policy (see `emsa_pkcs1_v1_5::emsa_pkcs1_v1_5_verify`'s + // docs), that is accepted, not merely tolerated either way. Any other + // "acceptable" flag combination is an unreviewed case, not silently ignored. + 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, 259, "expected 257 + 1 + 1 tests across all three groups"); + assert_eq!(num_missing_null, 1); + assert_eq!(num_valid, 9); + assert_eq!(num_invalid, 249); +} From 9175cb940fc3ecc049245a8c08b1c0878564a9a5 Mon Sep 17 00:00:00 2001 From: David Hook Date: Sat, 19 Sep 2026 20:07:53 +1000 Subject: [PATCH 05/55] rsa: RSASSA-PSS sign/verify for RSA-2048/SHA-256 Adds the second vertical slice: mgf1.rs (RFC 8017 Appendix B.2.1), emsa_pss.rs (SS9.1 encode/decode), rsassa_pss.rs (SS8.1 orchestration), and RSA-2048/SHA-256/MGF1-SHA-256/32-byte-salt wiring in rsa_2048.rs. emsa_pss.rs hard-codes "clear the top bit of EM's first octet" rather than threading RFC 8017's generic 8*emLen - emBits bit-count through: every modulus size this crate offers is a whole number of 64-bit limbs, so modBits is always a multiple of 8 and that count is always exactly 1. Documented inline rather than left implicit, since it's a real narrowing of the spec's generality that only holds because of this crate's own fixed-width design. Signing draws its salt from an RNG (bouncycastle-rng, matching the DefaultRNG::default() pattern bouncycastle-sm2's keygen already uses), via a sign/sign_with_salt split: sign_with_salt stays deterministic given a salt, so it -- and emsa_pss_encode/verify underneath it -- can be tested directly against known values instead of only through randomized end-to-end round trips. Validated against all 108 real vectors in Wycheproof's rsa_pss_2048_sha256_mgf1_32_test.json (63 valid/45 invalid, using the same genuine key recovered in the previous commit), plus self-consistency round trips both with a fixed salt (deterministic, checked twice for repeatability) and via DefaultRNG (confirming two signatures of the same message differ but both verify). mgf1 and emsa_pss also have their own KATs, direct Python transliterations of RFC 8017's own steps rather than values taken from recall. Mutation testing for this slice is deferred to a consolidated pass across the whole crate at the end of the RSA work, rather than per-commit: the crate's mutant count has grown enough (230 -> 311) that each run now re-executes the full Wycheproof-backed test suite (debug-build modexp is exponent-oblivious by design, so every verify call pays the same cost as a full constant-time signing operation), pushing a single mutants pass past several hours. Co-Authored-By: Claude Sonnet 5 --- crypto/rsa/src/emsa_pss.rs | 243 +++++++++++++++++++++++++ crypto/rsa/src/lib.rs | 22 ++- crypto/rsa/src/mgf1.rs | 91 +++++++++ crypto/rsa/src/rsa_2048.rs | 47 ++++- crypto/rsa/src/rsassa_pss.rs | 112 ++++++++++++ crypto/rsa/tests/rsa_2048_pss_tests.rs | 170 +++++++++++++++++ 6 files changed, 676 insertions(+), 9 deletions(-) create mode 100644 crypto/rsa/src/emsa_pss.rs create mode 100644 crypto/rsa/src/mgf1.rs create mode 100644 crypto/rsa/src/rsassa_pss.rs create mode 100644 crypto/rsa/tests/rsa_2048_pss_tests.rs diff --git a/crypto/rsa/src/emsa_pss.rs b/crypto/rsa/src/emsa_pss.rs new file mode 100644 index 00000000..3fe2c91c --- /dev/null +++ b/crypto/rsa/src/emsa_pss.rs @@ -0,0 +1,243 @@ +//! EMSA-PSS (RFC 8017 §9.1): probabilistic signature encoding, built on [`crate::mgf1`]. +//! +//! # 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::mgf1; +use bouncycastle_core::traits::Hash; + +/// EMSA-PSS-ENCODE (RFC 8017 §9.1.1), with `emBits` fixed to `8 * K_LEN - 1` (see the module +/// docs) and the salt supplied by the caller 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. +pub fn emsa_pss_encode< + H: Hash + Default, + const H_LEN: usize, + const SEED_LEN: usize, + const S_LEN: usize, + const M_PRIME_LEN: usize, + const DB_LEN: usize, + const K_LEN: usize, +>( + message: &[u8], + salt: &[u8; S_LEN], +) -> [u8; K_LEN] { + debug_assert_eq!(M_PRIME_LEN, 8 + H_LEN + S_LEN, "emsa_pss_encode: M_PRIME_LEN mismatch"); + debug_assert_eq!(DB_LEN, K_LEN - H_LEN - 1, "emsa_pss_encode: DB_LEN mismatch"); + debug_assert!( + K_LEN >= H_LEN + S_LEN + 2, + "emsa_pss_encode: modulus too short for this hash/salt" + ); + + // Steps 1-2: mHash = Hash(M). + let mut m_hash = [0u8; H_LEN]; + H::default().hash_out(message, &mut m_hash); + + // Steps 5-6: M' = 8 zero octets || mHash || salt; H = Hash(M'). + let mut m_prime = [0u8; M_PRIME_LEN]; + m_prime[8..8 + H_LEN].copy_from_slice(&m_hash); + m_prime[8 + H_LEN..].copy_from_slice(salt); + let mut h = [0u8; H_LEN]; + H::default().hash_out(&m_prime, &mut h); + + // Steps 7-8: DB = PS || 0x01 || salt (PS is all-zero, already the array's initial value). + let mut db = [0u8; DB_LEN]; + db[DB_LEN - S_LEN - 1] = 0x01; + db[DB_LEN - S_LEN..].copy_from_slice(salt); + + // Steps 9-11: maskedDB = DB xor MGF(H, DB_LEN), then clear the top bit (see module docs). + let db_mask: [u8; DB_LEN] = mgf1::(&h); + let mut masked_db = [0u8; DB_LEN]; + for i in 0..DB_LEN { + masked_db[i] = db[i] ^ db_mask[i]; + } + masked_db[0] &= 0x7f; + + // Step 12: EM = maskedDB || H || 0xbc. + let mut em = [0u8; K_LEN]; + em[..DB_LEN].copy_from_slice(&masked_db); + em[DB_LEN..DB_LEN + H_LEN].copy_from_slice(&h); + em[K_LEN - 1] = 0xbc; + em +} + +/// EMSA-PSS-VERIFY (RFC 8017 §9.1.2), with `emBits` fixed as [`emsa_pss_encode`]'s is. Step 1's +/// message-length limit and step 3's minimum-`emLen` check are not reachable for this crate's +/// fixed sizes, for the same reasons given there. +pub fn emsa_pss_verify< + H: Hash + Default, + const H_LEN: usize, + const SEED_LEN: usize, + const S_LEN: usize, + const M_PRIME_LEN: usize, + const DB_LEN: usize, + const K_LEN: usize, +>( + message: &[u8], + em: &[u8; K_LEN], +) -> bool { + // 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 mut masked_db = [0u8; DB_LEN]; + masked_db.copy_from_slice(&em[..DB_LEN]); + let mut h = [0u8; H_LEN]; + h.copy_from_slice(&em[DB_LEN..DB_LEN + H_LEN]); + + // Steps 7-9. + let db_mask: [u8; DB_LEN] = mgf1::(&h); + let mut db = [0u8; DB_LEN]; + for i in 0..DB_LEN { + db[i] = masked_db[i] ^ db_mask[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 mut salt = [0u8; S_LEN]; + salt.copy_from_slice(&db[DB_LEN - S_LEN..]); + + // Steps 12-14. + let mut m_hash = [0u8; H_LEN]; + H::default().hash_out(message, &mut m_hash); + let mut m_prime = [0u8; M_PRIME_LEN]; + m_prime[8..8 + H_LEN].copy_from_slice(&m_hash); + m_prime[8 + H_LEN..].copy_from_slice(&salt); + let mut h_prime = [0u8; H_LEN]; + H::default().hash_out(&m_prime, &mut h_prime); + + h == h_prime +} + +#[cfg(test)] +mod tests { + //! `emsa_pss_encode`/`emsa_pss_verify` 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. + + use super::*; + use bouncycastle_sha2::SHA256; + + 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 encode(message: &[u8], salt: &[u8; 32]) -> [u8; 256] { + emsa_pss_encode::(message, salt) + } + + fn verify(message: &[u8], em: &[u8; 256]) -> bool { + emsa_pss_verify::(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)); + } +} diff --git a/crypto/rsa/src/lib.rs b/crypto/rsa/src/lib.rs index bc8b320e..c354c497 100644 --- a/crypto/rsa/src/lib.rs +++ b/crypto/rsa/src/lib.rs @@ -33,6 +33,18 @@ //! //! // A signature does not verify against a different message. //! assert!(pkcs1_v1_5_verify_sha256(&pk, b"a different message", &signature).is_err()); +//! +//! // RSASSA-PSS is randomized (a fresh salt each time), so two signatures of the same message +//! // differ, but both verify. +//! use bouncycastle_rsa::rsa_2048::{pss_sign_sha256, pss_verify_sha256}; +//! use bouncycastle_rng::DefaultRNG; +//! +//! let mut rng = DefaultRNG::default(); +//! let sig_a = pss_sign_sha256(&sk, b"the message to sign", &mut rng)?; +//! let sig_b = pss_sign_sha256(&sk, b"the message to sign", &mut rng)?; +//! assert_ne!(sig_a, sig_b); +//! pss_verify_sha256(&pk, b"the message to sign", &sig_a)?; +//! pss_verify_sha256(&pk, b"the message to sign", &sig_b)?; //! # Ok::<(), bouncycastle_core::errors::SignatureError>(()) //! ``` //! @@ -40,10 +52,9 @@ //! //! [`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`), -//! and RSASSA-PKCS1-v1_5 ([`rsassa_pkcs1_v1_5`], wired up for RSA-2048/SHA-256 in [`rsa_2048`]) -//! are implemented, validated against genuine Wycheproof RSA-2048/SHA-256 vectors (both -//! `rsa_pkcs1_2048_sig_gen_test.json` and `rsa_signature_2048_sha256_test.json`). RSASSA-PSS, -//! the remaining modulus sizes, and the remaining hash functions are not yet. +//! RSASSA-PKCS1-v1_5 ([`rsassa_pkcs1_v1_5`]), and RSASSA-PSS ([`rsassa_pss`]) are implemented, +//! both wired up for RSA-2048/SHA-256 in [`rsa_2048`] and validated against genuine Wycheproof +//! vectors. The remaining modulus sizes and the remaining hash functions are not yet. #![no_std] #![forbid(unsafe_code)] @@ -51,8 +62,11 @@ mod codec; mod emsa_pkcs1_v1_5; +mod emsa_pss; pub mod keys; +mod mgf1; pub mod modexp; pub mod rsa_2048; mod rsa_core; pub mod rsassa_pkcs1_v1_5; +pub mod rsassa_pss; diff --git a/crypto/rsa/src/mgf1.rs b/crypto/rsa/src/mgf1.rs new file mode 100644 index 00000000..69e29d17 --- /dev/null +++ b/crypto/rsa/src/mgf1.rs @@ -0,0 +1,91 @@ +//! MGF1 (RFC 8017 Appendix B.2.1): a mask generation function based on a hash function, used by +//! [`crate::emsa_pss`]. Specialized to PSS's own call shape (`MGF(H, maskLen)`, where `H` is +//! always the hash's own `hLen`-byte output) rather than MGF1's fully general arbitrary-length +//! seed: `mgfSeed` here is always exactly `H_LEN` bytes. + +use bouncycastle_core::traits::Hash; + +/// 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. +pub fn mgf1( + seed: &[u8; H_LEN], +) -> [u8; MASK_LEN] { + debug_assert_eq!(SEED_LEN, H_LEN + 4, "mgf1 needs SEED_LEN == H_LEN + 4"); + + let mut mask = [0u8; MASK_LEN]; + let mut offset = 0; + let mut counter: u32 = 0; + while offset < MASK_LEN { + let mut input = [0u8; SEED_LEN]; + input[..H_LEN].copy_from_slice(seed); + input[H_LEN..].copy_from_slice(&counter.to_be_bytes()); + + let mut block = [0u8; H_LEN]; + H::default().hash_out(&input, &mut block); + + let take = core::cmp::min(H_LEN, MASK_LEN - offset); + mask[offset..offset + take].copy_from_slice(&block[..take]); + offset += take; + counter += 1; + } + mask +} + +#[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, + ]; + + /// `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 mask: [u8; 223] = mgf1::(&SEED); + 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 mask: [u8; 10] = mgf1::(&SEED); + 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 longer: [u8; 223] = mgf1::(&SEED); + 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 mask: [u8; 70] = mgf1::(&SEED); + let longer: [u8; 223] = mgf1::(&SEED); + assert_eq!(mask, longer[..70]); + } +} diff --git a/crypto/rsa/src/rsa_2048.rs b/crypto/rsa/src/rsa_2048.rs index 449c3ec5..ba480560 100644 --- a/crypto/rsa/src/rsa_2048.rs +++ b/crypto/rsa/src/rsa_2048.rs @@ -1,12 +1,16 @@ -//! RSA-2048: the generic engine ([`crate::modexp`], [`crate::rsa_core`], [`crate::rsassa_pkcs1_v1_5`]) -//! wired to concrete widths -- `L = 32` (2048 bits), `HALF = 16` (1024-bit CRT primes) -- so a -//! caller using this size doesn't thread six const-generic width parameters through every call. -//! One file per modulus size, matching [`crate::keys::RsaPrivateKey`]'s own `` shape; -//! `rsa_1024`/`rsa_3072`/`rsa_4096`/`rsa_8192` are the same pattern at their own widths. +//! RSA-2048: the generic engine ([`crate::modexp`], [`crate::rsa_core`], [`crate::rsassa_pkcs1_v1_5`], +//! [`crate::rsassa_pss`]) wired to concrete widths -- `L = 32` (2048 bits), `HALF = 16` (1024-bit +//! CRT primes) -- so a caller using this size doesn't thread const-generic width parameters +//! through every call. One file per modulus size, matching [`crate::keys::RsaPrivateKey`]'s own +//! `` shape; `rsa_1024`/`rsa_3072`/`rsa_4096`/`rsa_8192` are the same pattern at their +//! own widths. PSS's salt length is fixed to 32 bytes (`H_LEN` for SHA-256), matching RFC 8017 +//! §9.1 note 4's "typical" choice and Wycheproof's own `rsa_pss_2048_sha256_mgf1_32_test.json`. use crate::keys::{RsaPrivateKey, RsaPublicKey}; use crate::rsassa_pkcs1_v1_5; +use crate::rsassa_pss; use bouncycastle_core::errors::SignatureError; +use bouncycastle_core::traits::RNG; use bouncycastle_sha2::SHA256; /// An RSA-2048 private key (`p`, `q` each 1024 bits). @@ -32,3 +36,36 @@ pub fn pkcs1_v1_5_verify_sha256( ) -> Result<(), SignatureError> { rsassa_pkcs1_v1_5::verify::(pk, message, signature) } + +/// RSASSA-PSS (RFC 8017 §8.1) signing with SHA-256 (both as the message hash and, per §8.1's own +/// recommendation, as MGF1's hash) and a 32-byte salt drawn fresh from `rng` for each signature. +/// See [`rsassa_pss::sign`] for what each error means. +pub fn pss_sign_sha256( + sk: &Rsa2048PrivateKey, + message: &[u8], + rng: &mut dyn RNG, +) -> Result<[u8; 256], SignatureError> { + rsassa_pss::sign::(sk, message, rng) +} + +/// As [`pss_sign_sha256`], but with the salt supplied directly instead of drawn from an RNG -- +/// deterministic, for testing against a known salt. See [`rsassa_pss::sign_with_salt`]. +pub fn pss_sign_sha256_with_salt( + sk: &Rsa2048PrivateKey, + message: &[u8], + salt: &[u8; 32], +) -> Result<[u8; 256], SignatureError> { + rsassa_pss::sign_with_salt::( + sk, message, salt, + ) +} + +/// RSASSA-PSS (RFC 8017 §8.1) verification against a SHA-256/MGF1-SHA-256/32-byte-salt encoding. +/// See [`rsassa_pss::verify`] for what each error means. +pub fn pss_verify_sha256( + pk: &Rsa2048PublicKey, + message: &[u8], + signature: &[u8; 256], +) -> Result<(), SignatureError> { + rsassa_pss::verify::(pk, message, signature) +} diff --git a/crypto/rsa/src/rsassa_pss.rs b/crypto/rsa/src/rsassa_pss.rs new file mode 100644 index 00000000..f69f9565 --- /dev/null +++ b/crypto/rsa/src/rsassa_pss.rs @@ -0,0 +1,112 @@ +//! RSASSA-PSS (RFC 8017 §8.1): sign and verify, built on [`crate::rsa_core`]'s RSASP1/RSAVP1 and +//! [`crate::emsa_pss`]'s probabilistic encoding. Generic over the same width parameters as +//! [`crate::rsassa_pkcs1_v1_5`] plus PSS's own `S_LEN` (salt length) and `M_PRIME_LEN` +//! (`8 + H_LEN + S_LEN`); a concrete modulus size wires these to literals (RSA-2048/SHA-256 in +//! [`crate::rsa_2048`]). + +use crate::codec::{be_bytes_from_limbs, limbs_from_be_bytes}; +use crate::emsa_pss::{emsa_pss_encode, emsa_pss_verify}; +use crate::keys::{RsaPrivateKey, RsaPublicKey}; +use crate::rsa_core::{rsasp1, rsavp1}; +use bouncycastle_core::errors::SignatureError; +use bouncycastle_core::traits::{Hash, RNG}; + +/// RSASSA-PSS-SIGN (RFC 8017 §8.1.1) with the salt supplied directly rather than drawn from an +/// RNG: EMSA-PSS is randomized only in its choice of salt (§9.1's own note 5), so fixing it makes +/// this deterministic and directly testable against a known salt. [`sign`] is the RNG-backed +/// entry point real callers want. +pub fn sign_with_salt< + H: Hash + Default, + const H_LEN: usize, + const SEED_LEN: usize, + const S_LEN: usize, + const M_PRIME_LEN: usize, + const DB_LEN: usize, + const L: usize, + const L2: usize, + const L21: usize, + const HALF: usize, + const HALF2: usize, + const HALF21: usize, + const K_LEN: usize, +>( + sk: &RsaPrivateKey, + message: &[u8], + salt: &[u8; S_LEN], +) -> Result<[u8; K_LEN], SignatureError> { + let em = + emsa_pss_encode::(message, salt); + let m = limbs_from_be_bytes::(&em); + let s = rsasp1::(sk, &m)?; + Ok(be_bytes_from_limbs::(&s)) +} + +/// RSASSA-PSS-SIGN (RFC 8017 §8.1.1), drawing a fresh `S_LEN`-byte salt from `rng` for each +/// signature (step 4 of EMSA-PSS-ENCODE). +pub fn sign< + H: Hash + Default, + const H_LEN: usize, + const SEED_LEN: usize, + const S_LEN: usize, + const M_PRIME_LEN: usize, + const DB_LEN: usize, + const L: usize, + const L2: usize, + const L21: usize, + const HALF: usize, + const HALF2: usize, + const HALF21: usize, + const K_LEN: usize, +>( + sk: &RsaPrivateKey, + message: &[u8], + rng: &mut dyn RNG, +) -> Result<[u8; K_LEN], SignatureError> { + let mut salt = [0u8; S_LEN]; + rng.next_bytes_out(&mut salt).map_err(SignatureError::RNGError)?; + sign_with_salt::< + H, + H_LEN, + SEED_LEN, + S_LEN, + M_PRIME_LEN, + DB_LEN, + L, + L2, + L21, + HALF, + HALF2, + HALF21, + K_LEN, + >(sk, message, &salt) +} + +/// RSASSA-PSS-VERIFY (RFC 8017 §8.1.2): recovers `EM = I2OSP(RSAVP1((n, e), OS2IP(S)), emLen)` +/// and checks it against `message` via [`emsa_pss_verify`], which recovers the salt from `EM` +/// itself (EMSA-PSS's own verification operation, §9.1.2) rather than needing it supplied. +pub fn verify< + H: Hash + Default, + const H_LEN: usize, + const SEED_LEN: usize, + const S_LEN: usize, + const M_PRIME_LEN: usize, + const DB_LEN: usize, + const L: usize, + const L2: usize, + const L21: usize, + const K_LEN: usize, +>( + pk: &RsaPublicKey, + message: &[u8], + signature: &[u8; K_LEN], +) -> Result<(), SignatureError> { + let s = limbs_from_be_bytes::(signature); + let m = rsavp1::(pk, &s)?; + let em = be_bytes_from_limbs::(&m); + + if emsa_pss_verify::(message, &em) { + Ok(()) + } else { + Err(SignatureError::SignatureVerificationFailed) + } +} 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..9f626e90 --- /dev/null +++ b/crypto/rsa/tests/rsa_2048_pss_tests.rs @@ -0,0 +1,170 @@ +//! 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_hex::decode as hex_decode; +use bouncycastle_rng::DefaultRNG; +use bouncycastle_rsa::rsa_2048::{ + Rsa2048PrivateKey, Rsa2048PublicKey, pss_sign_sha256, pss_sign_sha256_with_salt, + pss_verify_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" + ); +} + +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() -> Rsa2048PrivateKey { + 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, + ]; + Rsa2048PrivateKey::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 = Rsa2048PublicKey::new(sk.n(), 0x10001).unwrap(); + + let salt = [0x42u8; 32]; + let sig = pss_sign_sha256_with_salt(&sk, b"the message to sign", &salt) + .expect("signing must succeed"); + pss_verify_sha256(&pk, b"the message to sign", &sig).expect("must verify"); + + // Deterministic given the same salt. + let sig2 = pss_sign_sha256_with_salt(&sk, b"the message to sign", &salt).unwrap(); + assert_eq!(sig, sig2); + + assert!(pss_verify_sha256(&pk, b"a different message", &sig).is_err()); +} + +#[test] +fn pss_sign_with_rng_produces_fresh_salts_that_both_verify() { + let sk = wycheproof_key(); + let pk = Rsa2048PublicKey::new(sk.n(), 0x10001).unwrap(); + let mut rng = DefaultRNG::default(); + + let sig_a = pss_sign_sha256(&sk, b"hello", &mut rng).expect("signing must succeed"); + let sig_b = pss_sign_sha256(&sk, b"hello", &mut rng).expect("signing must succeed"); + assert_ne!(sig_a, sig_b, "PSS is randomized: two signatures of the same message must differ"); + pss_verify_sha256(&pk, b"hello", &sig_a).expect("sig_a must verify"); + pss_verify_sha256(&pk, b"hello", &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 = Rsa2048PublicKey::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 = pss_verify_sha256(&pk, &msg, &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); +} From 921f65eeca3462f6c3c63effc769e86310e23381 Mon Sep 17 00:00:00 2001 From: David Hook Date: Sat, 19 Sep 2026 20:15:12 +1000 Subject: [PATCH 06/55] rsa: SHA-384 and SHA-512 for RSA-2048 (PKCS#1 v1.5 and PSS) Wires up the remaining hash choices step 4/5's generic engine already supports without any change to it: pkcs1_v1_5_sign/verify_sha384/512 and pss_sign/verify_sha384/512 in rsa_2048.rs, with PSS's salt length fixed to each hash's own output length (48/64 bytes) as before. Each of Wycheproof's rsa_pkcs1_2048_sig_gen_test.json groups (including its SHA-384/SHA-512 ones) uses a distinct key, so there is no shared sig-gen key to recover and reuse the way SHA-256's was. Factoring separate keys per hash would not exercise anything the SHA-256 slice hasn't already: EMSA-PKCS1-v1_5/EMSA-PSS's hash handling is generic (digest_info built from AlgorithmOID::OID_DER regardless of which hash), and RSASP1/RSAVP1 don't depend on which hash produced the message representative. So the sign side here is a self-consistency round trip reusing the existing genuine key, while the verify side -- where a wrong OID or digest length for the hash in question is the real risk -- is checked against Wycheproof's real vectors for both hashes: rsa_signature_2048_sha384_test.json (258 vectors) and rsa_signature_2048_sha512_test.json (259 vectors), each including its own MissingNull acceptable case. rsa_pss_2048_sha384_mgf1_48_test.json (141 vectors) covers PSS/SHA-384 the same way; no matching-hash-and-MGF PSS vector file exists for plain SHA-512 in this checkout (only the SHA-512/224, SHA-512/256, and mixed-MGF variants), so PSS/SHA-512 is self-consistency only. Mutation testing remains deferred to a single consolidated pass across the whole crate once every planned modulus size and hash is in, per direction given after step 5's mutants run projected past several hours. Co-Authored-By: Claude Sonnet 5 --- crypto/rsa/src/lib.rs | 4 +- crypto/rsa/src/rsa_2048.rs | 109 +++++++++- ...rsa_2048_pkcs1_v1_5_sha384_sha512_tests.rs | 200 ++++++++++++++++++ .../tests/rsa_2048_pss_sha384_sha512_tests.rs | 179 ++++++++++++++++ 4 files changed, 487 insertions(+), 5 deletions(-) create mode 100644 crypto/rsa/tests/rsa_2048_pkcs1_v1_5_sha384_sha512_tests.rs create mode 100644 crypto/rsa/tests/rsa_2048_pss_sha384_sha512_tests.rs diff --git a/crypto/rsa/src/lib.rs b/crypto/rsa/src/lib.rs index c354c497..ee4c2110 100644 --- a/crypto/rsa/src/lib.rs +++ b/crypto/rsa/src/lib.rs @@ -53,8 +53,8 @@ //! [`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, -//! both wired up for RSA-2048/SHA-256 in [`rsa_2048`] and validated against genuine Wycheproof -//! vectors. The remaining modulus sizes and the remaining hash functions are not yet. +//! wired up for RSA-2048 with SHA-256, SHA-384, and SHA-512 in [`rsa_2048`] and validated against +//! genuine Wycheproof vectors. The remaining modulus sizes are not yet. #![no_std] #![forbid(unsafe_code)] diff --git a/crypto/rsa/src/rsa_2048.rs b/crypto/rsa/src/rsa_2048.rs index ba480560..e733fc86 100644 --- a/crypto/rsa/src/rsa_2048.rs +++ b/crypto/rsa/src/rsa_2048.rs @@ -3,15 +3,16 @@ //! CRT primes) -- so a caller using this size doesn't thread const-generic width parameters //! through every call. One file per modulus size, matching [`crate::keys::RsaPrivateKey`]'s own //! `` shape; `rsa_1024`/`rsa_3072`/`rsa_4096`/`rsa_8192` are the same pattern at their -//! own widths. PSS's salt length is fixed to 32 bytes (`H_LEN` for SHA-256), matching RFC 8017 -//! §9.1 note 4's "typical" choice and Wycheproof's own `rsa_pss_2048_sha256_mgf1_32_test.json`. +//! own widths. PSS's salt length is fixed to each hash's own output length (`H_LEN`) throughout, +//! matching RFC 8017 §9.1 note 4's "typical" choice and Wycheproof's own +//! `rsa_pss_2048_sha256_mgf1_32_test.json`/`..._sha384_mgf1_48_test.json`. use crate::keys::{RsaPrivateKey, RsaPublicKey}; use crate::rsassa_pkcs1_v1_5; use crate::rsassa_pss; use bouncycastle_core::errors::SignatureError; use bouncycastle_core::traits::RNG; -use bouncycastle_sha2::SHA256; +use bouncycastle_sha2::{SHA256, SHA384, SHA512}; /// An RSA-2048 private key (`p`, `q` each 1024 bits). pub type Rsa2048PrivateKey = RsaPrivateKey<32, 16>; @@ -69,3 +70,105 @@ pub fn pss_verify_sha256( ) -> Result<(), SignatureError> { rsassa_pss::verify::(pk, message, signature) } + +/// RSASSA-PKCS1-v1_5 (RFC 8017 §8.2) signing with SHA-384. See [`rsassa_pkcs1_v1_5::sign`] for +/// what each error means. +pub fn pkcs1_v1_5_sign_sha384( + sk: &Rsa2048PrivateKey, + message: &[u8], +) -> Result<[u8; 256], SignatureError> { + rsassa_pkcs1_v1_5::sign::(sk, message) +} + +/// RSASSA-PKCS1-v1_5 (RFC 8017 §8.2) verification against a SHA-384 digest. See +/// [`rsassa_pkcs1_v1_5::verify`] for what each error means. +pub fn pkcs1_v1_5_verify_sha384( + pk: &Rsa2048PublicKey, + message: &[u8], + signature: &[u8; 256], +) -> Result<(), SignatureError> { + rsassa_pkcs1_v1_5::verify::(pk, message, signature) +} + +/// RSASSA-PKCS1-v1_5 (RFC 8017 §8.2) signing with SHA-512. See [`rsassa_pkcs1_v1_5::sign`] for +/// what each error means. +pub fn pkcs1_v1_5_sign_sha512( + sk: &Rsa2048PrivateKey, + message: &[u8], +) -> Result<[u8; 256], SignatureError> { + rsassa_pkcs1_v1_5::sign::(sk, message) +} + +/// RSASSA-PKCS1-v1_5 (RFC 8017 §8.2) verification against a SHA-512 digest. See +/// [`rsassa_pkcs1_v1_5::verify`] for what each error means. +pub fn pkcs1_v1_5_verify_sha512( + pk: &Rsa2048PublicKey, + message: &[u8], + signature: &[u8; 256], +) -> Result<(), SignatureError> { + rsassa_pkcs1_v1_5::verify::(pk, message, signature) +} + +/// RSASSA-PSS (RFC 8017 §8.1) signing with SHA-384 (as both the message hash and MGF1's hash) +/// and a 48-byte salt drawn fresh from `rng`. See [`rsassa_pss::sign`] for what each error means. +pub fn pss_sign_sha384( + sk: &Rsa2048PrivateKey, + message: &[u8], + rng: &mut dyn RNG, +) -> Result<[u8; 256], SignatureError> { + rsassa_pss::sign::(sk, message, rng) +} + +/// As [`pss_sign_sha384`], but with the salt supplied directly instead of drawn from an RNG -- +/// deterministic, for testing against a known salt. See [`rsassa_pss::sign_with_salt`]. +pub fn pss_sign_sha384_with_salt( + sk: &Rsa2048PrivateKey, + message: &[u8], + salt: &[u8; 48], +) -> Result<[u8; 256], SignatureError> { + rsassa_pss::sign_with_salt::( + sk, message, salt, + ) +} + +/// RSASSA-PSS (RFC 8017 §8.1) verification against a SHA-384/MGF1-SHA-384/48-byte-salt encoding. +/// See [`rsassa_pss::verify`] for what each error means. +pub fn pss_verify_sha384( + pk: &Rsa2048PublicKey, + message: &[u8], + signature: &[u8; 256], +) -> Result<(), SignatureError> { + rsassa_pss::verify::(pk, message, signature) +} + +/// RSASSA-PSS (RFC 8017 §8.1) signing with SHA-512 (as both the message hash and MGF1's hash) +/// and a 64-byte salt drawn fresh from `rng`. See [`rsassa_pss::sign`] for what each error means. +pub fn pss_sign_sha512( + sk: &Rsa2048PrivateKey, + message: &[u8], + rng: &mut dyn RNG, +) -> Result<[u8; 256], SignatureError> { + rsassa_pss::sign::(sk, message, rng) +} + +/// As [`pss_sign_sha512`], but with the salt supplied directly instead of drawn from an RNG -- +/// deterministic, for testing against a known salt. See [`rsassa_pss::sign_with_salt`]. +pub fn pss_sign_sha512_with_salt( + sk: &Rsa2048PrivateKey, + message: &[u8], + salt: &[u8; 64], +) -> Result<[u8; 256], SignatureError> { + rsassa_pss::sign_with_salt::( + sk, message, salt, + ) +} + +/// RSASSA-PSS (RFC 8017 §8.1) verification against a SHA-512/MGF1-SHA-512/64-byte-salt encoding. +/// See [`rsassa_pss::verify`] for what each error means. +pub fn pss_verify_sha512( + pk: &Rsa2048PublicKey, + message: &[u8], + signature: &[u8; 256], +) -> Result<(), SignatureError> { + rsassa_pss::verify::(pk, message, signature) +} 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..3c76685b --- /dev/null +++ b/crypto/rsa/tests/rsa_2048_pkcs1_v1_5_sha384_sha512_tests.rs @@ -0,0 +1,200 @@ +//! 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_hex::decode as hex_decode; +use bouncycastle_rsa::rsa_2048::{ + Rsa2048PrivateKey, Rsa2048PublicKey, pkcs1_v1_5_sign_sha384, pkcs1_v1_5_sign_sha512, + pkcs1_v1_5_verify_sha384, pkcs1_v1_5_verify_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 +} + +/// 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() -> Rsa2048PrivateKey { + 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, + ]; + Rsa2048PrivateKey::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 = Rsa2048PublicKey::new(sk.n(), 0x10001).unwrap(); + let sig = pkcs1_v1_5_sign_sha384(&sk, b"hello").expect("signing must succeed"); + pkcs1_v1_5_verify_sha384(&pk, b"hello", &sig).expect("must verify"); + assert!(pkcs1_v1_5_verify_sha384(&pk, b"goodbye", &sig).is_err()); +} + +#[test] +fn pkcs1_v1_5_sha512_round_trips() { + let sk = genuine_key(); + let pk = Rsa2048PublicKey::new(sk.n(), 0x10001).unwrap(); + let sig = pkcs1_v1_5_sign_sha512(&sk, b"hello").expect("signing must succeed"); + pkcs1_v1_5_verify_sha512(&pk, b"hello", &sig).expect("must verify"); + assert!(pkcs1_v1_5_verify_sha512(&pk, b"goodbye", &sig).is_err()); +} + +fn run_verify_vectors( + filename: &str, + verify: impl Fn(&Rsa2048PublicKey, &[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 = Rsa2048PublicKey::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| pkcs1_v1_5_verify_sha384(pk, msg, 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| pkcs1_v1_5_verify_sha512(pk, msg, sig).is_ok(), + "SHA-512", + 259, + 8, + 250, + ); +} 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..44794170 --- /dev/null +++ b/crypto/rsa/tests/rsa_2048_pss_sha384_sha512_tests.rs @@ -0,0 +1,179 @@ +//! 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_hex::decode as hex_decode; +use bouncycastle_rng::DefaultRNG; +use bouncycastle_rsa::rsa_2048::{ + Rsa2048PrivateKey, Rsa2048PublicKey, pss_sign_sha384, pss_sign_sha384_with_salt, + pss_sign_sha512, pss_sign_sha512_with_salt, pss_verify_sha384, pss_verify_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 +} + +/// 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() -> Rsa2048PrivateKey { + 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, + ]; + Rsa2048PrivateKey::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 = Rsa2048PublicKey::new(sk.n(), 0x10001).unwrap(); + let salt = [0x42u8; 48]; + let sig = pss_sign_sha384_with_salt(&sk, b"hello", &salt).expect("signing must succeed"); + pss_verify_sha384(&pk, b"hello", &sig).expect("must verify"); + assert!(pss_verify_sha384(&pk, b"goodbye", &sig).is_err()); +} + +#[test] +fn pss_sha384_rng_produces_fresh_salts_that_both_verify() { + let sk = genuine_key(); + let pk = Rsa2048PublicKey::new(sk.n(), 0x10001).unwrap(); + let mut rng = DefaultRNG::default(); + let sig_a = pss_sign_sha384(&sk, b"hello", &mut rng).expect("signing must succeed"); + let sig_b = pss_sign_sha384(&sk, b"hello", &mut rng).expect("signing must succeed"); + assert_ne!(sig_a, sig_b); + pss_verify_sha384(&pk, b"hello", &sig_a).expect("sig_a must verify"); + pss_verify_sha384(&pk, b"hello", &sig_b).expect("sig_b must verify"); +} + +#[test] +fn pss_sha512_fixed_salt_round_trips() { + let sk = genuine_key(); + let pk = Rsa2048PublicKey::new(sk.n(), 0x10001).unwrap(); + let salt = [0x42u8; 64]; + let sig = pss_sign_sha512_with_salt(&sk, b"hello", &salt).expect("signing must succeed"); + pss_verify_sha512(&pk, b"hello", &sig).expect("must verify"); + assert!(pss_verify_sha512(&pk, b"goodbye", &sig).is_err()); +} + +#[test] +fn pss_sha512_rng_produces_fresh_salts_that_both_verify() { + let sk = genuine_key(); + let pk = Rsa2048PublicKey::new(sk.n(), 0x10001).unwrap(); + let mut rng = DefaultRNG::default(); + let sig_a = pss_sign_sha512(&sk, b"hello", &mut rng).expect("signing must succeed"); + let sig_b = pss_sign_sha512(&sk, b"hello", &mut rng).expect("signing must succeed"); + assert_ne!(sig_a, sig_b); + pss_verify_sha512(&pk, b"hello", &sig_a).expect("sig_a must verify"); + pss_verify_sha512(&pk, b"hello", &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 = Rsa2048PublicKey::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 = pss_verify_sha384(&pk, &msg, &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); +} From 80f38fc4354be2f87548347fba8eb977f9fd405a Mon Sep 17 00:00:00 2001 From: David Hook Date: Sat, 19 Sep 2026 20:45:39 +1000 Subject: [PATCH 07/55] rsa: RSA-1024, 1536, 3072, 4096, and 8192 (PKCS#1 v1.5 and PSS) Instantiates the existing generic engine (modexp, rsa_core, keys, emsa_pkcs1_v1_5, emsa_pss, mgf1, rsassa_pkcs1_v1_5, rsassa_pss) at every remaining modulus size the plan calls for. No changes to that engine were needed -- this is purely per-size const-generic wiring: L (limb count = bits/64), HALF (=L/2, CRT prime limb count), L2/L21/HALF2/HALF21, and K_LEN (=8*L) for the modulus, against the existing per-hash constants (H_LEN, T_LEN, SEED_LEN, S_LEN, M_PRIME_LEN, DB_LEN). RSA-1024 (rsa_1024.rs, L=16) and RSA-1536 (rsa_1536.rs, L=24) are verification only -- no RsaXXXPrivateKey type and no sign function exist for either, enforced by the absent type rather than a runtime check, per this crate's established design. 1024 exposes SHA-256/SHA-384 PKCS#1 v1.5 verify (Wycheproof's rsa_pkcs1_1024_sig_gen_test.json has no SHA-512 group and no PSS vectors at this size); 1536 exposes all three hashes for PKCS#1 v1.5 (no PSS vectors at 1536 either). Neither size has a dedicated rsa_signature_*.json verify-vector file in Wycheproof, so each test suite uses the sig-gen file's own privateKey.modulus/publicExponent fields as real public-key material and its own (msg, sig) pairs as real "valid" verify vectors -- the same genuine data, just recovered from a differently-shaped file. RSA-3072 (rsa_3072.rs, L=48) and RSA-4096 (rsa_4096.rs, L=64) support both directions. Their sig-gen keys were recovered by factoring n from the known (n, e, d) triple (Boneh 1999 SS I.B / Miller 1975), the same method used for RSA-2048 in an earlier commit, with each recovered key verified against all of its sig-gen file's real signatures before use. Both are validated against full real Wycheproof coverage: 3072 against rsa_signature_3072_sha256 (259 vectors) and rsa_pss_3072_sha256_mgf1_32 (108 vectors); 4096 against all three hashes' rsa_signature_4096_sha* and rsa_pss_4096_sha*_mgf1_* files (250+ verify vectors and 45+ PSS vectors per hash). RSA-8192 (rsa_8192.rs, L=128) has no Wycheproof sig-gen or PSS data at all, so it's validated two ways instead: a fresh 8192-bit key was generated locally (Miller-Rabin primality testing), and its PKCS#1 v1.5 signatures for SHA-256/384/512 are checked byte-for-byte against BC Java's own RSA implementation (java.security.Signature with the BC provider, RSAPrivateCrtKeySpec built from the identical key material); PSS is cross-verified against BC Java's output instead, since PSS is randomized. Wycheproof's rsa_signature_8192_sha*_test.json files (which exist despite no sig-gen file existing) are still exercised for verify-only regression coverage, but sampled rather than exhaustively: one representative vector per distinct (result, flags) combination, because a 128-limb modexp costs roughly (128/48)^3 times a 3072-bit one and full coverage would run on the order of an hour. Mutation testing remains deferred to a single consolidated pass across the whole crate once every planned modulus size, hash, and the SHAKE128/ 256 (RFC 8702) slice are all in. Co-Authored-By: Claude Sonnet 5 --- crypto/rsa/src/lib.rs | 19 +- crypto/rsa/src/rsa_1024.rs | 39 ++++ crypto/rsa/src/rsa_1536.rs | 45 +++++ crypto/rsa/src/rsa_3072.rs | 164 ++++++++++++++++ crypto/rsa/src/rsa_4096.rs | 168 ++++++++++++++++ crypto/rsa/src/rsa_8192.rs | 170 ++++++++++++++++ crypto/rsa/tests/rsa_1024_tests.rs | 112 +++++++++++ crypto/rsa/tests/rsa_1536_tests.rs | 113 +++++++++++ crypto/rsa/tests/rsa_3072_tests.rs | 254 ++++++++++++++++++++++++ crypto/rsa/tests/rsa_4096_tests.rs | 302 ++++++++++++++++++++++++++++ crypto/rsa/tests/rsa_8192_tests.rs | 305 +++++++++++++++++++++++++++++ 11 files changed, 1686 insertions(+), 5 deletions(-) create mode 100644 crypto/rsa/src/rsa_1024.rs create mode 100644 crypto/rsa/src/rsa_1536.rs create mode 100644 crypto/rsa/src/rsa_3072.rs create mode 100644 crypto/rsa/src/rsa_4096.rs create mode 100644 crypto/rsa/src/rsa_8192.rs create mode 100644 crypto/rsa/tests/rsa_1024_tests.rs create mode 100644 crypto/rsa/tests/rsa_1536_tests.rs create mode 100644 crypto/rsa/tests/rsa_3072_tests.rs create mode 100644 crypto/rsa/tests/rsa_4096_tests.rs create mode 100644 crypto/rsa/tests/rsa_8192_tests.rs diff --git a/crypto/rsa/src/lib.rs b/crypto/rsa/src/lib.rs index ee4c2110..445cba66 100644 --- a/crypto/rsa/src/lib.rs +++ b/crypto/rsa/src/lib.rs @@ -8,9 +8,10 @@ //! # Scope //! //! Signature schemes only -- no RSAES-OAEP or RSAES-PKCS1-v1_5 encryption. Modulus sizes 2048 -//! through 8192 bits support both signing and verification; 1024-bit moduli support verification -//! only, enforced by the absence of a private-key/signer type for that size rather than a runtime -//! check. +//! through 8192 bits ([`rsa_2048`], [`rsa_3072`], [`rsa_4096`], [`rsa_8192`]) support both signing +//! and verification; 1024- and 1536-bit moduli ([`rsa_1024`], [`rsa_1536`]) support verification +//! only, enforced by the absence of a private-key/signer type for those sizes rather than a +//! runtime check. //! //! # Usage Examples //! @@ -53,8 +54,11 @@ //! [`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, -//! wired up for RSA-2048 with SHA-256, SHA-384, and SHA-512 in [`rsa_2048`] and validated against -//! genuine Wycheproof vectors. The remaining modulus sizes are not yet. +//! 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. #![no_std] #![forbid(unsafe_code)] @@ -66,7 +70,12 @@ mod emsa_pss; 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 rsassa_pkcs1_v1_5; pub mod rsassa_pss; diff --git a/crypto/rsa/src/rsa_1024.rs b/crypto/rsa/src/rsa_1024.rs new file mode 100644 index 00000000..e1545e80 --- /dev/null +++ b/crypto/rsa/src/rsa_1024.rs @@ -0,0 +1,39 @@ +//! RSA-1024: verification only. `L = 16` (1024 bits). There is no `Rsa1024PrivateKey` and no +//! signing function -- per this crate's `# Scope` (see `src/lib.rs`), a 1024-bit modulus is for +//! verifying signatures made elsewhere (legacy interoperability), not for producing new ones, and +//! that is enforced by the absent type rather than a runtime check. +//! +//! Only SHA-256 and SHA-384 PKCS#1 v1.5 are wired up: Wycheproof's own +//! `rsa_pkcs1_1024_sig_gen_test.json` has no SHA-512 group at 1024 bits (unlike every other size +//! this crate offers) and no PSS vectors at all, so there is nothing to validate a SHA-512 or PSS +//! pairing against at this size -- both remain mathematically expressible through +//! [`crate::rsassa_pkcs1_v1_5`]/[`crate::rsassa_pss`] directly if a caller ever needs them, just +//! not exposed here without real vectors behind them. + +use crate::keys::RsaPublicKey; +use crate::rsassa_pkcs1_v1_5; +use bouncycastle_core::errors::SignatureError; +use bouncycastle_sha2::{SHA256, SHA384}; + +/// An RSA-1024 public key. +pub type Rsa1024PublicKey = RsaPublicKey<16>; + +/// RSASSA-PKCS1-v1_5 (RFC 8017 §8.2) verification against a SHA-256 digest. See +/// [`rsassa_pkcs1_v1_5::verify`] for what each error means. +pub fn pkcs1_v1_5_verify_sha256( + pk: &Rsa1024PublicKey, + message: &[u8], + signature: &[u8; 128], +) -> Result<(), SignatureError> { + rsassa_pkcs1_v1_5::verify::(pk, message, signature) +} + +/// RSASSA-PKCS1-v1_5 (RFC 8017 §8.2) verification against a SHA-384 digest. See +/// [`rsassa_pkcs1_v1_5::verify`] for what each error means. +pub fn pkcs1_v1_5_verify_sha384( + pk: &Rsa1024PublicKey, + message: &[u8], + signature: &[u8; 128], +) -> Result<(), SignatureError> { + rsassa_pkcs1_v1_5::verify::(pk, message, signature) +} diff --git a/crypto/rsa/src/rsa_1536.rs b/crypto/rsa/src/rsa_1536.rs new file mode 100644 index 00000000..805d60f4 --- /dev/null +++ b/crypto/rsa/src/rsa_1536.rs @@ -0,0 +1,45 @@ +//! RSA-1536: verification only. `L = 24` (1536 bits). As with [`crate::rsa_1024`], there is no +//! `Rsa1536PrivateKey` and no signing function -- see that module's docs and this crate's +//! `# Scope` for why. +//! +//! Only PKCS#1 v1.5 is wired up: Wycheproof has no PSS vectors at 1536 bits (nor, realistically, +//! would PSS be paired with a modulus this small in practice -- it postdates PKCS#1 v1.5 and +//! became common alongside longer keys), so there is nothing to validate a PSS pairing against at +//! this size. +use crate::keys::RsaPublicKey; +use crate::rsassa_pkcs1_v1_5; +use bouncycastle_core::errors::SignatureError; +use bouncycastle_sha2::{SHA256, SHA384, SHA512}; + +/// An RSA-1536 public key. +pub type Rsa1536PublicKey = RsaPublicKey<24>; + +/// RSASSA-PKCS1-v1_5 (RFC 8017 §8.2) verification against a SHA-256 digest. See +/// [`rsassa_pkcs1_v1_5::verify`] for what each error means. +pub fn pkcs1_v1_5_verify_sha256( + pk: &Rsa1536PublicKey, + message: &[u8], + signature: &[u8; 192], +) -> Result<(), SignatureError> { + rsassa_pkcs1_v1_5::verify::(pk, message, signature) +} + +/// RSASSA-PKCS1-v1_5 (RFC 8017 §8.2) verification against a SHA-384 digest. See +/// [`rsassa_pkcs1_v1_5::verify`] for what each error means. +pub fn pkcs1_v1_5_verify_sha384( + pk: &Rsa1536PublicKey, + message: &[u8], + signature: &[u8; 192], +) -> Result<(), SignatureError> { + rsassa_pkcs1_v1_5::verify::(pk, message, signature) +} + +/// RSASSA-PKCS1-v1_5 (RFC 8017 §8.2) verification against a SHA-512 digest. See +/// [`rsassa_pkcs1_v1_5::verify`] for what each error means. +pub fn pkcs1_v1_5_verify_sha512( + pk: &Rsa1536PublicKey, + message: &[u8], + signature: &[u8; 192], +) -> Result<(), SignatureError> { + rsassa_pkcs1_v1_5::verify::(pk, message, signature) +} diff --git a/crypto/rsa/src/rsa_3072.rs b/crypto/rsa/src/rsa_3072.rs new file mode 100644 index 00000000..b6d46a74 --- /dev/null +++ b/crypto/rsa/src/rsa_3072.rs @@ -0,0 +1,164 @@ +//! RSA-3072: `L = 48` (3072 bits), `HALF = 24` (1536-bit CRT primes). See [`crate::rsa_2048`]'s +//! docs for the pattern every concrete modulus size in this crate follows. + +use crate::keys::{RsaPrivateKey, RsaPublicKey}; +use crate::rsassa_pkcs1_v1_5; +use crate::rsassa_pss; +use bouncycastle_core::errors::SignatureError; +use bouncycastle_core::traits::RNG; +use bouncycastle_sha2::{SHA256, SHA384, SHA512}; + +/// An RSA-3072 private key (`p`, `q` each 1536 bits). +pub type Rsa3072PrivateKey = RsaPrivateKey<48, 24>; +/// An RSA-3072 public key. +pub type Rsa3072PublicKey = RsaPublicKey<48>; + +/// RSASSA-PKCS1-v1_5 (RFC 8017 §8.2) signing with SHA-256. See [`rsassa_pkcs1_v1_5::sign`] for +/// what each error means. +pub fn pkcs1_v1_5_sign_sha256( + sk: &Rsa3072PrivateKey, + message: &[u8], +) -> Result<[u8; 384], SignatureError> { + rsassa_pkcs1_v1_5::sign::(sk, message) +} + +/// RSASSA-PKCS1-v1_5 (RFC 8017 §8.2) verification against a SHA-256 digest. See +/// [`rsassa_pkcs1_v1_5::verify`] for what each error means. +pub fn pkcs1_v1_5_verify_sha256( + pk: &Rsa3072PublicKey, + message: &[u8], + signature: &[u8; 384], +) -> Result<(), SignatureError> { + rsassa_pkcs1_v1_5::verify::(pk, message, signature) +} + +/// RSASSA-PKCS1-v1_5 (RFC 8017 §8.2) signing with SHA-384. See [`rsassa_pkcs1_v1_5::sign`] for +/// what each error means. +pub fn pkcs1_v1_5_sign_sha384( + sk: &Rsa3072PrivateKey, + message: &[u8], +) -> Result<[u8; 384], SignatureError> { + rsassa_pkcs1_v1_5::sign::(sk, message) +} + +/// RSASSA-PKCS1-v1_5 (RFC 8017 §8.2) verification against a SHA-384 digest. See +/// [`rsassa_pkcs1_v1_5::verify`] for what each error means. +pub fn pkcs1_v1_5_verify_sha384( + pk: &Rsa3072PublicKey, + message: &[u8], + signature: &[u8; 384], +) -> Result<(), SignatureError> { + rsassa_pkcs1_v1_5::verify::(pk, message, signature) +} + +/// RSASSA-PKCS1-v1_5 (RFC 8017 §8.2) signing with SHA-512. See [`rsassa_pkcs1_v1_5::sign`] for +/// what each error means. +pub fn pkcs1_v1_5_sign_sha512( + sk: &Rsa3072PrivateKey, + message: &[u8], +) -> Result<[u8; 384], SignatureError> { + rsassa_pkcs1_v1_5::sign::(sk, message) +} + +/// RSASSA-PKCS1-v1_5 (RFC 8017 §8.2) verification against a SHA-512 digest. See +/// [`rsassa_pkcs1_v1_5::verify`] for what each error means. +pub fn pkcs1_v1_5_verify_sha512( + pk: &Rsa3072PublicKey, + message: &[u8], + signature: &[u8; 384], +) -> Result<(), SignatureError> { + rsassa_pkcs1_v1_5::verify::(pk, message, signature) +} + +/// RSASSA-PSS (RFC 8017 §8.1) signing with SHA-256 and a 32-byte salt drawn fresh from `rng`. See +/// [`rsassa_pss::sign`] for what each error means. +pub fn pss_sign_sha256( + sk: &Rsa3072PrivateKey, + message: &[u8], + rng: &mut dyn RNG, +) -> Result<[u8; 384], SignatureError> { + rsassa_pss::sign::(sk, message, rng) +} + +/// As [`pss_sign_sha256`], but with the salt supplied directly instead of drawn from an RNG. +pub fn pss_sign_sha256_with_salt( + sk: &Rsa3072PrivateKey, + message: &[u8], + salt: &[u8; 32], +) -> Result<[u8; 384], SignatureError> { + rsassa_pss::sign_with_salt::( + sk, message, salt, + ) +} + +/// RSASSA-PSS (RFC 8017 §8.1) verification against a SHA-256/MGF1-SHA-256/32-byte-salt encoding. +/// See [`rsassa_pss::verify`] for what each error means. +pub fn pss_verify_sha256( + pk: &Rsa3072PublicKey, + message: &[u8], + signature: &[u8; 384], +) -> Result<(), SignatureError> { + rsassa_pss::verify::(pk, message, signature) +} + +/// RSASSA-PSS (RFC 8017 §8.1) signing with SHA-384 and a 48-byte salt drawn fresh from `rng`. See +/// [`rsassa_pss::sign`] for what each error means. +pub fn pss_sign_sha384( + sk: &Rsa3072PrivateKey, + message: &[u8], + rng: &mut dyn RNG, +) -> Result<[u8; 384], SignatureError> { + rsassa_pss::sign::(sk, message, rng) +} + +/// As [`pss_sign_sha384`], but with the salt supplied directly instead of drawn from an RNG. +pub fn pss_sign_sha384_with_salt( + sk: &Rsa3072PrivateKey, + message: &[u8], + salt: &[u8; 48], +) -> Result<[u8; 384], SignatureError> { + rsassa_pss::sign_with_salt::( + sk, message, salt, + ) +} + +/// RSASSA-PSS (RFC 8017 §8.1) verification against a SHA-384/MGF1-SHA-384/48-byte-salt encoding. +/// See [`rsassa_pss::verify`] for what each error means. +pub fn pss_verify_sha384( + pk: &Rsa3072PublicKey, + message: &[u8], + signature: &[u8; 384], +) -> Result<(), SignatureError> { + rsassa_pss::verify::(pk, message, signature) +} + +/// RSASSA-PSS (RFC 8017 §8.1) signing with SHA-512 and a 64-byte salt drawn fresh from `rng`. See +/// [`rsassa_pss::sign`] for what each error means. +pub fn pss_sign_sha512( + sk: &Rsa3072PrivateKey, + message: &[u8], + rng: &mut dyn RNG, +) -> Result<[u8; 384], SignatureError> { + rsassa_pss::sign::(sk, message, rng) +} + +/// As [`pss_sign_sha512`], but with the salt supplied directly instead of drawn from an RNG. +pub fn pss_sign_sha512_with_salt( + sk: &Rsa3072PrivateKey, + message: &[u8], + salt: &[u8; 64], +) -> Result<[u8; 384], SignatureError> { + rsassa_pss::sign_with_salt::( + sk, message, salt, + ) +} + +/// RSASSA-PSS (RFC 8017 §8.1) verification against a SHA-512/MGF1-SHA-512/64-byte-salt encoding. +/// See [`rsassa_pss::verify`] for what each error means. +pub fn pss_verify_sha512( + pk: &Rsa3072PublicKey, + message: &[u8], + signature: &[u8; 384], +) -> Result<(), SignatureError> { + rsassa_pss::verify::(pk, message, signature) +} diff --git a/crypto/rsa/src/rsa_4096.rs b/crypto/rsa/src/rsa_4096.rs new file mode 100644 index 00000000..afd33fcd --- /dev/null +++ b/crypto/rsa/src/rsa_4096.rs @@ -0,0 +1,168 @@ +//! RSA-4096: `L = 64` (4096 bits), `HALF = 32` (2048-bit CRT primes). See [`crate::rsa_2048`]'s +//! docs for the pattern every concrete modulus size in this crate follows. + +use crate::keys::{RsaPrivateKey, RsaPublicKey}; +use crate::rsassa_pkcs1_v1_5; +use crate::rsassa_pss; +use bouncycastle_core::errors::SignatureError; +use bouncycastle_core::traits::RNG; +use bouncycastle_sha2::{SHA256, SHA384, SHA512}; + +/// An RSA-4096 private key (`p`, `q` each 2048 bits). +pub type Rsa4096PrivateKey = RsaPrivateKey<64, 32>; +/// An RSA-4096 public key. +pub type Rsa4096PublicKey = RsaPublicKey<64>; + +/// RSASSA-PKCS1-v1_5 (RFC 8017 §8.2) signing with SHA-256. See [`rsassa_pkcs1_v1_5::sign`] for +/// what each error means. +pub fn pkcs1_v1_5_sign_sha256( + sk: &Rsa4096PrivateKey, + message: &[u8], +) -> Result<[u8; 512], SignatureError> { + rsassa_pkcs1_v1_5::sign::(sk, message) +} + +/// RSASSA-PKCS1-v1_5 (RFC 8017 §8.2) verification against a SHA-256 digest. See +/// [`rsassa_pkcs1_v1_5::verify`] for what each error means. +pub fn pkcs1_v1_5_verify_sha256( + pk: &Rsa4096PublicKey, + message: &[u8], + signature: &[u8; 512], +) -> Result<(), SignatureError> { + rsassa_pkcs1_v1_5::verify::(pk, message, signature) +} + +/// RSASSA-PKCS1-v1_5 (RFC 8017 §8.2) signing with SHA-384. See [`rsassa_pkcs1_v1_5::sign`] for +/// what each error means. +pub fn pkcs1_v1_5_sign_sha384( + sk: &Rsa4096PrivateKey, + message: &[u8], +) -> Result<[u8; 512], SignatureError> { + rsassa_pkcs1_v1_5::sign::(sk, message) +} + +/// RSASSA-PKCS1-v1_5 (RFC 8017 §8.2) verification against a SHA-384 digest. See +/// [`rsassa_pkcs1_v1_5::verify`] for what each error means. +pub fn pkcs1_v1_5_verify_sha384( + pk: &Rsa4096PublicKey, + message: &[u8], + signature: &[u8; 512], +) -> Result<(), SignatureError> { + rsassa_pkcs1_v1_5::verify::(pk, message, signature) +} + +/// RSASSA-PKCS1-v1_5 (RFC 8017 §8.2) signing with SHA-512. See [`rsassa_pkcs1_v1_5::sign`] for +/// what each error means. +pub fn pkcs1_v1_5_sign_sha512( + sk: &Rsa4096PrivateKey, + message: &[u8], +) -> Result<[u8; 512], SignatureError> { + rsassa_pkcs1_v1_5::sign::(sk, message) +} + +/// RSASSA-PKCS1-v1_5 (RFC 8017 §8.2) verification against a SHA-512 digest. See +/// [`rsassa_pkcs1_v1_5::verify`] for what each error means. +pub fn pkcs1_v1_5_verify_sha512( + pk: &Rsa4096PublicKey, + message: &[u8], + signature: &[u8; 512], +) -> Result<(), SignatureError> { + rsassa_pkcs1_v1_5::verify::(pk, message, signature) +} + +/// RSASSA-PSS (RFC 8017 §8.1) signing with SHA-256 and a 32-byte salt drawn fresh from `rng`. See +/// [`rsassa_pss::sign`] for what each error means. +pub fn pss_sign_sha256( + sk: &Rsa4096PrivateKey, + message: &[u8], + rng: &mut dyn RNG, +) -> Result<[u8; 512], SignatureError> { + rsassa_pss::sign::(sk, message, rng) +} + +/// As [`pss_sign_sha256`], but with the salt supplied directly instead of drawn from an RNG. +pub fn pss_sign_sha256_with_salt( + sk: &Rsa4096PrivateKey, + message: &[u8], + salt: &[u8; 32], +) -> Result<[u8; 512], SignatureError> { + rsassa_pss::sign_with_salt::( + sk, message, salt, + ) +} + +/// RSASSA-PSS (RFC 8017 §8.1) verification against a SHA-256/MGF1-SHA-256/32-byte-salt encoding. +/// See [`rsassa_pss::verify`] for what each error means. +pub fn pss_verify_sha256( + pk: &Rsa4096PublicKey, + message: &[u8], + signature: &[u8; 512], +) -> Result<(), SignatureError> { + rsassa_pss::verify::(pk, message, signature) +} + +/// RSASSA-PSS (RFC 8017 §8.1) signing with SHA-384 and a 48-byte salt drawn fresh from `rng`. See +/// [`rsassa_pss::sign`] for what each error means. +pub fn pss_sign_sha384( + sk: &Rsa4096PrivateKey, + message: &[u8], + rng: &mut dyn RNG, +) -> Result<[u8; 512], SignatureError> { + rsassa_pss::sign::( + sk, message, rng, + ) +} + +/// As [`pss_sign_sha384`], but with the salt supplied directly instead of drawn from an RNG. +pub fn pss_sign_sha384_with_salt( + sk: &Rsa4096PrivateKey, + message: &[u8], + salt: &[u8; 48], +) -> Result<[u8; 512], SignatureError> { + rsassa_pss::sign_with_salt::( + sk, message, salt, + ) +} + +/// RSASSA-PSS (RFC 8017 §8.1) verification against a SHA-384/MGF1-SHA-384/48-byte-salt encoding. +/// See [`rsassa_pss::verify`] for what each error means. +pub fn pss_verify_sha384( + pk: &Rsa4096PublicKey, + message: &[u8], + signature: &[u8; 512], +) -> Result<(), SignatureError> { + rsassa_pss::verify::(pk, message, signature) +} + +/// RSASSA-PSS (RFC 8017 §8.1) signing with SHA-512 and a 64-byte salt drawn fresh from `rng`. See +/// [`rsassa_pss::sign`] for what each error means. +pub fn pss_sign_sha512( + sk: &Rsa4096PrivateKey, + message: &[u8], + rng: &mut dyn RNG, +) -> Result<[u8; 512], SignatureError> { + rsassa_pss::sign::( + sk, message, rng, + ) +} + +/// As [`pss_sign_sha512`], but with the salt supplied directly instead of drawn from an RNG. +pub fn pss_sign_sha512_with_salt( + sk: &Rsa4096PrivateKey, + message: &[u8], + salt: &[u8; 64], +) -> Result<[u8; 512], SignatureError> { + rsassa_pss::sign_with_salt::( + sk, message, salt, + ) +} + +/// RSASSA-PSS (RFC 8017 §8.1) verification against a SHA-512/MGF1-SHA-512/64-byte-salt encoding. +/// See [`rsassa_pss::verify`] for what each error means. +pub fn pss_verify_sha512( + pk: &Rsa4096PublicKey, + message: &[u8], + signature: &[u8; 512], +) -> Result<(), SignatureError> { + rsassa_pss::verify::(pk, message, signature) +} diff --git a/crypto/rsa/src/rsa_8192.rs b/crypto/rsa/src/rsa_8192.rs new file mode 100644 index 00000000..b4914b41 --- /dev/null +++ b/crypto/rsa/src/rsa_8192.rs @@ -0,0 +1,170 @@ +//! RSA-8192: `L = 128` (8192 bits), `HALF = 64` (4096-bit CRT primes). See [`crate::rsa_2048`]'s +//! docs for the pattern every concrete modulus size in this crate follows. + +use crate::keys::{RsaPrivateKey, RsaPublicKey}; +use crate::rsassa_pkcs1_v1_5; +use crate::rsassa_pss; +use bouncycastle_core::errors::SignatureError; +use bouncycastle_core::traits::RNG; +use bouncycastle_sha2::{SHA256, SHA384, SHA512}; + +/// An RSA-8192 private key (`p`, `q` each 4096 bits). +pub type Rsa8192PrivateKey = RsaPrivateKey<128, 64>; +/// An RSA-8192 public key. +pub type Rsa8192PublicKey = RsaPublicKey<128>; + +/// RSASSA-PKCS1-v1_5 (RFC 8017 §8.2) signing with SHA-256. See [`rsassa_pkcs1_v1_5::sign`] for +/// what each error means. +pub fn pkcs1_v1_5_sign_sha256( + sk: &Rsa8192PrivateKey, + message: &[u8], +) -> Result<[u8; 1024], SignatureError> { + rsassa_pkcs1_v1_5::sign::(sk, message) +} + +/// RSASSA-PKCS1-v1_5 (RFC 8017 §8.2) verification against a SHA-256 digest. See +/// [`rsassa_pkcs1_v1_5::verify`] for what each error means. +pub fn pkcs1_v1_5_verify_sha256( + pk: &Rsa8192PublicKey, + message: &[u8], + signature: &[u8; 1024], +) -> Result<(), SignatureError> { + rsassa_pkcs1_v1_5::verify::(pk, message, signature) +} + +/// RSASSA-PKCS1-v1_5 (RFC 8017 §8.2) signing with SHA-384. See [`rsassa_pkcs1_v1_5::sign`] for +/// what each error means. +pub fn pkcs1_v1_5_sign_sha384( + sk: &Rsa8192PrivateKey, + message: &[u8], +) -> Result<[u8; 1024], SignatureError> { + rsassa_pkcs1_v1_5::sign::(sk, message) +} + +/// RSASSA-PKCS1-v1_5 (RFC 8017 §8.2) verification against a SHA-384 digest. See +/// [`rsassa_pkcs1_v1_5::verify`] for what each error means. +pub fn pkcs1_v1_5_verify_sha384( + pk: &Rsa8192PublicKey, + message: &[u8], + signature: &[u8; 1024], +) -> Result<(), SignatureError> { + rsassa_pkcs1_v1_5::verify::(pk, message, signature) +} + +/// RSASSA-PKCS1-v1_5 (RFC 8017 §8.2) signing with SHA-512. See [`rsassa_pkcs1_v1_5::sign`] for +/// what each error means. +pub fn pkcs1_v1_5_sign_sha512( + sk: &Rsa8192PrivateKey, + message: &[u8], +) -> Result<[u8; 1024], SignatureError> { + rsassa_pkcs1_v1_5::sign::(sk, message) +} + +/// RSASSA-PKCS1-v1_5 (RFC 8017 §8.2) verification against a SHA-512 digest. See +/// [`rsassa_pkcs1_v1_5::verify`] for what each error means. +pub fn pkcs1_v1_5_verify_sha512( + pk: &Rsa8192PublicKey, + message: &[u8], + signature: &[u8; 1024], +) -> Result<(), SignatureError> { + rsassa_pkcs1_v1_5::verify::(pk, message, signature) +} + +/// RSASSA-PSS (RFC 8017 §8.1) signing with SHA-256 and a 32-byte salt drawn fresh from `rng`. See +/// [`rsassa_pss::sign`] for what each error means. +pub fn pss_sign_sha256( + sk: &Rsa8192PrivateKey, + message: &[u8], + rng: &mut dyn RNG, +) -> Result<[u8; 1024], SignatureError> { + rsassa_pss::sign::( + sk, message, rng, + ) +} + +/// As [`pss_sign_sha256`], but with the salt supplied directly instead of drawn from an RNG. +pub fn pss_sign_sha256_with_salt( + sk: &Rsa8192PrivateKey, + message: &[u8], + salt: &[u8; 32], +) -> Result<[u8; 1024], SignatureError> { + rsassa_pss::sign_with_salt::( + sk, message, salt, + ) +} + +/// RSASSA-PSS (RFC 8017 §8.1) verification against a SHA-256/MGF1-SHA-256/32-byte-salt encoding. +/// See [`rsassa_pss::verify`] for what each error means. +pub fn pss_verify_sha256( + pk: &Rsa8192PublicKey, + message: &[u8], + signature: &[u8; 1024], +) -> Result<(), SignatureError> { + rsassa_pss::verify::(pk, message, signature) +} + +/// RSASSA-PSS (RFC 8017 §8.1) signing with SHA-384 and a 48-byte salt drawn fresh from `rng`. See +/// [`rsassa_pss::sign`] for what each error means. +pub fn pss_sign_sha384( + sk: &Rsa8192PrivateKey, + message: &[u8], + rng: &mut dyn RNG, +) -> Result<[u8; 1024], SignatureError> { + rsassa_pss::sign::( + sk, message, rng, + ) +} + +/// As [`pss_sign_sha384`], but with the salt supplied directly instead of drawn from an RNG. +pub fn pss_sign_sha384_with_salt( + sk: &Rsa8192PrivateKey, + message: &[u8], + salt: &[u8; 48], +) -> Result<[u8; 1024], SignatureError> { + rsassa_pss::sign_with_salt::( + sk, message, salt, + ) +} + +/// RSASSA-PSS (RFC 8017 §8.1) verification against a SHA-384/MGF1-SHA-384/48-byte-salt encoding. +/// See [`rsassa_pss::verify`] for what each error means. +pub fn pss_verify_sha384( + pk: &Rsa8192PublicKey, + message: &[u8], + signature: &[u8; 1024], +) -> Result<(), SignatureError> { + rsassa_pss::verify::(pk, message, signature) +} + +/// RSASSA-PSS (RFC 8017 §8.1) signing with SHA-512 and a 64-byte salt drawn fresh from `rng`. See +/// [`rsassa_pss::sign`] for what each error means. +pub fn pss_sign_sha512( + sk: &Rsa8192PrivateKey, + message: &[u8], + rng: &mut dyn RNG, +) -> Result<[u8; 1024], SignatureError> { + rsassa_pss::sign::( + sk, message, rng, + ) +} + +/// As [`pss_sign_sha512`], but with the salt supplied directly instead of drawn from an RNG. +pub fn pss_sign_sha512_with_salt( + sk: &Rsa8192PrivateKey, + message: &[u8], + salt: &[u8; 64], +) -> Result<[u8; 1024], SignatureError> { + rsassa_pss::sign_with_salt::( + sk, message, salt, + ) +} + +/// RSASSA-PSS (RFC 8017 §8.1) verification against a SHA-512/MGF1-SHA-512/64-byte-salt encoding. +/// See [`rsassa_pss::verify`] for what each error means. +pub fn pss_verify_sha512( + pk: &Rsa8192PublicKey, + message: &[u8], + signature: &[u8; 1024], +) -> Result<(), SignatureError> { + rsassa_pss::verify::(pk, message, signature) +} diff --git a/crypto/rsa/tests/rsa_1024_tests.rs b/crypto/rsa/tests/rsa_1024_tests.rs new file mode 100644 index 00000000..762db074 --- /dev/null +++ b/crypto/rsa/tests/rsa_1024_tests.rs @@ -0,0 +1,112 @@ +//! 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_hex::decode as hex_decode; +use bouncycastle_rsa::rsa_1024::{ + Rsa1024PublicKey, pkcs1_v1_5_verify_sha256, pkcs1_v1_5_verify_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(&Rsa1024PublicKey, &[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 = Rsa1024PublicKey::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| { + pkcs1_v1_5_verify_sha256(pk, msg, 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| { + pkcs1_v1_5_verify_sha384(pk, msg, sig).is_ok() + }); +} + +#[test] +fn pkcs1_v1_5_rejects_wrong_message() { + 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-256" && 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 = Rsa1024PublicKey::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!( + pkcs1_v1_5_verify_sha256(&pk, b"a message this signature was not made for", &sig).is_err() + ); +} diff --git a/crypto/rsa/tests/rsa_1536_tests.rs b/crypto/rsa/tests/rsa_1536_tests.rs new file mode 100644 index 00000000..3a6d0989 --- /dev/null +++ b/crypto/rsa/tests/rsa_1536_tests.rs @@ -0,0 +1,113 @@ +//! 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_hex::decode as hex_decode; +use bouncycastle_rsa::rsa_1536::{ + Rsa1536PublicKey, pkcs1_v1_5_verify_sha256, pkcs1_v1_5_verify_sha384, pkcs1_v1_5_verify_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(&Rsa1536PublicKey, &[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 = Rsa1536PublicKey::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| { + pkcs1_v1_5_verify_sha256(pk, msg, 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| { + pkcs1_v1_5_verify_sha384(pk, msg, 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| { + pkcs1_v1_5_verify_sha512(pk, msg, sig).is_ok() + }); +} + +#[test] +fn pkcs1_v1_5_rejects_wrong_message() { + 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-256").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 = Rsa1536PublicKey::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!( + pkcs1_v1_5_verify_sha256(&pk, b"a message this signature was not made for", &sig).is_err() + ); +} diff --git a/crypto/rsa/tests/rsa_3072_tests.rs b/crypto/rsa/tests/rsa_3072_tests.rs new file mode 100644 index 00000000..643798af --- /dev/null +++ b/crypto/rsa/tests/rsa_3072_tests.rs @@ -0,0 +1,254 @@ +//! 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). +//! +//! `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_hex::decode as hex_decode; +use bouncycastle_rng::DefaultRNG; +use bouncycastle_rsa::rsa_3072::{ + Rsa3072PrivateKey, Rsa3072PublicKey, pkcs1_v1_5_sign_sha256, pkcs1_v1_5_sign_sha384, + pkcs1_v1_5_sign_sha512, pkcs1_v1_5_verify_sha256, pkcs1_v1_5_verify_sha384, + pkcs1_v1_5_verify_sha512, pss_sign_sha256, pss_sign_sha384_with_salt, pss_sign_sha512, + pss_verify_sha256, pss_verify_sha384, pss_verify_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 genuine_key() -> Rsa3072PrivateKey { + 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, + ]; + Rsa3072PrivateKey::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 = pkcs1_v1_5_sign_sha256(&sk, &msg).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 = Rsa3072PublicKey::new(sk.n(), 0x10001).unwrap(); + let sig384 = pkcs1_v1_5_sign_sha384(&sk, b"hello").unwrap(); + pkcs1_v1_5_verify_sha384(&pk, b"hello", &sig384).unwrap(); + let sig512 = pkcs1_v1_5_sign_sha512(&sk, b"hello").unwrap(); + pkcs1_v1_5_verify_sha512(&pk, b"hello", &sig512).unwrap(); +} + +#[test] +fn pss_sha256_sha384_sha512_round_trip() { + let sk = genuine_key(); + let pk = Rsa3072PublicKey::new(sk.n(), 0x10001).unwrap(); + let mut rng = DefaultRNG::default(); + + let sig256 = pss_sign_sha256(&sk, b"hello", &mut rng).unwrap(); + pss_verify_sha256(&pk, b"hello", &sig256).unwrap(); + + let salt384 = [0x11u8; 48]; + let sig384 = pss_sign_sha384_with_salt(&sk, b"hello", &salt384).unwrap(); + pss_verify_sha384(&pk, b"hello", &sig384).unwrap(); + + let sig512 = pss_sign_sha512(&sk, b"hello", &mut rng).unwrap(); + pss_verify_sha512(&pk, b"hello", &sig512).unwrap(); +} + +fn run_pkcs1_v1_5_verify_vectors( + filename: &str, + verify: impl Fn(&Rsa3072PublicKey, &[u8], &[u8; 384]) -> bool, + expected_sha: &str, +) { + 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 = Rsa3072PublicKey::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, 8, "for {filename}"); + assert_eq!(num_invalid, 250, "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| pkcs1_v1_5_verify_sha256(pk, msg, sig).is_ok(), + "SHA-256", + ); +} + +#[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 = Rsa3072PublicKey::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 = pss_verify_sha256(&pk, &msg, &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); +} diff --git a/crypto/rsa/tests/rsa_4096_tests.rs b/crypto/rsa/tests/rsa_4096_tests.rs new file mode 100644 index 00000000..30d51fb5 --- /dev/null +++ b/crypto/rsa/tests/rsa_4096_tests.rs @@ -0,0 +1,302 @@ +//! 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). +//! +//! `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_hex::decode as hex_decode; +use bouncycastle_rsa::rsa_4096::{ + Rsa4096PrivateKey, Rsa4096PublicKey, pkcs1_v1_5_sign_sha256, pkcs1_v1_5_verify_sha256, + pkcs1_v1_5_verify_sha384, pkcs1_v1_5_verify_sha512, pss_verify_sha256, pss_verify_sha384, + pss_verify_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 genuine_key() -> Rsa4096PrivateKey { + 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, + ]; + Rsa4096PrivateKey::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 = pkcs1_v1_5_sign_sha256(&sk, &msg).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); +} + +fn run_pkcs1_v1_5_verify_vectors( + filename: &str, + verify: impl Fn(&Rsa4096PublicKey, &[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 = Rsa4096PublicKey::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| pkcs1_v1_5_verify_sha256(pk, msg, 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| pkcs1_v1_5_verify_sha384(pk, msg, 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| pkcs1_v1_5_verify_sha512(pk, msg, sig).is_ok(), + "SHA-512", + 7, + 251, + ); +} + +fn run_pss_verify_vectors( + filename: &str, + verify: impl Fn(&Rsa4096PublicKey, &[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 = Rsa4096PublicKey::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| pss_verify_sha256(pk, msg, 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| pss_verify_sha384(pk, msg, 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| pss_verify_sha512(pk, msg, sig).is_ok(), + "SHA-512", + 64, + 132, + 47, + ); +} diff --git a/crypto/rsa/tests/rsa_8192_tests.rs b/crypto/rsa/tests/rsa_8192_tests.rs new file mode 100644 index 00000000..06457df5 --- /dev/null +++ b/crypto/rsa/tests/rsa_8192_tests.rs @@ -0,0 +1,305 @@ +//! 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 `pkcs1_v1_5_sign_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_verify_sha{256,384,512}`, 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_hex::decode as hex_decode; +use bouncycastle_rng::DefaultRNG; +use bouncycastle_rsa::rsa_8192::{ + Rsa8192PrivateKey, Rsa8192PublicKey, pkcs1_v1_5_sign_sha256, pkcs1_v1_5_sign_sha384, + pkcs1_v1_5_sign_sha512, pkcs1_v1_5_verify_sha256, pkcs1_v1_5_verify_sha384, + pkcs1_v1_5_verify_sha512, pss_sign_sha256, pss_verify_sha256, pss_verify_sha384, + pss_verify_sha512, +}; +use serde_json::Value; +use std::collections::HashSet; +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 fresh, self-generated key used for the BC Java cross-check and for self-consistency. +fn genuine_key() -> Rsa8192PrivateKey { + 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, + ]; + Rsa8192PrivateKey::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 = pkcs1_v1_5_sign_sha256(&sk, b"hello").unwrap(); + assert_eq!(sig256.to_vec(), hex_decode(BC_JAVA_SHA256_SIG).unwrap()); + + let sig384 = pkcs1_v1_5_sign_sha384(&sk, b"hello").unwrap(); + assert_eq!(sig384.to_vec(), hex_decode(BC_JAVA_SHA384_SIG).unwrap()); + + let sig512 = pkcs1_v1_5_sign_sha512(&sk, b"hello").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 = Rsa8192PublicKey::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(); + pkcs1_v1_5_verify_sha256(&pk, b"hello", &sig256).expect("BC Java's SHA-256 sig must verify"); + pkcs1_v1_5_verify_sha384(&pk, b"hello", &sig384).expect("BC Java's SHA-384 sig must verify"); + pkcs1_v1_5_verify_sha512(&pk, b"hello", &sig512).expect("BC Java's SHA-512 sig must verify"); +} + +#[test] +fn pss_verifies_bc_java_sha256_signature() { + let sk = genuine_key(); + let pk = Rsa8192PublicKey::new(sk.n(), 0x10001).unwrap(); + let sig: [u8; 1024] = hex_decode(BC_JAVA_PSS_SHA256_SIG).unwrap().try_into().unwrap(); + pss_verify_sha256(&pk, b"hello", &sig) + .expect("BC Java's PSS/SHA-256 signature (default salt length = hLen) must verify"); +} + +#[test] +fn pss_self_consistency_sha256_sha384_sha512() { + let sk = genuine_key(); + let pk = Rsa8192PublicKey::new(sk.n(), 0x10001).unwrap(); + let mut rng = DefaultRNG::default(); + + let sig = pss_sign_sha256(&sk, b"hello", &mut rng).unwrap(); + pss_verify_sha256(&pk, b"hello", &sig).unwrap(); + + // pss_sign_sha384/512 need a salt of their own hash's length; reuse sign_with_salt directly + // via the crate's generic engine is unnecessary here since rsa_8192 already exposes + // pss_sign_sha384/512 -- see rsa_2048_pss_sha384_sha512_tests.rs for the identical pattern. + use bouncycastle_rsa::rsa_8192::{pss_sign_sha384_with_salt, pss_sign_sha512_with_salt}; + let sig384 = pss_sign_sha384_with_salt(&sk, b"hello", &[0x11u8; 48]).unwrap(); + pss_verify_sha384(&pk, b"hello", &sig384).unwrap(); + let sig512 = pss_sign_sha512_with_salt(&sk, b"hello", &[0x22u8; 64]).unwrap(); + pss_verify_sha512(&pk, b"hello", &sig512).unwrap(); +} + +/// 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(&Rsa8192PublicKey, &[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 = Rsa8192PublicKey::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| pkcs1_v1_5_verify_sha256(pk, msg, 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| pkcs1_v1_5_verify_sha384(pk, msg, 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| pkcs1_v1_5_verify_sha512(pk, msg, sig).is_ok(), + "SHA-512", + ); +} From 20cb229ed46d5ef1549d6d2bcdffd38dd37e4d1f Mon Sep 17 00:00:00 2001 From: David Hook Date: Sat, 19 Sep 2026 21:15:05 +1000 Subject: [PATCH 08/55] rsa: RSASSA-PSS-SHAKE128/256 (RFC 8702 SS3.2.1) Adds id-RSASSA-PSS-SHAKE128/id-RSASSA-PSS-SHAKE256: SHAKE128/SHAKE256 as both the message hash and the mask generation function, per RFC 8702 SS3.2.1's own wording, "the SHAKEs MUST be used natively as the MGF, instead of the MGF1 algorithm that uses the hash function in multiple iterations". A SHAKE can already produce an arbitrary-length output from a single absorb (it's an XOF), so emsa_pss_shake.rs has no counterpart to mgf1.rs's counter loop at all -- the mask step is one xof_out call on the seed. Otherwise emsa_pss_shake.rs/rsassa_pss_shake.rs are RFC 8017 SS9.1/SS8.1's EMSA-PSS-ENCODE/VERIFY and RSASSA-PSS-SIGN/VERIFY, generic over X: XOF + Default in place of H: Hash + Default, mirroring emsa_pss.rs/rsassa_pss.rs as separate files rather than folding the two mask-generation strategies into one parameterized module. RFC 8702 SS3.2.1 also fixes hLen == sLen (32 bytes for SHAKE128, 64 for SHAKE256) and the trailer field to 0xbc -- already this crate's own "typical" PSS salt-length convention and its only trailer byte (see emsa_pss.rs's own module docs), so no new relationship needed stating. Wired up for the pairings RFC 8702 SS5's security considerations recommend: SHAKE128 with a 2048- or 3072-bit modulus (rsa_2048, rsa_3072), SHAKE256 with 4096-bit or larger (rsa_4096). Wycheproof carries no PSS sig-gen vectors (PSS is randomized), so the sign side is a self-consistency round trip against each size's already-recovered genuine key, and the verify side is checked against all of Wycheproof's real vectors: rsa_pss_2048_shake128_test.json and rsa_pss_3072_shake128_test.json (114 vectors each, 69 valid/45 invalid), and rsa_pss_4096_shake256_test.json (184 vectors, 138 valid/46 invalid). emsa_pss_shake.rs's own encode KAT is a direct Python transliteration of RFC 8017 SS9.1.1 with RFC 8702's native-SHAKE mask substituted for MGF1, using hashlib.shake_128 (not from recall). Mutation testing remains deferred to a single consolidated pass across the whole crate once every planned modulus size, hash, and SHAKE variant is in. Co-Authored-By: Claude Sonnet 5 --- crypto/rsa/Cargo.toml | 1 + crypto/rsa/src/emsa_pss_shake.rs | 244 ++++++++++++++++++ crypto/rsa/src/lib.rs | 9 + crypto/rsa/src/rsa_2048.rs | 38 +++ crypto/rsa/src/rsa_3072.rs | 37 +++ crypto/rsa/src/rsa_4096.rs | 39 +++ crypto/rsa/src/rsassa_pss_shake.rs | 96 +++++++ .../rsa/tests/rsa_2048_pss_shake128_tests.rs | 165 ++++++++++++ .../rsa/tests/rsa_3072_pss_shake128_tests.rs | 172 ++++++++++++ .../rsa/tests/rsa_4096_pss_shake256_tests.rs | 182 +++++++++++++ 10 files changed, 983 insertions(+) create mode 100644 crypto/rsa/src/emsa_pss_shake.rs create mode 100644 crypto/rsa/src/rsassa_pss_shake.rs create mode 100644 crypto/rsa/tests/rsa_2048_pss_shake128_tests.rs create mode 100644 crypto/rsa/tests/rsa_3072_pss_shake128_tests.rs create mode 100644 crypto/rsa/tests/rsa_4096_pss_shake256_tests.rs diff --git a/crypto/rsa/Cargo.toml b/crypto/rsa/Cargo.toml index f0d97d2e..4b10a4e4 100644 --- a/crypto/rsa/Cargo.toml +++ b/crypto/rsa/Cargo.toml @@ -8,6 +8,7 @@ bouncycastle-core.workspace = true bouncycastle-ec.workspace = true bouncycastle-rng.workspace = true bouncycastle-sha2.workspace = true +bouncycastle-sha3.workspace = true bouncycastle-utils.workspace = true [dev-dependencies] diff --git a/crypto/rsa/src/emsa_pss_shake.rs b/crypto/rsa/src/emsa_pss_shake.rs new file mode 100644 index 00000000..81a7f49d --- /dev/null +++ b/crypto/rsa/src/emsa_pss_shake.rs @@ -0,0 +1,244 @@ +//! EMSA-PSS with a SHAKE hash and native-SHAKE mask generation (RFC 8702 §3.2.1), rather than +//! MGF1: RFC 8017's own EMSA-PSS-ENCODE/VERIFY (§9.1), but per RFC 8702 §3.2.1 "the SHAKEs MUST be +//! used natively as the MGF, instead of the MGF1 algorithm ... In other words, the MGF is defined +//! as the SHAKE128 or SHAKE256 with input being the mgfSeed". A SHAKE (`X: XOF`) can already +//! produce an arbitrary-length output directly from one absorb, so this module has no counterpart +//! to [`crate::mgf1`] at all -- the "mask generation function" step is just `X::default().xof_out` +//! on the seed, one call instead of MGF1's counter loop. +//! +//! Otherwise this is [`crate::emsa_pss`] with `X` standing in for the hash: same steps, same +//! `8 * K_LEN - emBits == 1` simplification (see that module's docs) for the same reason (every +//! modulus size here is a whole number of 64-bit limbs). RFC 8702 §3.2.1 also fixes the hash +//! output length `H_LEN` and salt length `S_LEN` to be equal (32 bytes for SHAKE128, 64 for +//! SHAKE256) -- already this crate's own "typical" salt-length convention for MGF1-based PSS, so +//! no new relationship needs stating. + +use bouncycastle_core::traits::XOF; + +/// EMSA-PSS-ENCODE (RFC 8017 §9.1.1) with the mask generation function replaced by native SHAKE +/// output (RFC 8702 §3.2.1). See the module docs for `emBits` and the salt argument. +pub fn emsa_pss_encode_shake< + X: XOF + Default, + const H_LEN: usize, + const S_LEN: usize, + const M_PRIME_LEN: usize, + const DB_LEN: usize, + const K_LEN: usize, +>( + message: &[u8], + salt: &[u8; S_LEN], +) -> [u8; K_LEN] { + debug_assert_eq!(M_PRIME_LEN, 8 + H_LEN + S_LEN, "emsa_pss_encode_shake: M_PRIME_LEN mismatch"); + debug_assert_eq!(DB_LEN, K_LEN - H_LEN - 1, "emsa_pss_encode_shake: DB_LEN mismatch"); + debug_assert!( + K_LEN >= H_LEN + S_LEN + 2, + "emsa_pss_encode_shake: modulus too short for this hash/salt" + ); + + // Steps 1-2: mHash = Hash(M). + let mut m_hash = [0u8; H_LEN]; + X::default().hash_out(message, &mut m_hash); + + // Steps 5-6: M' = 8 zero octets || mHash || salt; H = Hash(M'). + let mut m_prime = [0u8; M_PRIME_LEN]; + m_prime[8..8 + H_LEN].copy_from_slice(&m_hash); + m_prime[8 + H_LEN..].copy_from_slice(salt); + let mut h = [0u8; H_LEN]; + X::default().hash_out(&m_prime, &mut h); + + // Steps 7-8: DB = PS || 0x01 || salt (PS is all-zero, already the array's initial value). + let mut db = [0u8; DB_LEN]; + db[DB_LEN - S_LEN - 1] = 0x01; + db[DB_LEN - S_LEN..].copy_from_slice(salt); + + // Steps 9-11: maskedDB = DB xor MGF(H, DB_LEN), the SHAKE itself in place of MGF1 (RFC 8702 + // SS3.2.1), then clear the top bit (see module docs). + let mut db_mask = [0u8; DB_LEN]; + X::default().xof_out(&h, &mut db_mask); + let mut masked_db = [0u8; DB_LEN]; + for i in 0..DB_LEN { + masked_db[i] = db[i] ^ db_mask[i]; + } + masked_db[0] &= 0x7f; + + // Step 12: EM = maskedDB || H || 0xbc. + let mut em = [0u8; K_LEN]; + em[..DB_LEN].copy_from_slice(&masked_db); + em[DB_LEN..DB_LEN + H_LEN].copy_from_slice(&h); + em[K_LEN - 1] = 0xbc; + em +} + +/// EMSA-PSS-VERIFY (RFC 8017 §9.1.2) with the mask generation function replaced by native SHAKE +/// output, as [`emsa_pss_encode_shake`]. +pub fn emsa_pss_verify_shake< + X: XOF + Default, + const H_LEN: usize, + const S_LEN: usize, + const M_PRIME_LEN: usize, + const DB_LEN: usize, + const K_LEN: usize, +>( + message: &[u8], + em: &[u8; K_LEN], +) -> bool { + // 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 mut masked_db = [0u8; DB_LEN]; + masked_db.copy_from_slice(&em[..DB_LEN]); + let mut h = [0u8; H_LEN]; + h.copy_from_slice(&em[DB_LEN..DB_LEN + H_LEN]); + + // Steps 7-9. + let mut db_mask = [0u8; DB_LEN]; + X::default().xof_out(&h, &mut db_mask); + let mut db = [0u8; DB_LEN]; + for i in 0..DB_LEN { + db[i] = masked_db[i] ^ db_mask[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 mut salt = [0u8; S_LEN]; + salt.copy_from_slice(&db[DB_LEN - S_LEN..]); + + // Steps 12-14. + let mut m_hash = [0u8; H_LEN]; + X::default().hash_out(message, &mut m_hash); + let mut m_prime = [0u8; M_PRIME_LEN]; + m_prime[8..8 + H_LEN].copy_from_slice(&m_hash); + m_prime[8 + H_LEN..].copy_from_slice(&salt); + let mut h_prime = [0u8; H_LEN]; + X::default().hash_out(&m_prime, &mut h_prime); + + h == h_prime +} + +#[cfg(test)] +mod tests { + //! `emsa_pss_encode_shake`/`emsa_pss_verify_shake` are crate-private (only + //! [`crate::rsassa_pss_shake`] 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 with RFC 8702 SS3.2.1's native-SHAKE mask substituted for MGF1 (not from + //! recall), using `hashlib.shake_128`. + + use super::*; + 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, + ]; + + fn encode(message: &[u8], salt: &[u8; 32]) -> [u8; 256] { + emsa_pss_encode_shake::(message, salt) + } + + fn verify(message: &[u8], em: &[u8; 256]) -> bool { + emsa_pss_verify_shake::(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/lib.rs b/crypto/rsa/src/lib.rs index 445cba66..39adcf48 100644 --- a/crypto/rsa/src/lib.rs +++ b/crypto/rsa/src/lib.rs @@ -59,6 +59,13 @@ //! 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. +//! +//! 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 also implemented ([`rsassa_pss_shake`], built on `emsa_pss_shake` rather than +//! `mgf1`), 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. #![no_std] #![forbid(unsafe_code)] @@ -67,6 +74,7 @@ mod codec; mod emsa_pkcs1_v1_5; mod emsa_pss; +mod emsa_pss_shake; pub mod keys; mod mgf1; pub mod modexp; @@ -79,3 +87,4 @@ pub mod rsa_8192; mod rsa_core; pub mod rsassa_pkcs1_v1_5; pub mod rsassa_pss; +pub mod rsassa_pss_shake; diff --git a/crypto/rsa/src/rsa_2048.rs b/crypto/rsa/src/rsa_2048.rs index e733fc86..dd71409c 100644 --- a/crypto/rsa/src/rsa_2048.rs +++ b/crypto/rsa/src/rsa_2048.rs @@ -10,9 +10,11 @@ use crate::keys::{RsaPrivateKey, RsaPublicKey}; use crate::rsassa_pkcs1_v1_5; use crate::rsassa_pss; +use crate::rsassa_pss_shake; use bouncycastle_core::errors::SignatureError; use bouncycastle_core::traits::RNG; use bouncycastle_sha2::{SHA256, SHA384, SHA512}; +use bouncycastle_sha3::SHAKE128; /// An RSA-2048 private key (`p`, `q` each 1024 bits). pub type Rsa2048PrivateKey = RsaPrivateKey<32, 16>; @@ -172,3 +174,39 @@ pub fn pss_verify_sha512( ) -> Result<(), SignatureError> { rsassa_pss::verify::(pk, message, signature) } + +/// RSASSA-PSS-SHAKE128 (`id-RSASSA-PSS-SHAKE128`, RFC 8702 §3.2.1) signing: SHAKE128 as both the +/// message hash and, natively rather than through MGF1, the mask generation function, with a +/// 32-byte salt drawn fresh from `rng` for each signature. RFC 8702 §5 recommends this pairing for +/// a 2048- or 3072-bit RSA modulus. See [`rsassa_pss_shake::sign`] for what each error means. +pub fn pss_shake128_sign( + sk: &Rsa2048PrivateKey, + message: &[u8], + rng: &mut dyn RNG, +) -> Result<[u8; 256], SignatureError> { + rsassa_pss_shake::sign::( + sk, message, rng, + ) +} + +/// As [`pss_shake128_sign`], but with the salt supplied directly instead of drawn from an RNG -- +/// deterministic, for testing against a known salt. See [`rsassa_pss_shake::sign_with_salt`]. +pub fn pss_shake128_sign_with_salt( + sk: &Rsa2048PrivateKey, + message: &[u8], + salt: &[u8; 32], +) -> Result<[u8; 256], SignatureError> { + rsassa_pss_shake::sign_with_salt::( + sk, message, salt, + ) +} + +/// RSASSA-PSS-SHAKE128 (RFC 8702 §3.2.1) verification. See [`rsassa_pss_shake::verify`] for what +/// each error means. +pub fn pss_shake128_verify( + pk: &Rsa2048PublicKey, + message: &[u8], + signature: &[u8; 256], +) -> Result<(), SignatureError> { + rsassa_pss_shake::verify::(pk, message, signature) +} diff --git a/crypto/rsa/src/rsa_3072.rs b/crypto/rsa/src/rsa_3072.rs index b6d46a74..40ca76d6 100644 --- a/crypto/rsa/src/rsa_3072.rs +++ b/crypto/rsa/src/rsa_3072.rs @@ -4,9 +4,11 @@ use crate::keys::{RsaPrivateKey, RsaPublicKey}; use crate::rsassa_pkcs1_v1_5; use crate::rsassa_pss; +use crate::rsassa_pss_shake; use bouncycastle_core::errors::SignatureError; use bouncycastle_core::traits::RNG; use bouncycastle_sha2::{SHA256, SHA384, SHA512}; +use bouncycastle_sha3::SHAKE128; /// An RSA-3072 private key (`p`, `q` each 1536 bits). pub type Rsa3072PrivateKey = RsaPrivateKey<48, 24>; @@ -162,3 +164,38 @@ pub fn pss_verify_sha512( ) -> Result<(), SignatureError> { rsassa_pss::verify::(pk, message, signature) } + +/// RSASSA-PSS-SHAKE128 (`id-RSASSA-PSS-SHAKE128`, RFC 8702 §3.2.1) signing: SHAKE128 as both the +/// message hash and, natively rather than through MGF1, the mask generation function, with a +/// 32-byte salt drawn fresh from `rng`. RFC 8702 §5 recommends this pairing for a 2048- or +/// 3072-bit RSA modulus. See [`rsassa_pss_shake::sign`] for what each error means. +pub fn pss_shake128_sign( + sk: &Rsa3072PrivateKey, + message: &[u8], + rng: &mut dyn RNG, +) -> Result<[u8; 384], SignatureError> { + rsassa_pss_shake::sign::( + sk, message, rng, + ) +} + +/// As [`pss_shake128_sign`], but with the salt supplied directly instead of drawn from an RNG. +pub fn pss_shake128_sign_with_salt( + sk: &Rsa3072PrivateKey, + message: &[u8], + salt: &[u8; 32], +) -> Result<[u8; 384], SignatureError> { + rsassa_pss_shake::sign_with_salt::( + sk, message, salt, + ) +} + +/// RSASSA-PSS-SHAKE128 (RFC 8702 §3.2.1) verification. See [`rsassa_pss_shake::verify`] for what +/// each error means. +pub fn pss_shake128_verify( + pk: &Rsa3072PublicKey, + message: &[u8], + signature: &[u8; 384], +) -> Result<(), SignatureError> { + rsassa_pss_shake::verify::(pk, message, signature) +} diff --git a/crypto/rsa/src/rsa_4096.rs b/crypto/rsa/src/rsa_4096.rs index afd33fcd..c743c3b4 100644 --- a/crypto/rsa/src/rsa_4096.rs +++ b/crypto/rsa/src/rsa_4096.rs @@ -4,9 +4,11 @@ use crate::keys::{RsaPrivateKey, RsaPublicKey}; use crate::rsassa_pkcs1_v1_5; use crate::rsassa_pss; +use crate::rsassa_pss_shake; use bouncycastle_core::errors::SignatureError; use bouncycastle_core::traits::RNG; use bouncycastle_sha2::{SHA256, SHA384, SHA512}; +use bouncycastle_sha3::SHAKE256; /// An RSA-4096 private key (`p`, `q` each 2048 bits). pub type Rsa4096PrivateKey = RsaPrivateKey<64, 32>; @@ -166,3 +168,40 @@ pub fn pss_verify_sha512( ) -> Result<(), SignatureError> { rsassa_pss::verify::(pk, message, signature) } + +/// RSASSA-PSS-SHAKE256 (`id-RSASSA-PSS-SHAKE256`, RFC 8702 §3.2.1) signing: SHAKE256 as both the +/// message hash and, natively rather than through MGF1, the mask generation function, with a +/// 64-byte salt drawn fresh from `rng`. RFC 8702 §5 recommends this pairing for a 4096-bit or +/// larger RSA modulus. See [`rsassa_pss_shake::sign`] for what each error means. +pub fn pss_shake256_sign( + sk: &Rsa4096PrivateKey, + message: &[u8], + rng: &mut dyn RNG, +) -> Result<[u8; 512], SignatureError> { + rsassa_pss_shake::sign::( + sk, message, rng, + ) +} + +/// As [`pss_shake256_sign`], but with the salt supplied directly instead of drawn from an RNG. +pub fn pss_shake256_sign_with_salt( + sk: &Rsa4096PrivateKey, + message: &[u8], + salt: &[u8; 64], +) -> Result<[u8; 512], SignatureError> { + rsassa_pss_shake::sign_with_salt::( + sk, message, salt, + ) +} + +/// RSASSA-PSS-SHAKE256 (RFC 8702 §3.2.1) verification. See [`rsassa_pss_shake::verify`] for what +/// each error means. +pub fn pss_shake256_verify( + pk: &Rsa4096PublicKey, + message: &[u8], + signature: &[u8; 512], +) -> Result<(), SignatureError> { + rsassa_pss_shake::verify::( + pk, message, signature, + ) +} diff --git a/crypto/rsa/src/rsassa_pss_shake.rs b/crypto/rsa/src/rsassa_pss_shake.rs new file mode 100644 index 00000000..894ba81e --- /dev/null +++ b/crypto/rsa/src/rsassa_pss_shake.rs @@ -0,0 +1,96 @@ +//! RSASSA-PSS with SHAKE128 or SHAKE256 as both the hash and the (native, non-MGF1) mask +//! generation function -- `id-RSASSA-PSS-SHAKE128`/`id-RSASSA-PSS-SHAKE256` (RFC 8702 §3.2.1). +//! Otherwise identical to [`crate::rsassa_pss`] (RFC 8017 §8.1): same RSASP1/RSAVP1 orchestration, +//! same fresh-salt-per-signature approach, just built on [`crate::emsa_pss_shake`] in place of +//! [`crate::emsa_pss`]. + +use crate::codec::{be_bytes_from_limbs, limbs_from_be_bytes}; +use crate::emsa_pss_shake::{emsa_pss_encode_shake, emsa_pss_verify_shake}; +use crate::keys::{RsaPrivateKey, RsaPublicKey}; +use crate::rsa_core::{rsasp1, rsavp1}; +use bouncycastle_core::errors::SignatureError; +use bouncycastle_core::traits::{RNG, XOF}; + +/// RSASSA-PSS-SIGN (RFC 8017 §8.1.1) with the salt supplied directly rather than drawn from an +/// RNG, mirroring [`crate::rsassa_pss::sign_with_salt`]: EMSA-PSS is randomized only in its choice +/// of salt, so fixing it makes this deterministic and directly testable. [`sign`] is the +/// RNG-backed entry point real callers want. +pub fn sign_with_salt< + X: XOF + Default, + const H_LEN: usize, + const S_LEN: usize, + const M_PRIME_LEN: usize, + const DB_LEN: usize, + const L: usize, + const L2: usize, + const L21: usize, + const HALF: usize, + const HALF2: usize, + const HALF21: usize, + const K_LEN: usize, +>( + sk: &RsaPrivateKey, + message: &[u8], + salt: &[u8; S_LEN], +) -> Result<[u8; K_LEN], SignatureError> { + let em = emsa_pss_encode_shake::(message, salt); + let m = limbs_from_be_bytes::(&em); + let s = rsasp1::(sk, &m)?; + Ok(be_bytes_from_limbs::(&s)) +} + +/// RSASSA-PSS-SIGN (RFC 8017 §8.1.1), drawing a fresh `S_LEN`-byte salt from `rng` for each +/// signature (step 4 of EMSA-PSS-ENCODE). RFC 8702 §3.2.1 fixes `S_LEN` at 32 bytes for +/// `id-RSASSA-PSS-SHAKE128` and 64 for `id-RSASSA-PSS-SHAKE256`. +pub fn sign< + X: XOF + Default, + const H_LEN: usize, + const S_LEN: usize, + const M_PRIME_LEN: usize, + const DB_LEN: usize, + const L: usize, + const L2: usize, + const L21: usize, + const HALF: usize, + const HALF2: usize, + const HALF21: usize, + const K_LEN: usize, +>( + sk: &RsaPrivateKey, + message: &[u8], + rng: &mut dyn RNG, +) -> Result<[u8; K_LEN], SignatureError> { + let mut salt = [0u8; S_LEN]; + rng.next_bytes_out(&mut salt).map_err(SignatureError::RNGError)?; + sign_with_salt::( + sk, message, &salt, + ) +} + +/// RSASSA-PSS-VERIFY (RFC 8017 §8.1.2), mirroring [`crate::rsassa_pss::verify`] but built on +/// [`emsa_pss_verify_shake`], which recovers the salt from `EM` itself. +pub fn verify< + X: XOF + Default, + const H_LEN: usize, + const S_LEN: usize, + const M_PRIME_LEN: usize, + const DB_LEN: usize, + const L: usize, + const L2: usize, + const L21: usize, + const K_LEN: usize, +>( + pk: &RsaPublicKey, + message: &[u8], + signature: &[u8; K_LEN], +) -> Result<(), SignatureError> { + let s = limbs_from_be_bytes::(signature); + let m = rsavp1::(pk, &s)?; + let em = be_bytes_from_limbs::(&m); + + if emsa_pss_verify_shake::(message, &em) { + Ok(()) + } else { + Err(SignatureError::SignatureVerificationFailed) + } +} 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..c492bd51 --- /dev/null +++ b/crypto/rsa/tests/rsa_2048_pss_shake128_tests.rs @@ -0,0 +1,165 @@ +//! 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_hex::decode as hex_decode; +use bouncycastle_rng::DefaultRNG; +use bouncycastle_rsa::rsa_2048::{ + Rsa2048PrivateKey, Rsa2048PublicKey, pss_shake128_sign, pss_shake128_sign_with_salt, + pss_shake128_verify, +}; +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/MGF1 specifically. +fn genuine_key() -> Rsa2048PrivateKey { + 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, + ]; + Rsa2048PrivateKey::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 = Rsa2048PublicKey::new(sk.n(), 0x10001).unwrap(); + + let salt = [0x42u8; 32]; + let sig = pss_shake128_sign_with_salt(&sk, b"the message to sign", &salt) + .expect("signing must succeed"); + pss_shake128_verify(&pk, b"the message to sign", &sig).expect("must verify"); + + // Deterministic given the same salt. + let sig2 = pss_shake128_sign_with_salt(&sk, b"the message to sign", &salt).unwrap(); + assert_eq!(sig, sig2); + + assert!(pss_shake128_verify(&pk, b"a different message", &sig).is_err()); +} + +#[test] +fn pss_shake128_sign_with_rng_produces_fresh_salts_that_both_verify() { + let sk = genuine_key(); + let pk = Rsa2048PublicKey::new(sk.n(), 0x10001).unwrap(); + let mut rng = DefaultRNG::default(); + + let sig_a = pss_shake128_sign(&sk, b"hello", &mut rng).expect("signing must succeed"); + let sig_b = pss_shake128_sign(&sk, b"hello", &mut rng).expect("signing must succeed"); + assert_ne!(sig_a, sig_b, "PSS is randomized: two signatures of the same message must differ"); + pss_shake128_verify(&pk, b"hello", &sig_a).expect("sig_a must verify"); + pss_shake128_verify(&pk, b"hello", &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 = Rsa2048PublicKey::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 = pss_shake128_verify(&pk, &msg, &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); +} 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..ff652558 --- /dev/null +++ b/crypto/rsa/tests/rsa_3072_pss_shake128_tests.rs @@ -0,0 +1,172 @@ +//! 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_hex::decode as hex_decode; +use bouncycastle_rng::DefaultRNG; +use bouncycastle_rsa::rsa_3072::{ + Rsa3072PrivateKey, Rsa3072PublicKey, pss_shake128_sign, pss_shake128_sign_with_salt, + pss_shake128_verify, +}; +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-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() -> Rsa3072PrivateKey { + 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, + ]; + Rsa3072PrivateKey::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 = Rsa3072PublicKey::new(sk.n(), 0x10001).unwrap(); + + let salt = [0x42u8; 32]; + let sig = pss_shake128_sign_with_salt(&sk, b"the message to sign", &salt) + .expect("signing must succeed"); + pss_shake128_verify(&pk, b"the message to sign", &sig).expect("must verify"); + + let sig2 = pss_shake128_sign_with_salt(&sk, b"the message to sign", &salt).unwrap(); + assert_eq!(sig, sig2); + + assert!(pss_shake128_verify(&pk, b"a different message", &sig).is_err()); +} + +#[test] +fn pss_shake128_sign_with_rng_produces_fresh_salts_that_both_verify() { + let sk = genuine_key(); + let pk = Rsa3072PublicKey::new(sk.n(), 0x10001).unwrap(); + let mut rng = DefaultRNG::default(); + + let sig_a = pss_shake128_sign(&sk, b"hello", &mut rng).expect("signing must succeed"); + let sig_b = pss_shake128_sign(&sk, b"hello", &mut rng).expect("signing must succeed"); + assert_ne!(sig_a, sig_b, "PSS is randomized: two signatures of the same message must differ"); + pss_shake128_verify(&pk, b"hello", &sig_a).expect("sig_a must verify"); + pss_shake128_verify(&pk, b"hello", &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 = Rsa3072PublicKey::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 = pss_shake128_verify(&pk, &msg, &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); +} 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..87f80f87 --- /dev/null +++ b/crypto/rsa/tests/rsa_4096_pss_shake256_tests.rs @@ -0,0 +1,182 @@ +//! 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_hex::decode as hex_decode; +use bouncycastle_rng::DefaultRNG; +use bouncycastle_rsa::rsa_4096::{ + Rsa4096PrivateKey, Rsa4096PublicKey, pss_shake256_sign, pss_shake256_sign_with_salt, + pss_shake256_verify, +}; +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-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() -> Rsa4096PrivateKey { + 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, + ]; + Rsa4096PrivateKey::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 = Rsa4096PublicKey::new(sk.n(), 0x10001).unwrap(); + + let salt = [0x42u8; 64]; + let sig = pss_shake256_sign_with_salt(&sk, b"the message to sign", &salt) + .expect("signing must succeed"); + pss_shake256_verify(&pk, b"the message to sign", &sig).expect("must verify"); + + let sig2 = pss_shake256_sign_with_salt(&sk, b"the message to sign", &salt).unwrap(); + assert_eq!(sig, sig2); + + assert!(pss_shake256_verify(&pk, b"a different message", &sig).is_err()); +} + +#[test] +fn pss_shake256_sign_with_rng_produces_fresh_salts_that_both_verify() { + let sk = genuine_key(); + let pk = Rsa4096PublicKey::new(sk.n(), 0x10001).unwrap(); + let mut rng = DefaultRNG::default(); + + let sig_a = pss_shake256_sign(&sk, b"hello", &mut rng).expect("signing must succeed"); + let sig_b = pss_shake256_sign(&sk, b"hello", &mut rng).expect("signing must succeed"); + assert_ne!(sig_a, sig_b, "PSS is randomized: two signatures of the same message must differ"); + pss_shake256_verify(&pk, b"hello", &sig_a).expect("sig_a must verify"); + pss_shake256_verify(&pk, b"hello", &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 = Rsa4096PublicKey::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 = pss_shake256_verify(&pk, &msg, &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); +} From 6e2cb49d7fdc4dab5c4ce5d8323994c03ad668f0 Mon Sep 17 00:00:00 2001 From: David Hook Date: Sat, 19 Sep 2026 22:30:13 +1000 Subject: [PATCH 09/55] rsa: CLI subcommands, criterion benches, and a stack-usage harness Adds the pieces every primitive in this repo owes per QUALITY_AND_STYLE.md (CLI, benches, mem_usage_benches) for bouncycastle-rsa, which had none of the three yet. CLI (cli/src/rsa_cmd.rs): one subcommand per modulus size (rsa-1024 .. rsa-8192) rather than one per (scheme, hash) pair. ECDSA and HMAC each vary along a single axis (curve, or hash), so one subcommand per concrete instantiation is the natural fit there; RSA varies along three independent axes -- modulus size, scheme (PKCS#1 v1.5/PSS), and hash -- and multiplying all three out would mean over thirty near-identical subcommands for what is fundamentally one primitive per modulus size. Modulus size stays the subcommand-selecting axis (it fixes the key and signature byte lengths, the same reason ecdsa_cmd.rs picks one command per curve); scheme and hash become --scheme/--hash flags. Two generic dispatchers (rsa_pkcs1_cmd, rsa_pss_cmd -- split because PSS's sign takes an RNG and PKCS#1 v1.5's doesn't) cover every concrete function pointer, mirroring ecdsa_cmd.rs's own "one generic function, monomorphised per instantiation" shape. There is no Keygen action (this crate has no RSA key generation at all -- see keys.rs's own docs) and no PkFromSk (a private key's CRT components alone do not determine the public exponent e, so there is nothing to derive a public key from). 1024/1536 take no --action/--skfile at all: they are verification-only in this crate. Key file I/O needed a byte encoding this crate didn't have: keys.rs gains RsaPrivateKey::encode/from_bytes (p || q || dP || dQ || qInv, each HALF_BYTES = 8 * HALF bytes) and RsaPublicKey::encode/from_bytes (n || e, N_BYTES = 8 * L bytes then 4). Deliberately not PEM or ASN.1 DER -- this crate has no encoder for either -- just a fixed-width raw layout, so a key from another RSA implementation can't be fed to this CLI directly. from_bytes reuses from_crt_components'/new's existing validation, so bad input is rejected the same way either constructor already rejects it; keys_tests.rs adds round-trip and rejection tests for both. Smoke-tested end to end: sign+verify round trip and a PSS-SHAKE128 round trip through the built CLI binary, plus a genuine Wycheproof RSA-1024 signature verified through it (tcId from rsa_pkcs1_1024_sig_gen_test.json). Benches (crypto/rsa/benches/rsa_*_benches.rs, one file per modulus size): every (scheme, hash) pairing that size wires up gets its own bench_function, since SHA-256/384/512 and SHAKE128/256 each have a different hashing cost and PKCS#1 v1.5 vs PSS differ by a salt draw and MGF1/native-SHAKE masking. Genuine keys throughout, reusing exactly the CRT components each tests/rsa_*.rs file already recovered/generated (no freshly fabricated key material). All six smoke-tested with `cargo bench -- --test` (a single untimed run of every bench_function) rather than a full statistical pass, given RSA-8192's per-operation cost. Stack usage (mem_usage_benches/src/bench_rsa_mem_usage.rs): only one representative pairing (PKCS#1 v1.5/SHA-256) is benched, at three modulus sizes (1024 verify-only, 2048, 8192) rather than every size and every (scheme, hash) combination -- peak stack usage here is dominated by the const-generic-width RSASP1/RSAVP1 modular exponentiation (L, the modulus's own limb count), not by which hash or scheme fed into it; the criterion benches above are where per-hash/per-scheme *time* differences are measured instead. Each non-default function was run once manually to confirm it actually signs/verifies correctly before being wired behind main()'s commented-out calls (the same pattern bench_ecdsa_mem_usage.rs uses). Wiring: bouncycastle-rsa is now re-exported from the umbrella `bouncycastle` crate (src/lib.rs, root Cargo.toml) so the CLI and mem_usage_benches -- which depend on `bouncycastle`, not the sub-crate directly -- can reach it. cargo test -p bouncycastle-rsa and -p cli both pass; cargo clippy and cargo fmt are clean on every new/changed file. Mutation testing remains deferred to a single consolidated pass across the whole crate once every planned step is in. Co-Authored-By: Claude Sonnet 5 --- Cargo.toml | 1 + cli/src/main.rs | 298 ++++++++++ cli/src/rsa_cmd.rs | 588 +++++++++++++++++++ crypto/rsa/Cargo.toml | 24 + crypto/rsa/benches/rsa_1024_benches.rs | 70 +++ crypto/rsa/benches/rsa_1536_benches.rs | 87 +++ crypto/rsa/benches/rsa_2048_benches.rs | 155 +++++ crypto/rsa/benches/rsa_3072_benches.rs | 163 +++++ crypto/rsa/benches/rsa_4096_benches.rs | 174 ++++++ crypto/rsa/benches/rsa_8192_benches.rs | 199 +++++++ crypto/rsa/src/keys.rs | 91 +++ crypto/rsa/tests/keys_tests.rs | 40 ++ mem_usage_benches/Cargo.toml | 4 + mem_usage_benches/src/bench_rsa_mem_usage.rs | 281 +++++++++ mem_usage_benches/src/lib.rs | 1 + src/lib.rs | 1 + 16 files changed, 2177 insertions(+) create mode 100644 cli/src/rsa_cmd.rs create mode 100644 crypto/rsa/benches/rsa_1024_benches.rs create mode 100644 crypto/rsa/benches/rsa_1536_benches.rs create mode 100644 crypto/rsa/benches/rsa_2048_benches.rs create mode 100644 crypto/rsa/benches/rsa_3072_benches.rs create mode 100644 crypto/rsa/benches/rsa_4096_benches.rs create mode 100644 crypto/rsa/benches/rsa_8192_benches.rs create mode 100644 mem_usage_benches/src/bench_rsa_mem_usage.rs diff --git a/Cargo.toml b/Cargo.toml index cc2a93e5..1d742073 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -83,6 +83,7 @@ bouncycastle-mlkem.workspace = true bouncycastle-mlkem-lowmemory.workspace = true bouncycastle-poly1305.workspace = true bouncycastle-rng.workspace = true +bouncycastle-rsa.workspace = true bouncycastle-sha2.workspace = true bouncycastle-sha3.workspace = true bouncycastle-sm2.workspace = true diff --git a/cli/src/main.rs b/cli/src/main.rs index 635260d2..f33dc22b 100644 --- a/cli/src/main.rs +++ b/cli/src/main.rs @@ -19,6 +19,8 @@ mod mac_cmd; mod mldsa_cmd; mod mlkem_cmd; mod rng_cmd; +mod rsa_cmd; +mod rsasve_cmd; mod sha2_cmd; mod sha3_cmd; mod sm2_cmd; @@ -29,6 +31,8 @@ use crate::hkdf_cmd::HKDFVariant; use crate::mac_cmd::HMACVariant; use crate::mldsa_cmd::{MLDSAAction, PreHashAlg}; use crate::rng_cmd::DrbgHash; +use crate::rsa_cmd::{RSAAction, RSAHash, RSAScheme}; +use crate::rsasve_cmd::RSASVEAction; use crate::sha2_cmd::SHA2Variant; use crate::sha3_cmd::{SHA3Variant, Strength}; use crate::sm2_cmd::SM2Action; @@ -2844,6 +2848,270 @@ 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, + }, + + /// 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 @@ -3511,6 +3779,36 @@ 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_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); } diff --git a/cli/src/rsa_cmd.rs b/cli/src/rsa_cmd.rs new file mode 100644 index 00000000..ebb500c0 --- /dev/null +++ b/cli/src/rsa_cmd.rs @@ -0,0 +1,588 @@ +//! 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. +//! +//! `bouncycastle_rsa` does not generate keys (see that crate's `keys` module docs), so there is no +//! `Keygen` action here, and no `PkFromSk` either -- a private key's CRT components alone do not +//! determine the public exponent `e`, so there is nothing to derive a public key from. Private and +//! public key files use `RsaPrivateKey::encode`/`RsaPublicKey::encode`'s raw fixed-width layout +//! (documented on those methods): 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. +//! +//! Reads the whole message into memory (`read_all_stdin`) rather than this CLI's usual ~1 KB +//! streaming buffer: RSASSA-PKCS1-v1_5 and RSASSA-PSS both hash the entire message before any +//! signing/verification step can begin, and `bouncycastle_rsa`'s sign/verify functions take the +//! whole message as one slice -- there is no incremental hash state to feed a chunk at a time. + +use crate::helpers::{read_from_file, write_bytes_or_hex}; +use bouncycastle::core::errors::SignatureError; +use bouncycastle::core::traits::RNG; +use bouncycastle::rng::DefaultRNG; +use bouncycastle::rsa::keys::{RsaPrivateKey, RsaPublicKey}; +use clap::ValueEnum; +use std::io; +use std::io::Read; +use std::process::exit; + +#[derive(ValueEnum, Clone, Debug, PartialEq, Eq)] +pub(crate) enum RSAAction { + /// 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, +} + +fn require_file(file: &Option, flag_name: &str) -> Vec { + match file { + Some(f) => read_from_file(f), + None => { + eprintln!("Error: no {flag_name} provided."); + exit(-1); + } + } +} + +/// The message is read raw, never hex-decoded: unlike a key or signature file, arbitrary message +/// bytes that happen to look like hex must still be signed/verified byte-for-byte. +fn read_all_stdin() -> Vec { + let mut buf = Vec::new(); + io::stdin().read_to_end(&mut buf).expect("Failed to read from stdin"); + buf +} + +fn unsupported(scheme: &RSAScheme, hash: &RSAHash, alg_name: &str) -> ! { + eprintln!("Error: {scheme:?}/{hash:?} is not supported for {alg_name}."); + exit(-1); +} + +/// A `bouncycastle_rsa::rsa_*::pkcs1_v1_5_sign_*` function. +type PkcsSignFn = + fn(&RsaPrivateKey, &[u8]) -> Result<[u8; SIG_LEN], SignatureError>; +/// A `bouncycastle_rsa::rsa_*::pss_sign_*`/`pss_shake*_sign` function. +type PssSignFn = + fn(&RsaPrivateKey, &[u8], &mut dyn RNG) -> Result<[u8; SIG_LEN], SignatureError>; +/// A `bouncycastle_rsa::rsa_*::{pkcs1_v1_5,pss,pss_shake*}_verify_*` function -- the same shape +/// for every scheme, since verification never needs an RNG. +type VerifyFn = + fn(&RsaPublicKey, &[u8], &[u8; SIG_LEN]) -> Result<(), SignatureError>; + +/// See [`RsaPrivateKey::from_bytes`] for the expected layout. +fn parse_sk( + bytes: &[u8], + alg_name: &str, +) -> RsaPrivateKey { + let Ok(arr): Result<[u8; SK_LEN], _> = bytes.try_into() else { + eprintln!("Error: {alg_name} private key file must be exactly {SK_LEN} bytes."); + exit(-1); + }; + match RsaPrivateKey::::from_bytes::(&arr) { + Ok(sk) => sk, + Err(_) => { + eprintln!("Error: couldn't parse the input as a valid {alg_name} private key."); + exit(-1); + } + } +} + +/// See [`RsaPublicKey::from_bytes`] for the expected layout. +fn parse_pk( + bytes: &[u8], + alg_name: &str, +) -> RsaPublicKey { + let Ok(arr): Result<[u8; PK_LEN], _> = bytes.try_into() else { + eprintln!("Error: {alg_name} public key file must be exactly {PK_LEN} bytes."); + exit(-1); + }; + match RsaPublicKey::::from_bytes::(&arr) { + Ok(pk) => pk, + Err(_) => { + eprintln!("Error: couldn't parse the input as a valid {alg_name} public key."); + exit(-1); + } + } +} + +/// Shared by [`rsa_pkcs1_cmd`] and [`rsa_pss_cmd`]'s `Verify` arm, and called directly by the +/// verify-only sizes (`rsa_1024_cmd`, `rsa_1536_cmd`). +fn do_verify( + verify: VerifyFn, + pkfile: &Option, + sigfile: &Option, + alg_name: &str, +) { + let pk_bytes = require_file(pkfile, "pkfile"); + let pk = parse_pk::(&pk_bytes, alg_name); + let sig_bytes = require_file(sigfile, "sigfile"); + let Ok(sig): Result<[u8; SIG_LEN], _> = sig_bytes.try_into() else { + eprintln!("Error: signature file must be exactly {SIG_LEN} bytes for {alg_name}."); + exit(-1); + }; + let msg = read_all_stdin(); + if verify(&pk, &msg, &sig).is_ok() { + println!("Signature is valid."); + } else { + eprintln!("Signature is invalid."); + exit(-1); + } +} + +/// RSASSA-PKCS1-v1_5 (deterministic: `sign` takes no RNG). See [`rsa_pss_cmd`] for the PSS +/// counterpart. +#[allow(clippy::too_many_arguments)] +fn rsa_pkcs1_cmd< + const HALF: usize, + const L: usize, + const HALF_BYTES: usize, + const SK_LEN: usize, + const N_BYTES: usize, + const PK_LEN: usize, + const SIG_LEN: usize, +>( + action: &RSAAction, + sign: PkcsSignFn, + verify: VerifyFn, + skfile: &Option, + pkfile: &Option, + sigfile: &Option, + output_hex: bool, + alg_name: &str, +) { + match action { + RSAAction::Sign => { + let sk_bytes = require_file(skfile, "skfile"); + let sk = parse_sk::(&sk_bytes, alg_name); + let msg = read_all_stdin(); + let sig = sign(&sk, &msg).unwrap_or_else(|_| { + eprintln!("Error: signing failed."); + exit(-1); + }); + write_bytes_or_hex(&sig, output_hex); + } + RSAAction::Verify => { + do_verify::(verify, pkfile, sigfile, alg_name) + } + } +} + +/// RSASSA-PSS (randomized: `sign` draws a fresh salt from a [`DefaultRNG`] each call), covering +/// both the MGF1-based scheme (RFC 8017 §8.1) and the SHAKE-native one (RFC 8702 §3.2.1) -- their +/// `sign`/`verify` function shapes are identical, only the concrete function passed in differs. +#[allow(clippy::too_many_arguments)] +fn rsa_pss_cmd< + const HALF: usize, + const L: usize, + const HALF_BYTES: usize, + const SK_LEN: usize, + const N_BYTES: usize, + const PK_LEN: usize, + const SIG_LEN: usize, +>( + action: &RSAAction, + sign: PssSignFn, + verify: VerifyFn, + skfile: &Option, + pkfile: &Option, + sigfile: &Option, + output_hex: bool, + alg_name: &str, +) { + match action { + RSAAction::Sign => { + let sk_bytes = require_file(skfile, "skfile"); + let sk = parse_sk::(&sk_bytes, alg_name); + let msg = read_all_stdin(); + let mut rng = DefaultRNG::default(); + let sig = sign(&sk, &msg, &mut rng).unwrap_or_else(|_| { + eprintln!("Error: signing failed."); + exit(-1); + }); + write_bytes_or_hex(&sig, output_hex); + } + RSAAction::Verify => { + do_verify::(verify, pkfile, sigfile, alg_name) + } + } +} + +/// RSA-1024: verification only (see module docs). `L = 16`, `N_BYTES = 128`, `PK_LEN = 132`, +/// `SIG_LEN = 128`. No SHA-512 or PSS group exists in Wycheproof at this size (see +/// `bouncycastle_rsa::rsa_1024`'s own docs), so neither is wired up here either. +pub(crate) fn rsa_1024_cmd( + scheme: &RSAScheme, + hash: &RSAHash, + pkfile: &Option, + sigfile: &Option, +) { + use bouncycastle::rsa::rsa_1024::{pkcs1_v1_5_verify_sha256, pkcs1_v1_5_verify_sha384}; + match (scheme, hash) { + (RSAScheme::Pkcs1v15, RSAHash::Sha256) => do_verify::<16, 128, 132, 128>( + pkcs1_v1_5_verify_sha256, + pkfile, + sigfile, + "RSA-1024/PKCS#1v1.5/SHA-256", + ), + (RSAScheme::Pkcs1v15, RSAHash::Sha384) => do_verify::<16, 128, 132, 128>( + pkcs1_v1_5_verify_sha384, + pkfile, + sigfile, + "RSA-1024/PKCS#1v1.5/SHA-384", + ), + (scheme, hash) => unsupported(scheme, hash, "RSA-1024"), + } +} + +/// RSA-1536: verification only (see module docs). `L = 24`, `N_BYTES = 192`, `PK_LEN = 196`, +/// `SIG_LEN = 192`. No PSS group exists in Wycheproof at this size. +pub(crate) fn rsa_1536_cmd( + scheme: &RSAScheme, + hash: &RSAHash, + pkfile: &Option, + sigfile: &Option, +) { + use bouncycastle::rsa::rsa_1536::{ + pkcs1_v1_5_verify_sha256, pkcs1_v1_5_verify_sha384, pkcs1_v1_5_verify_sha512, + }; + match (scheme, hash) { + (RSAScheme::Pkcs1v15, RSAHash::Sha256) => do_verify::<24, 192, 196, 192>( + pkcs1_v1_5_verify_sha256, + pkfile, + sigfile, + "RSA-1536/PKCS#1v1.5/SHA-256", + ), + (RSAScheme::Pkcs1v15, RSAHash::Sha384) => do_verify::<24, 192, 196, 192>( + pkcs1_v1_5_verify_sha384, + pkfile, + sigfile, + "RSA-1536/PKCS#1v1.5/SHA-384", + ), + (RSAScheme::Pkcs1v15, RSAHash::Sha512) => do_verify::<24, 192, 196, 192>( + pkcs1_v1_5_verify_sha512, + pkfile, + sigfile, + "RSA-1536/PKCS#1v1.5/SHA-512", + ), + (scheme, hash) => unsupported(scheme, hash, "RSA-1536"), + } +} + +/// RSA-2048: sign and verify. `HALF = 16`, `L = 32`, `HALF_BYTES = 128`, `SK_LEN = 640`, `N_BYTES +/// = 256`, `PK_LEN = 260`, `SIG_LEN = 256`. `--hash shake128` is the only SHAKE choice wired up at +/// this size (RFC 8702 §5 pairs SHAKE128 with 2048/3072-bit RSA, SHAKE256 with 4096-bit or +/// larger). +#[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 bouncycastle::rsa::rsa_2048::{ + pkcs1_v1_5_sign_sha256, pkcs1_v1_5_sign_sha384, pkcs1_v1_5_sign_sha512, + pkcs1_v1_5_verify_sha256, pkcs1_v1_5_verify_sha384, pkcs1_v1_5_verify_sha512, + pss_shake128_sign, pss_shake128_verify, pss_sign_sha256, pss_sign_sha384, pss_sign_sha512, + pss_verify_sha256, pss_verify_sha384, pss_verify_sha512, + }; + match (scheme, hash) { + (RSAScheme::Pkcs1v15, RSAHash::Sha256) => rsa_pkcs1_cmd::<16, 32, 128, 640, 256, 260, 256>( + action, + pkcs1_v1_5_sign_sha256, + pkcs1_v1_5_verify_sha256, + skfile, + pkfile, + sigfile, + output_hex, + "RSA-2048/PKCS#1v1.5/SHA-256", + ), + (RSAScheme::Pkcs1v15, RSAHash::Sha384) => rsa_pkcs1_cmd::<16, 32, 128, 640, 256, 260, 256>( + action, + pkcs1_v1_5_sign_sha384, + pkcs1_v1_5_verify_sha384, + skfile, + pkfile, + sigfile, + output_hex, + "RSA-2048/PKCS#1v1.5/SHA-384", + ), + (RSAScheme::Pkcs1v15, RSAHash::Sha512) => rsa_pkcs1_cmd::<16, 32, 128, 640, 256, 260, 256>( + action, + pkcs1_v1_5_sign_sha512, + pkcs1_v1_5_verify_sha512, + skfile, + pkfile, + sigfile, + output_hex, + "RSA-2048/PKCS#1v1.5/SHA-512", + ), + (RSAScheme::Pss, RSAHash::Sha256) => rsa_pss_cmd::<16, 32, 128, 640, 256, 260, 256>( + action, pss_sign_sha256, pss_verify_sha256, skfile, pkfile, sigfile, output_hex, + "RSA-2048/PSS/SHA-256", + ), + (RSAScheme::Pss, RSAHash::Sha384) => rsa_pss_cmd::<16, 32, 128, 640, 256, 260, 256>( + action, pss_sign_sha384, pss_verify_sha384, skfile, pkfile, sigfile, output_hex, + "RSA-2048/PSS/SHA-384", + ), + (RSAScheme::Pss, RSAHash::Sha512) => rsa_pss_cmd::<16, 32, 128, 640, 256, 260, 256>( + action, pss_sign_sha512, pss_verify_sha512, skfile, pkfile, sigfile, output_hex, + "RSA-2048/PSS/SHA-512", + ), + (RSAScheme::Pss, RSAHash::Shake128) => rsa_pss_cmd::<16, 32, 128, 640, 256, 260, 256>( + action, pss_shake128_sign, pss_shake128_verify, skfile, pkfile, sigfile, output_hex, + "RSA-2048/PSS-SHAKE128", + ), + (scheme, hash) => unsupported(scheme, hash, "RSA-2048"), + } +} + +/// RSA-3072: sign and verify. `HALF = 24`, `L = 48`, `HALF_BYTES = 192`, `SK_LEN = 960`, `N_BYTES +/// = 384`, `PK_LEN = 388`, `SIG_LEN = 384`. See [`rsa_2048_cmd`] for the SHAKE128 pairing +/// rationale. +#[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 bouncycastle::rsa::rsa_3072::{ + pkcs1_v1_5_sign_sha256, pkcs1_v1_5_sign_sha384, pkcs1_v1_5_sign_sha512, + pkcs1_v1_5_verify_sha256, pkcs1_v1_5_verify_sha384, pkcs1_v1_5_verify_sha512, + pss_shake128_sign, pss_shake128_verify, pss_sign_sha256, pss_sign_sha384, pss_sign_sha512, + pss_verify_sha256, pss_verify_sha384, pss_verify_sha512, + }; + match (scheme, hash) { + (RSAScheme::Pkcs1v15, RSAHash::Sha256) => rsa_pkcs1_cmd::<24, 48, 192, 960, 384, 388, 384>( + action, + pkcs1_v1_5_sign_sha256, + pkcs1_v1_5_verify_sha256, + skfile, + pkfile, + sigfile, + output_hex, + "RSA-3072/PKCS#1v1.5/SHA-256", + ), + (RSAScheme::Pkcs1v15, RSAHash::Sha384) => rsa_pkcs1_cmd::<24, 48, 192, 960, 384, 388, 384>( + action, + pkcs1_v1_5_sign_sha384, + pkcs1_v1_5_verify_sha384, + skfile, + pkfile, + sigfile, + output_hex, + "RSA-3072/PKCS#1v1.5/SHA-384", + ), + (RSAScheme::Pkcs1v15, RSAHash::Sha512) => rsa_pkcs1_cmd::<24, 48, 192, 960, 384, 388, 384>( + action, + pkcs1_v1_5_sign_sha512, + pkcs1_v1_5_verify_sha512, + skfile, + pkfile, + sigfile, + output_hex, + "RSA-3072/PKCS#1v1.5/SHA-512", + ), + (RSAScheme::Pss, RSAHash::Sha256) => rsa_pss_cmd::<24, 48, 192, 960, 384, 388, 384>( + action, pss_sign_sha256, pss_verify_sha256, skfile, pkfile, sigfile, output_hex, + "RSA-3072/PSS/SHA-256", + ), + (RSAScheme::Pss, RSAHash::Sha384) => rsa_pss_cmd::<24, 48, 192, 960, 384, 388, 384>( + action, pss_sign_sha384, pss_verify_sha384, skfile, pkfile, sigfile, output_hex, + "RSA-3072/PSS/SHA-384", + ), + (RSAScheme::Pss, RSAHash::Sha512) => rsa_pss_cmd::<24, 48, 192, 960, 384, 388, 384>( + action, pss_sign_sha512, pss_verify_sha512, skfile, pkfile, sigfile, output_hex, + "RSA-3072/PSS/SHA-512", + ), + (RSAScheme::Pss, RSAHash::Shake128) => rsa_pss_cmd::<24, 48, 192, 960, 384, 388, 384>( + action, pss_shake128_sign, pss_shake128_verify, skfile, pkfile, sigfile, output_hex, + "RSA-3072/PSS-SHAKE128", + ), + (scheme, hash) => unsupported(scheme, hash, "RSA-3072"), + } +} + +/// RSA-4096: sign and verify. `HALF = 32`, `L = 64`, `HALF_BYTES = 256`, `SK_LEN = 1280`, `N_BYTES +/// = 512`, `PK_LEN = 516`, `SIG_LEN = 512`. `--hash shake256` (not shake128) is wired up at this +/// size -- see [`rsa_2048_cmd`] for the pairing rationale. +#[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 bouncycastle::rsa::rsa_4096::{ + pkcs1_v1_5_sign_sha256, pkcs1_v1_5_sign_sha384, pkcs1_v1_5_sign_sha512, + pkcs1_v1_5_verify_sha256, pkcs1_v1_5_verify_sha384, pkcs1_v1_5_verify_sha512, + pss_shake256_sign, pss_shake256_verify, pss_sign_sha256, pss_sign_sha384, pss_sign_sha512, + pss_verify_sha256, pss_verify_sha384, pss_verify_sha512, + }; + match (scheme, hash) { + (RSAScheme::Pkcs1v15, RSAHash::Sha256) => { + rsa_pkcs1_cmd::<32, 64, 256, 1280, 512, 516, 512>( + action, + pkcs1_v1_5_sign_sha256, + pkcs1_v1_5_verify_sha256, + skfile, + pkfile, + sigfile, + output_hex, + "RSA-4096/PKCS#1v1.5/SHA-256", + ) + } + (RSAScheme::Pkcs1v15, RSAHash::Sha384) => { + rsa_pkcs1_cmd::<32, 64, 256, 1280, 512, 516, 512>( + action, + pkcs1_v1_5_sign_sha384, + pkcs1_v1_5_verify_sha384, + skfile, + pkfile, + sigfile, + output_hex, + "RSA-4096/PKCS#1v1.5/SHA-384", + ) + } + (RSAScheme::Pkcs1v15, RSAHash::Sha512) => { + rsa_pkcs1_cmd::<32, 64, 256, 1280, 512, 516, 512>( + action, + pkcs1_v1_5_sign_sha512, + pkcs1_v1_5_verify_sha512, + skfile, + pkfile, + sigfile, + output_hex, + "RSA-4096/PKCS#1v1.5/SHA-512", + ) + } + (RSAScheme::Pss, RSAHash::Sha256) => rsa_pss_cmd::<32, 64, 256, 1280, 512, 516, 512>( + action, pss_sign_sha256, pss_verify_sha256, skfile, pkfile, sigfile, output_hex, + "RSA-4096/PSS/SHA-256", + ), + (RSAScheme::Pss, RSAHash::Sha384) => rsa_pss_cmd::<32, 64, 256, 1280, 512, 516, 512>( + action, pss_sign_sha384, pss_verify_sha384, skfile, pkfile, sigfile, output_hex, + "RSA-4096/PSS/SHA-384", + ), + (RSAScheme::Pss, RSAHash::Sha512) => rsa_pss_cmd::<32, 64, 256, 1280, 512, 516, 512>( + action, pss_sign_sha512, pss_verify_sha512, skfile, pkfile, sigfile, output_hex, + "RSA-4096/PSS/SHA-512", + ), + (RSAScheme::Pss, RSAHash::Shake256) => rsa_pss_cmd::<32, 64, 256, 1280, 512, 516, 512>( + action, pss_shake256_sign, pss_shake256_verify, skfile, pkfile, sigfile, output_hex, + "RSA-4096/PSS-SHAKE256", + ), + (scheme, hash) => unsupported(scheme, hash, "RSA-4096"), + } +} + +/// RSA-8192: sign and verify. `HALF = 64`, `L = 128`, `HALF_BYTES = 512`, `SK_LEN = 2560`, +/// `N_BYTES = 1024`, `PK_LEN = 1028`, `SIG_LEN = 1024`. No PSS-SHAKE variant is wired up at this +/// size: no Wycheproof vectors exist for it, and RFC 8702 §5 does not name a pairing beyond +/// "4096-bit or larger" for SHAKE256 -- 4096 already covers that recommendation. +#[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 bouncycastle::rsa::rsa_8192::{ + pkcs1_v1_5_sign_sha256, pkcs1_v1_5_sign_sha384, pkcs1_v1_5_sign_sha512, + pkcs1_v1_5_verify_sha256, pkcs1_v1_5_verify_sha384, pkcs1_v1_5_verify_sha512, + pss_sign_sha256, pss_sign_sha384, pss_sign_sha512, pss_verify_sha256, pss_verify_sha384, + pss_verify_sha512, + }; + match (scheme, hash) { + (RSAScheme::Pkcs1v15, RSAHash::Sha256) => { + rsa_pkcs1_cmd::<64, 128, 512, 2560, 1024, 1028, 1024>( + action, + pkcs1_v1_5_sign_sha256, + pkcs1_v1_5_verify_sha256, + skfile, + pkfile, + sigfile, + output_hex, + "RSA-8192/PKCS#1v1.5/SHA-256", + ) + } + (RSAScheme::Pkcs1v15, RSAHash::Sha384) => { + rsa_pkcs1_cmd::<64, 128, 512, 2560, 1024, 1028, 1024>( + action, + pkcs1_v1_5_sign_sha384, + pkcs1_v1_5_verify_sha384, + skfile, + pkfile, + sigfile, + output_hex, + "RSA-8192/PKCS#1v1.5/SHA-384", + ) + } + (RSAScheme::Pkcs1v15, RSAHash::Sha512) => { + rsa_pkcs1_cmd::<64, 128, 512, 2560, 1024, 1028, 1024>( + action, + pkcs1_v1_5_sign_sha512, + pkcs1_v1_5_verify_sha512, + skfile, + pkfile, + sigfile, + output_hex, + "RSA-8192/PKCS#1v1.5/SHA-512", + ) + } + (RSAScheme::Pss, RSAHash::Sha256) => rsa_pss_cmd::<64, 128, 512, 2560, 1024, 1028, 1024>( + action, pss_sign_sha256, pss_verify_sha256, skfile, pkfile, sigfile, output_hex, + "RSA-8192/PSS/SHA-256", + ), + (RSAScheme::Pss, RSAHash::Sha384) => rsa_pss_cmd::<64, 128, 512, 2560, 1024, 1028, 1024>( + action, pss_sign_sha384, pss_verify_sha384, skfile, pkfile, sigfile, output_hex, + "RSA-8192/PSS/SHA-384", + ), + (RSAScheme::Pss, RSAHash::Sha512) => rsa_pss_cmd::<64, 128, 512, 2560, 1024, 1028, 1024>( + action, pss_sign_sha512, pss_verify_sha512, skfile, pkfile, sigfile, output_hex, + "RSA-8192/PSS/SHA-512", + ), + (scheme, hash) => unsupported(scheme, hash, "RSA-8192"), + } +} diff --git a/crypto/rsa/Cargo.toml b/crypto/rsa/Cargo.toml index 4b10a4e4..ae675a3f 100644 --- a/crypto/rsa/Cargo.toml +++ b/crypto/rsa/Cargo.toml @@ -16,3 +16,27 @@ 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..e0af7879 --- /dev/null +++ b/crypto/rsa/benches/rsa_1024_benches.rs @@ -0,0 +1,70 @@ +//! 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 criterion::{Criterion, criterion_group, criterion_main}; +use std::hint::black_box; + +use bouncycastle_hex::decode as hex_decode; +use bouncycastle_rsa::rsa_1024::{ + Rsa1024PublicKey, pkcs1_v1_5_verify_sha256, pkcs1_v1_5_verify_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 = Rsa1024PublicKey::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 = Rsa1024PublicKey::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(|| { + pkcs1_v1_5_verify_sha256( + black_box(&pk_sha256), + black_box(&msg_sha256), + black_box(&sig_sha256), + ) + .unwrap() + }) + }); + group.bench_function("pkcs1v15_verify_sha384", |b| { + b.iter(|| { + pkcs1_v1_5_verify_sha384( + black_box(&pk_sha384), + black_box(&msg_sha384), + 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..314054ec --- /dev/null +++ b/crypto/rsa/benches/rsa_1536_benches.rs @@ -0,0 +1,87 @@ +//! 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 criterion::{Criterion, criterion_group, criterion_main}; +use std::hint::black_box; + +use bouncycastle_hex::decode as hex_decode; +use bouncycastle_rsa::rsa_1536::{ + Rsa1536PublicKey, pkcs1_v1_5_verify_sha256, pkcs1_v1_5_verify_sha384, pkcs1_v1_5_verify_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 = Rsa1536PublicKey::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 = Rsa1536PublicKey::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 = Rsa1536PublicKey::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(|| { + pkcs1_v1_5_verify_sha256(black_box(&pk_sha256), black_box(&msg), black_box(&sig_sha256)) + .unwrap() + }) + }); + group.bench_function("pkcs1v15_verify_sha384", |b| { + b.iter(|| { + pkcs1_v1_5_verify_sha384(black_box(&pk_sha384), black_box(&msg), black_box(&sig_sha384)) + .unwrap() + }) + }); + group.bench_function("pkcs1v15_verify_sha512", |b| { + b.iter(|| { + pkcs1_v1_5_verify_sha512(black_box(&pk_sha512), black_box(&msg), 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..169a097b --- /dev/null +++ b/crypto/rsa/benches/rsa_2048_benches.rs @@ -0,0 +1,155 @@ +//! 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 criterion::{Criterion, criterion_group, criterion_main}; +use std::hint::black_box; + +use bouncycastle_rng::DefaultRNG; +use bouncycastle_rsa::rsa_2048::{ + Rsa2048PrivateKey, Rsa2048PublicKey, pkcs1_v1_5_sign_sha256, pkcs1_v1_5_sign_sha384, + pkcs1_v1_5_sign_sha512, pkcs1_v1_5_verify_sha256, pkcs1_v1_5_verify_sha384, + pkcs1_v1_5_verify_sha512, pss_shake128_sign, pss_shake128_verify, pss_sign_sha256, + pss_sign_sha384, pss_sign_sha512, pss_verify_sha256, pss_verify_sha384, pss_verify_sha512, +}; + +const MSG: &[u8] = b"a representative message for benchmarking RSA-2048"; + +fn genuine_key() -> Rsa2048PrivateKey { + 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, + ]; + Rsa2048PrivateKey::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 = Rsa2048PublicKey::new(sk.n(), 0x10001).unwrap(); + let mut rng = DefaultRNG::default(); + + let sig_pkcs1_256 = pkcs1_v1_5_sign_sha256(&sk, MSG).unwrap(); + let sig_pkcs1_384 = pkcs1_v1_5_sign_sha384(&sk, MSG).unwrap(); + let sig_pkcs1_512 = pkcs1_v1_5_sign_sha512(&sk, MSG).unwrap(); + let sig_pss_256 = pss_sign_sha256(&sk, MSG, &mut rng).unwrap(); + let sig_pss_384 = pss_sign_sha384(&sk, MSG, &mut rng).unwrap(); + let sig_pss_512 = pss_sign_sha512(&sk, MSG, &mut rng).unwrap(); + let sig_pss_shake128 = pss_shake128_sign(&sk, MSG, &mut rng).unwrap(); + + let mut group = c.benchmark_group("rsa_2048"); + + group.bench_function("pkcs1v15_sign_sha256", |b| { + b.iter(|| black_box(pkcs1_v1_5_sign_sha256(black_box(&sk), black_box(MSG)).unwrap())) + }); + group.bench_function("pkcs1v15_verify_sha256", |b| { + b.iter(|| { + pkcs1_v1_5_verify_sha256(black_box(&pk), black_box(MSG), black_box(&sig_pkcs1_256)) + .unwrap() + }) + }); + group.bench_function("pkcs1v15_sign_sha384", |b| { + b.iter(|| black_box(pkcs1_v1_5_sign_sha384(black_box(&sk), black_box(MSG)).unwrap())) + }); + group.bench_function("pkcs1v15_verify_sha384", |b| { + b.iter(|| { + pkcs1_v1_5_verify_sha384(black_box(&pk), black_box(MSG), black_box(&sig_pkcs1_384)) + .unwrap() + }) + }); + group.bench_function("pkcs1v15_sign_sha512", |b| { + b.iter(|| black_box(pkcs1_v1_5_sign_sha512(black_box(&sk), black_box(MSG)).unwrap())) + }); + group.bench_function("pkcs1v15_verify_sha512", |b| { + b.iter(|| { + pkcs1_v1_5_verify_sha512(black_box(&pk), black_box(MSG), black_box(&sig_pkcs1_512)) + .unwrap() + }) + }); + group.bench_function("pss_sign_sha256", |b| { + b.iter(|| { + black_box( + pss_sign_sha256(black_box(&sk), black_box(MSG), &mut DefaultRNG::default()) + .unwrap(), + ) + }) + }); + group.bench_function("pss_verify_sha256", |b| { + b.iter(|| { + pss_verify_sha256(black_box(&pk), black_box(MSG), black_box(&sig_pss_256)).unwrap() + }) + }); + group.bench_function("pss_sign_sha384", |b| { + b.iter(|| { + black_box( + pss_sign_sha384(black_box(&sk), black_box(MSG), &mut DefaultRNG::default()) + .unwrap(), + ) + }) + }); + group.bench_function("pss_verify_sha384", |b| { + b.iter(|| { + pss_verify_sha384(black_box(&pk), black_box(MSG), black_box(&sig_pss_384)).unwrap() + }) + }); + group.bench_function("pss_sign_sha512", |b| { + b.iter(|| { + black_box( + pss_sign_sha512(black_box(&sk), black_box(MSG), &mut DefaultRNG::default()) + .unwrap(), + ) + }) + }); + group.bench_function("pss_verify_sha512", |b| { + b.iter(|| { + pss_verify_sha512(black_box(&pk), black_box(MSG), black_box(&sig_pss_512)).unwrap() + }) + }); + group.bench_function("pss_sign_shake128", |b| { + b.iter(|| { + black_box( + pss_shake128_sign(black_box(&sk), black_box(MSG), &mut DefaultRNG::default()) + .unwrap(), + ) + }) + }); + group.bench_function("pss_verify_shake128", |b| { + b.iter(|| { + pss_shake128_verify(black_box(&pk), black_box(MSG), black_box(&sig_pss_shake128)) + .unwrap() + }) + }); + + 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..c4a877dd --- /dev/null +++ b/crypto/rsa/benches/rsa_3072_benches.rs @@ -0,0 +1,163 @@ +//! 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 criterion::{Criterion, criterion_group, criterion_main}; +use std::hint::black_box; + +use bouncycastle_rng::DefaultRNG; +use bouncycastle_rsa::rsa_3072::{ + Rsa3072PrivateKey, Rsa3072PublicKey, pkcs1_v1_5_sign_sha256, pkcs1_v1_5_sign_sha384, + pkcs1_v1_5_sign_sha512, pkcs1_v1_5_verify_sha256, pkcs1_v1_5_verify_sha384, + pkcs1_v1_5_verify_sha512, pss_shake128_sign, pss_shake128_verify, pss_sign_sha256, + pss_sign_sha384, pss_sign_sha512, pss_verify_sha256, pss_verify_sha384, pss_verify_sha512, +}; + +const MSG: &[u8] = b"a representative message for benchmarking RSA-3072"; + +fn genuine_key() -> Rsa3072PrivateKey { + 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, + ]; + Rsa3072PrivateKey::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 = Rsa3072PublicKey::new(sk.n(), 0x10001).unwrap(); + let mut rng = DefaultRNG::default(); + + let sig_pkcs1_256 = pkcs1_v1_5_sign_sha256(&sk, MSG).unwrap(); + let sig_pkcs1_384 = pkcs1_v1_5_sign_sha384(&sk, MSG).unwrap(); + let sig_pkcs1_512 = pkcs1_v1_5_sign_sha512(&sk, MSG).unwrap(); + let sig_pss_256 = pss_sign_sha256(&sk, MSG, &mut rng).unwrap(); + let sig_pss_384 = pss_sign_sha384(&sk, MSG, &mut rng).unwrap(); + let sig_pss_512 = pss_sign_sha512(&sk, MSG, &mut rng).unwrap(); + let sig_pss_shake128 = pss_shake128_sign(&sk, MSG, &mut rng).unwrap(); + + let mut group = c.benchmark_group("rsa_3072"); + + group.bench_function("pkcs1v15_sign_sha256", |b| { + b.iter(|| black_box(pkcs1_v1_5_sign_sha256(black_box(&sk), black_box(MSG)).unwrap())) + }); + group.bench_function("pkcs1v15_verify_sha256", |b| { + b.iter(|| { + pkcs1_v1_5_verify_sha256(black_box(&pk), black_box(MSG), black_box(&sig_pkcs1_256)) + .unwrap() + }) + }); + group.bench_function("pkcs1v15_sign_sha384", |b| { + b.iter(|| black_box(pkcs1_v1_5_sign_sha384(black_box(&sk), black_box(MSG)).unwrap())) + }); + group.bench_function("pkcs1v15_verify_sha384", |b| { + b.iter(|| { + pkcs1_v1_5_verify_sha384(black_box(&pk), black_box(MSG), black_box(&sig_pkcs1_384)) + .unwrap() + }) + }); + group.bench_function("pkcs1v15_sign_sha512", |b| { + b.iter(|| black_box(pkcs1_v1_5_sign_sha512(black_box(&sk), black_box(MSG)).unwrap())) + }); + group.bench_function("pkcs1v15_verify_sha512", |b| { + b.iter(|| { + pkcs1_v1_5_verify_sha512(black_box(&pk), black_box(MSG), black_box(&sig_pkcs1_512)) + .unwrap() + }) + }); + group.bench_function("pss_sign_sha256", |b| { + b.iter(|| { + black_box( + pss_sign_sha256(black_box(&sk), black_box(MSG), &mut DefaultRNG::default()) + .unwrap(), + ) + }) + }); + group.bench_function("pss_verify_sha256", |b| { + b.iter(|| { + pss_verify_sha256(black_box(&pk), black_box(MSG), black_box(&sig_pss_256)).unwrap() + }) + }); + group.bench_function("pss_sign_sha384", |b| { + b.iter(|| { + black_box( + pss_sign_sha384(black_box(&sk), black_box(MSG), &mut DefaultRNG::default()) + .unwrap(), + ) + }) + }); + group.bench_function("pss_verify_sha384", |b| { + b.iter(|| { + pss_verify_sha384(black_box(&pk), black_box(MSG), black_box(&sig_pss_384)).unwrap() + }) + }); + group.bench_function("pss_sign_sha512", |b| { + b.iter(|| { + black_box( + pss_sign_sha512(black_box(&sk), black_box(MSG), &mut DefaultRNG::default()) + .unwrap(), + ) + }) + }); + group.bench_function("pss_verify_sha512", |b| { + b.iter(|| { + pss_verify_sha512(black_box(&pk), black_box(MSG), black_box(&sig_pss_512)).unwrap() + }) + }); + group.bench_function("pss_sign_shake128", |b| { + b.iter(|| { + black_box( + pss_shake128_sign(black_box(&sk), black_box(MSG), &mut DefaultRNG::default()) + .unwrap(), + ) + }) + }); + group.bench_function("pss_verify_shake128", |b| { + b.iter(|| { + pss_shake128_verify(black_box(&pk), black_box(MSG), black_box(&sig_pss_shake128)) + .unwrap() + }) + }); + + 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..3fe206de --- /dev/null +++ b/crypto/rsa/benches/rsa_4096_benches.rs @@ -0,0 +1,174 @@ +//! 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 criterion::{Criterion, criterion_group, criterion_main}; +use std::hint::black_box; + +use bouncycastle_rng::DefaultRNG; +use bouncycastle_rsa::rsa_4096::{ + Rsa4096PrivateKey, Rsa4096PublicKey, pkcs1_v1_5_sign_sha256, pkcs1_v1_5_sign_sha384, + pkcs1_v1_5_sign_sha512, pkcs1_v1_5_verify_sha256, pkcs1_v1_5_verify_sha384, + pkcs1_v1_5_verify_sha512, pss_shake256_sign, pss_shake256_verify, pss_sign_sha256, + pss_sign_sha384, pss_sign_sha512, pss_verify_sha256, pss_verify_sha384, pss_verify_sha512, +}; + +const MSG: &[u8] = b"a representative message for benchmarking RSA-4096"; + +fn genuine_key() -> Rsa4096PrivateKey { + 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, + ]; + Rsa4096PrivateKey::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 = Rsa4096PublicKey::new(sk.n(), 0x10001).unwrap(); + let mut rng = DefaultRNG::default(); + + let sig_pkcs1_256 = pkcs1_v1_5_sign_sha256(&sk, MSG).unwrap(); + let sig_pkcs1_384 = pkcs1_v1_5_sign_sha384(&sk, MSG).unwrap(); + let sig_pkcs1_512 = pkcs1_v1_5_sign_sha512(&sk, MSG).unwrap(); + let sig_pss_256 = pss_sign_sha256(&sk, MSG, &mut rng).unwrap(); + let sig_pss_384 = pss_sign_sha384(&sk, MSG, &mut rng).unwrap(); + let sig_pss_512 = pss_sign_sha512(&sk, MSG, &mut rng).unwrap(); + let sig_pss_shake256 = pss_shake256_sign(&sk, MSG, &mut rng).unwrap(); + + let mut group = c.benchmark_group("rsa_4096"); + + group.bench_function("pkcs1v15_sign_sha256", |b| { + b.iter(|| black_box(pkcs1_v1_5_sign_sha256(black_box(&sk), black_box(MSG)).unwrap())) + }); + group.bench_function("pkcs1v15_verify_sha256", |b| { + b.iter(|| { + pkcs1_v1_5_verify_sha256(black_box(&pk), black_box(MSG), black_box(&sig_pkcs1_256)) + .unwrap() + }) + }); + group.bench_function("pkcs1v15_sign_sha384", |b| { + b.iter(|| black_box(pkcs1_v1_5_sign_sha384(black_box(&sk), black_box(MSG)).unwrap())) + }); + group.bench_function("pkcs1v15_verify_sha384", |b| { + b.iter(|| { + pkcs1_v1_5_verify_sha384(black_box(&pk), black_box(MSG), black_box(&sig_pkcs1_384)) + .unwrap() + }) + }); + group.bench_function("pkcs1v15_sign_sha512", |b| { + b.iter(|| black_box(pkcs1_v1_5_sign_sha512(black_box(&sk), black_box(MSG)).unwrap())) + }); + group.bench_function("pkcs1v15_verify_sha512", |b| { + b.iter(|| { + pkcs1_v1_5_verify_sha512(black_box(&pk), black_box(MSG), black_box(&sig_pkcs1_512)) + .unwrap() + }) + }); + group.bench_function("pss_sign_sha256", |b| { + b.iter(|| { + black_box( + pss_sign_sha256(black_box(&sk), black_box(MSG), &mut DefaultRNG::default()) + .unwrap(), + ) + }) + }); + group.bench_function("pss_verify_sha256", |b| { + b.iter(|| { + pss_verify_sha256(black_box(&pk), black_box(MSG), black_box(&sig_pss_256)).unwrap() + }) + }); + group.bench_function("pss_sign_sha384", |b| { + b.iter(|| { + black_box( + pss_sign_sha384(black_box(&sk), black_box(MSG), &mut DefaultRNG::default()) + .unwrap(), + ) + }) + }); + group.bench_function("pss_verify_sha384", |b| { + b.iter(|| { + pss_verify_sha384(black_box(&pk), black_box(MSG), black_box(&sig_pss_384)).unwrap() + }) + }); + group.bench_function("pss_sign_sha512", |b| { + b.iter(|| { + black_box( + pss_sign_sha512(black_box(&sk), black_box(MSG), &mut DefaultRNG::default()) + .unwrap(), + ) + }) + }); + group.bench_function("pss_verify_sha512", |b| { + b.iter(|| { + pss_verify_sha512(black_box(&pk), black_box(MSG), black_box(&sig_pss_512)).unwrap() + }) + }); + group.bench_function("pss_sign_shake256", |b| { + b.iter(|| { + black_box( + pss_shake256_sign(black_box(&sk), black_box(MSG), &mut DefaultRNG::default()) + .unwrap(), + ) + }) + }); + group.bench_function("pss_verify_shake256", |b| { + b.iter(|| { + pss_shake256_verify(black_box(&pk), black_box(MSG), black_box(&sig_pss_shake256)) + .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..8abaa342 --- /dev/null +++ b/crypto/rsa/benches/rsa_8192_benches.rs @@ -0,0 +1,199 @@ +//! 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 criterion::{Criterion, criterion_group, criterion_main}; +use std::hint::black_box; + +use bouncycastle_rng::DefaultRNG; +use bouncycastle_rsa::rsa_8192::{ + Rsa8192PrivateKey, Rsa8192PublicKey, pkcs1_v1_5_sign_sha256, pkcs1_v1_5_sign_sha384, + pkcs1_v1_5_sign_sha512, pkcs1_v1_5_verify_sha256, pkcs1_v1_5_verify_sha384, + pkcs1_v1_5_verify_sha512, pss_sign_sha256, pss_sign_sha384, pss_sign_sha512, pss_verify_sha256, + pss_verify_sha384, pss_verify_sha512, +}; + +const MSG: &[u8] = b"a representative message for benchmarking RSA-8192"; + +fn genuine_key() -> Rsa8192PrivateKey { + 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, + ]; + Rsa8192PrivateKey::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 = Rsa8192PublicKey::new(sk.n(), 0x10001).unwrap(); + let mut rng = DefaultRNG::default(); + + let sig_pkcs1_256 = pkcs1_v1_5_sign_sha256(&sk, MSG).unwrap(); + let sig_pkcs1_384 = pkcs1_v1_5_sign_sha384(&sk, MSG).unwrap(); + let sig_pkcs1_512 = pkcs1_v1_5_sign_sha512(&sk, MSG).unwrap(); + let sig_pss_256 = pss_sign_sha256(&sk, MSG, &mut rng).unwrap(); + let sig_pss_384 = pss_sign_sha384(&sk, MSG, &mut rng).unwrap(); + let sig_pss_512 = pss_sign_sha512(&sk, MSG, &mut rng).unwrap(); + + let mut group = c.benchmark_group("rsa_8192"); + + group.bench_function("pkcs1v15_sign_sha256", |b| { + b.iter(|| black_box(pkcs1_v1_5_sign_sha256(black_box(&sk), black_box(MSG)).unwrap())) + }); + group.bench_function("pkcs1v15_verify_sha256", |b| { + b.iter(|| { + pkcs1_v1_5_verify_sha256(black_box(&pk), black_box(MSG), black_box(&sig_pkcs1_256)) + .unwrap() + }) + }); + group.bench_function("pkcs1v15_sign_sha384", |b| { + b.iter(|| black_box(pkcs1_v1_5_sign_sha384(black_box(&sk), black_box(MSG)).unwrap())) + }); + group.bench_function("pkcs1v15_verify_sha384", |b| { + b.iter(|| { + pkcs1_v1_5_verify_sha384(black_box(&pk), black_box(MSG), black_box(&sig_pkcs1_384)) + .unwrap() + }) + }); + group.bench_function("pkcs1v15_sign_sha512", |b| { + b.iter(|| black_box(pkcs1_v1_5_sign_sha512(black_box(&sk), black_box(MSG)).unwrap())) + }); + group.bench_function("pkcs1v15_verify_sha512", |b| { + b.iter(|| { + pkcs1_v1_5_verify_sha512(black_box(&pk), black_box(MSG), black_box(&sig_pkcs1_512)) + .unwrap() + }) + }); + group.bench_function("pss_sign_sha256", |b| { + b.iter(|| { + black_box( + pss_sign_sha256(black_box(&sk), black_box(MSG), &mut DefaultRNG::default()) + .unwrap(), + ) + }) + }); + group.bench_function("pss_verify_sha256", |b| { + b.iter(|| { + pss_verify_sha256(black_box(&pk), black_box(MSG), black_box(&sig_pss_256)).unwrap() + }) + }); + group.bench_function("pss_sign_sha384", |b| { + b.iter(|| { + black_box( + pss_sign_sha384(black_box(&sk), black_box(MSG), &mut DefaultRNG::default()) + .unwrap(), + ) + }) + }); + group.bench_function("pss_verify_sha384", |b| { + b.iter(|| { + pss_verify_sha384(black_box(&pk), black_box(MSG), black_box(&sig_pss_384)).unwrap() + }) + }); + group.bench_function("pss_sign_sha512", |b| { + b.iter(|| { + black_box( + pss_sign_sha512(black_box(&sk), black_box(MSG), &mut DefaultRNG::default()) + .unwrap(), + ) + }) + }); + group.bench_function("pss_verify_sha512", |b| { + b.iter(|| { + pss_verify_sha512(black_box(&pk), black_box(MSG), black_box(&sig_pss_512)).unwrap() + }) + }); + + group.finish(); +} + +criterion_group!(benches, bench_rsa_8192); +criterion_main!(benches); diff --git a/crypto/rsa/src/keys.rs b/crypto/rsa/src/keys.rs index d630bf24..08da584d 100644 --- a/crypto/rsa/src/keys.rs +++ b/crypto/rsa/src/keys.rs @@ -8,6 +8,7 @@ //! `(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. +use crate::codec::{be_bytes_from_limbs, limbs_from_be_bytes}; use bouncycastle_core::errors::SignatureError; use bouncycastle_ec::montgomery; use bouncycastle_ec::nat; @@ -48,6 +49,35 @@ impl RsaPublicKey { pub fn e(&self) -> u32 { self.e } + + /// Encodes as `n || e`: `n` as `N_BYTES = 8 * L` big-endian bytes (RFC 8017 §4.1's I2OSP), + /// then `e` as 4 big-endian bytes. Not an RFC 8017 or ASN.1 format -- this crate has no DER + /// encoder/decoder -- just a fixed-width raw layout [`Self::from_bytes`] round-trips, for + /// `cli/src/rsa_cmd.rs` to read and write public keys as files. + pub fn encode(&self) -> [u8; PK_LEN] { + debug_assert_eq!(N_BYTES, 8 * L, "RsaPublicKey::encode needs N_BYTES == 8 * L"); + debug_assert_eq!(PK_LEN, N_BYTES + 4, "RsaPublicKey::encode needs PK_LEN == N_BYTES + 4"); + let mut out = [0u8; PK_LEN]; + out[..N_BYTES].copy_from_slice(&be_bytes_from_limbs::(&self.n)); + out[N_BYTES..].copy_from_slice(&self.e.to_be_bytes()); + out + } + + /// Decodes [`Self::encode`]'s layout, validated the same way [`Self::new`] validates `(n, e)`. + pub fn from_bytes( + bytes: &[u8; PK_LEN], + ) -> Result { + debug_assert_eq!(N_BYTES, 8 * L, "RsaPublicKey::from_bytes needs N_BYTES == 8 * L"); + debug_assert_eq!( + PK_LEN, + N_BYTES + 4, + "RsaPublicKey::from_bytes needs PK_LEN == N_BYTES + 4" + ); + let n_bytes: [u8; N_BYTES] = bytes[..N_BYTES].try_into().expect("N_BYTES-byte slice"); + let n = limbs_from_be_bytes::(&n_bytes); + let e_bytes: [u8; 4] = bytes[N_BYTES..].try_into().expect("4-byte slice"); + Self::new(&n, u32::from_be_bytes(e_bytes)) + } } /// An RSA private key in RFC 8017 §3.2's CRT ("second representation") form: `p`, `q`, `dP`, @@ -161,4 +191,65 @@ impl RsaPrivateKey { pub(crate) fn q_inv(&self) -> &[u64; HALF] { &self.q_inv } + + /// Encodes as `p || q || dP || dQ || qInv`, each `HALF_BYTES = 8 * HALF` big-endian bytes. Not + /// an RFC 8017 or ASN.1 format -- see [`RsaPublicKey::encode`]'s docs for why -- just a + /// fixed-width raw layout [`Self::from_bytes`] round-trips, for `cli/src/rsa_cmd.rs` to read + /// and write private keys as files. + pub fn encode(&self) -> [u8; SK_LEN] { + debug_assert_eq!( + HALF_BYTES, + 8 * HALF, + "RsaPrivateKey::encode needs HALF_BYTES == 8 * HALF" + ); + debug_assert_eq!( + SK_LEN, + 5 * HALF_BYTES, + "RsaPrivateKey::encode needs SK_LEN == 5 * HALF_BYTES" + ); + let mut out = [0u8; SK_LEN]; + out[..HALF_BYTES].copy_from_slice(&be_bytes_from_limbs::(&self.p)); + out[HALF_BYTES..2 * HALF_BYTES] + .copy_from_slice(&be_bytes_from_limbs::(&self.q)); + out[2 * HALF_BYTES..3 * HALF_BYTES] + .copy_from_slice(&be_bytes_from_limbs::(&self.d_p)); + out[3 * HALF_BYTES..4 * HALF_BYTES] + .copy_from_slice(&be_bytes_from_limbs::(&self.d_q)); + out[4 * HALF_BYTES..] + .copy_from_slice(&be_bytes_from_limbs::(&self.q_inv)); + out + } + + /// Decodes [`Self::encode`]'s layout, validated the same way + /// [`Self::from_crt_components`] validates its five components. + pub fn from_bytes( + bytes: &[u8; SK_LEN], + ) -> Result { + debug_assert_eq!( + HALF_BYTES, + 8 * HALF, + "RsaPrivateKey::from_bytes needs HALF_BYTES == 8 * HALF" + ); + debug_assert_eq!( + SK_LEN, + 5 * HALF_BYTES, + "RsaPrivateKey::from_bytes needs SK_LEN == 5 * HALF_BYTES" + ); + let p_bytes: [u8; HALF_BYTES] = bytes[..HALF_BYTES].try_into().expect("HALF_BYTES bytes"); + let q_bytes: [u8; HALF_BYTES] = + bytes[HALF_BYTES..2 * HALF_BYTES].try_into().expect("HALF_BYTES bytes"); + let d_p_bytes: [u8; HALF_BYTES] = + bytes[2 * HALF_BYTES..3 * HALF_BYTES].try_into().expect("HALF_BYTES bytes"); + let d_q_bytes: [u8; HALF_BYTES] = + bytes[3 * HALF_BYTES..4 * HALF_BYTES].try_into().expect("HALF_BYTES bytes"); + let q_inv_bytes: [u8; HALF_BYTES] = + bytes[4 * HALF_BYTES..].try_into().expect("HALF_BYTES bytes"); + + let p = limbs_from_be_bytes::(&p_bytes); + let q = limbs_from_be_bytes::(&q_bytes); + let d_p = limbs_from_be_bytes::(&d_p_bytes); + let d_q = limbs_from_be_bytes::(&d_q_bytes); + let q_inv = limbs_from_be_bytes::(&q_inv_bytes); + Self::from_crt_components(&p, &q, &d_p, &d_q, &q_inv) + } } diff --git a/crypto/rsa/tests/keys_tests.rs b/crypto/rsa/tests/keys_tests.rs index af53a842..a9a71ea0 100644 --- a/crypto/rsa/tests/keys_tests.rs +++ b/crypto/rsa/tests/keys_tests.rs @@ -127,3 +127,43 @@ fn public_key_rejects_even_modulus() { even_n[0] &= !1; assert!(matches!(RsaPublicKey::<32>::new(&even_n, 3), Err(SignatureError::DecodingError(_)))); } + +#[test] +fn public_key_encode_round_trips() { + let pk = RsaPublicKey::<32>::new(&N, 0x10001).unwrap(); + let bytes: [u8; 260] = pk.encode::<256, 260>(); + let decoded = RsaPublicKey::<32>::from_bytes::<256, 260>(&bytes).expect("must decode"); + assert_eq!(decoded, pk); +} + +#[test] +fn public_key_from_bytes_rejects_even_modulus() { + let pk = RsaPublicKey::<32>::new(&N, 0x10001).unwrap(); + let mut bytes: [u8; 260] = pk.encode::<256, 260>(); + bytes[255] &= !1; // clear n's low bit (last byte, big-endian) + assert!(matches!( + RsaPublicKey::<32>::from_bytes::<256, 260>(&bytes), + Err(SignatureError::DecodingError(_)) + )); +} + +#[test] +fn private_key_encode_round_trips() { + let sk = RsaPrivateKey::<32, 16>::from_crt_components(&P, &Q, &D_P, &D_Q, &Q_INV).unwrap(); + let bytes: [u8; 640] = sk.encode::<128, 640>(); + let decoded = RsaPrivateKey::<32, 16>::from_bytes::<128, 640>(&bytes).expect("must decode"); + assert_eq!(decoded, sk); +} + +#[test] +fn private_key_from_bytes_rejects_equal_primes() { + let sk = RsaPrivateKey::<32, 16>::from_crt_components(&P, &Q, &D_P, &D_Q, &Q_INV).unwrap(); + let mut bytes: [u8; 640] = sk.encode::<128, 640>(); + // 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::<32, 16>::from_bytes::<128, 640>(&bytes), + Err(SignatureError::DecodingError(_)) + )); +} diff --git a/mem_usage_benches/Cargo.toml b/mem_usage_benches/Cargo.toml index b6b045f0..d4be9b03 100644 --- a/mem_usage_benches/Cargo.toml +++ b/mem_usage_benches/Cargo.toml @@ -39,6 +39,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" 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..355416ec --- /dev/null +++ b/mem_usage_benches/src/bench_rsa_mem_usage.rs @@ -0,0 +1,281 @@ +//! 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::rsa::{rsa_1024, rsa_1536, rsa_2048, rsa_3072, rsa_4096, rsa_8192}; + +const MSG: &[u8] = b"peak stack usage of RSA sign/verify, held constant across every modulus size"; + +/// This prints the on-disk encoded length of each modulus size's private/public keys and +/// signatures (`bouncycastle_rsa` has no in-memory key struct exposed here to `size_of` across +/// modules the way ECDSA's mem usage bench does, since each RSA key type is a distinct +/// `RsaPrivateKey`/`RsaPublicKey` monomorphization -- the byte lengths below are what +/// actually varies with modulus size). +fn print_key_sizes() { + println!("\nRSA-1024 (verification only)"); + println!("public key on disk (n || e): {} bytes", 8 * 16 + 4); + println!("signature: {} bytes", 8 * 16); + + println!("\nRSA-1536 (verification only)"); + println!("public key on disk (n || e): {} bytes", 8 * 24 + 4); + println!("signature: {} bytes", 8 * 24); + + println!("\nRSA-2048"); + println!("private key on disk (p||q||dP||dQ||qInv): {} bytes", 5 * 8 * 16); + println!("public key on disk (n || e): {} bytes", 8 * 32 + 4); + println!("signature: {} bytes", 8 * 32); + + println!("\nRSA-3072"); + println!("private key on disk (p||q||dP||dQ||qInv): {} bytes", 5 * 8 * 24); + println!("public key on disk (n || e): {} bytes", 8 * 48 + 4); + println!("signature: {} bytes", 8 * 48); + + println!("\nRSA-4096"); + println!("private key on disk (p||q||dP||dQ||qInv): {} bytes", 5 * 8 * 32); + println!("public key on disk (n || e): {} bytes", 8 * 64 + 4); + println!("signature: {} bytes", 8 * 64); + + println!("\nRSA-8192"); + println!("private key on disk (p||q||dP||dQ||qInv): {} bytes", 5 * 8 * 64); + println!("public key on disk (n || e): {} bytes", 8 * 128 + 4); + println!("signature: {} bytes", 8 * 128); +} + +/// 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 = rsa_1024::Rsa1024PublicKey::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 rsa_1024::pkcs1_v1_5_verify_sha256(&pk, &msg, &sig).is_ok() { + eprintln!("Verification succeeded!"); + } else { + panic!("Verification failed! -- figure that out"); + } +} + +fn genuine_2048_key() -> rsa_2048::Rsa2048PrivateKey { + 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, + ]; + rsa_2048::Rsa2048PrivateKey::from_crt_components(&p, &q, &d_p, &d_q, &q_inv).unwrap() +} + +fn bench_2048_sign() { + eprintln!("RSA-2048/Sign"); + let sk = genuine_2048_key(); + let sig = rsa_2048::pkcs1_v1_5_sign_sha256(&sk, MSG).unwrap(); + println!("{:x?}", sig); +} + +fn bench_2048_verify() { + eprintln!("RSA-2048/Verify"); + let sk = genuine_2048_key(); + let pk = rsa_2048::Rsa2048PublicKey::new(sk.n(), 0x10001).unwrap(); + let sig = rsa_2048::pkcs1_v1_5_sign_sha256(&sk, MSG).unwrap(); + + if rsa_2048::pkcs1_v1_5_verify_sha256(&pk, MSG, &sig).is_ok() { + eprintln!("Verification succeeded!"); + } else { + panic!("Verification failed! -- figure that out"); + } +} + +fn genuine_8192_key() -> rsa_8192::Rsa8192PrivateKey { + 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, + ]; + rsa_8192::Rsa8192PrivateKey::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 = rsa_8192::pkcs1_v1_5_sign_sha256(&sk, MSG).unwrap(); + println!("{:x?}", sig); +} + +fn bench_8192_verify() { + eprintln!("RSA-8192/Verify"); + let sk = genuine_8192_key(); + let pk = rsa_8192::Rsa8192PublicKey::new(sk.n(), 0x10001).unwrap(); + let sig = rsa_8192::pkcs1_v1_5_sign_sha256(&sk, MSG).unwrap(); + + if rsa_8192::pkcs1_v1_5_verify_sha256(&pk, MSG, &sig).is_ok() { + eprintln!("Verification succeeded!"); + } else { + panic!("Verification failed! -- figure that out"); + } +} + +fn main() { + print_key_sizes() + // bench_do_nothing() + // bench_1024_verify() + // bench_2048_sign() + // bench_2048_verify() + // bench_8192_sign() + // bench_8192_verify() +} diff --git a/mem_usage_benches/src/lib.rs b/mem_usage_benches/src/lib.rs index c7017c9d..7ad06764 100644 --- a/mem_usage_benches/src/lib.rs +++ b/mem_usage_benches/src/lib.rs @@ -7,6 +7,7 @@ mod bench_ecdsa_mem_usage; mod bench_mldsa_mem_usage; mod bench_mlkem_mem_usage; mod bench_poly1305_mem_usage; +mod bench_rsa_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 5864f64b..b2fcc0fd 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -16,6 +16,7 @@ pub use bouncycastle_mlkem as mlkem; pub use bouncycastle_mlkem_lowmemory as mlkem_lowmemory; pub use bouncycastle_poly1305 as poly1305; pub use bouncycastle_rng as rng; +pub use bouncycastle_rsa as rsa; pub use bouncycastle_sha2 as sha2; pub use bouncycastle_sha3 as sha3; pub use bouncycastle_sm2 as sm2; From b2c505ed4bf8cbffa454f651d6346376914706e7 Mon Sep 17 00:00:00 2001 From: David Hook Date: Sat, 19 Sep 2026 23:14:30 +1000 Subject: [PATCH 10/55] rsa: crate docs -- Usage Examples, Memory Usage, Security Considerations Adds the three doc sections QUALITY_AND_STYLE.md requires, which this crate had none of beyond a single Usage Examples snippet. Usage Examples gains the crate's other two major usage patterns beyond the existing RSA-2048/PKCS#1v1.5/PSS one: verify-only usage (RSA-1024, against one of Wycheproof's own genuine rsa_pkcs1_1024_sig_gen_test.json signatures -- no private key or signer type exists at this size at all), and a pointer to RSASSA-PSS-SHAKE128/256 rather than a third near-identical doctest, since its sign/verify shape is byte-for-byte the same as plain PSS's, just a different function name per hash pairing. Memory Usage is a table of on-disk and in-memory key/signature sizes for every modulus size, sourced from mem_usage_benches' bench_rsa_mem_usage binary -- which needed extending first: print_key_sizes() only printed on-disk lengths (computed from L/HALF), so it now also prints core::mem::size_of for each concrete RsaPrivateKey/ RsaPublicKey, matching bench_ecdsa_mem_usage.rs's own print_struct_sizes() convention of reporting both. Security Considerations covers five footguns: RSASP1 signing is constant-time in the CRT exponents but not blinded against the message (a chosen-message physical side-channel attacker may still learn about p/q/dP/dQ, per Kocher 1996 and Boneh & Brumley 2003); this crate validates p/q are odd and distinct but never checks primality, so a malformed key computes silently rather than being rejected; PSS's salt comes from the caller's RNG, and while a repeated/predictable salt does not leak the key the way ECDSA nonce reuse does, it weakens PSS's random-oracle argument; RSA-1024/1536 sit below NIST SP 800-131A's 112-bit threshold and are verification-only by design, not by oversight; and PSS's salt length is fixed to the hash's own output length rather than caller-configurable, so interop requires a peer using the same convention. Writing that first bullet surfaced a real problem rather than just something to word carefully: modexp.rs's own module docs claimed "RSA's private-key signing operation (a later addition to this crate) applies message blinding on top of this primitive" -- but rsa_core.rs's rsasp1 (the only caller that exponentiates with a secret exponent) has no blinding logic anywhere, confirmed by reading it end to end. That claim was false, not merely imprecise -- apparently a forward reference to blinding that was never actually added. Fixed the doc comment to state what the code actually does (no blinding, full stop) instead of what it was once expected to do. This is a documentation correction only: rsasp1's behavior is completely unchanged, only the comment describing it was wrong, and the crate's new Security Considerations section now states the real, unblinded behavior explicitly rather than repeating the stale claim. cargo test -p bouncycastle-rsa passes in full, including both doctests. Mutation testing remains deferred to a single consolidated pass, which follows this commit. Co-Authored-By: Claude Sonnet 5 --- crypto/rsa/src/lib.rs | 76 ++++++++++++++++++++ crypto/rsa/src/modexp.rs | 6 +- mem_usage_benches/src/bench_rsa_mem_usage.rs | 52 ++++++++------ 3 files changed, 110 insertions(+), 24 deletions(-) diff --git a/crypto/rsa/src/lib.rs b/crypto/rsa/src/lib.rs index 39adcf48..2ed78989 100644 --- a/crypto/rsa/src/lib.rs +++ b/crypto/rsa/src/lib.rs @@ -49,6 +49,27 @@ //! # Ok::<(), bouncycastle_core::errors::SignatureError>(()) //! ``` //! +//! RSA-1024 verification, the other major usage pattern: no private key or signer exists for this +//! size at all (see `# Scope` above), only verification against a signature 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_rsa::rsa_1024::{Rsa1024PublicKey, pkcs1_v1_5_verify_sha256}; +//! # const N: [u64; 16] = [0xd00343468eaacfbf, 0xb7c7044cc202dcca, 0x9686f30f478db649, 0x5179b54951fff6aa, 0xbabb14f550d5d0dd, 0x5405db7c5c8f4cf6, 0x9816e2eda41fd7b9, 0xb31b6abd805bace9, 0xb909dd0f4c6014f2, 0x9c8a5810b6d05990, 0x40760d1f23fe9250, 0x90adb011a919575a, 0x45e48572113cab28, 0xcb9ca9ec12000fc8, 0x91b4fcaf62a14595, 0xac9048a7a4f560af]; +//! let sig: [u8; 128] = bouncycastle_hex::decode("41339884a9b3940e8488d666bb158063c6a2a2717cae7f564834a876fcbf7098ecf3acbfabf37d38a8e6127b1e313744f1f896e165efdaea0b2e7673867842b9e94db0868ed9a92bcdcb370a4e20ff275c82595e4400a8b9e9f12482f014846b48216f321266ae6ae6338dbcdc41b711e483e6e3e728772e7f9f5ef95c30196b").unwrap().try_into().unwrap(); +//! let msg = [0u8; 20]; // Wycheproof's own genuine message for this signature. +//! let pk = Rsa1024PublicKey::new(&N, 0x10001)?; +//! pkcs1_v1_5_verify_sha256(&pk, &msg, &sig)?; +//! # Ok::<(), bouncycastle_core::errors::SignatureError>(()) +//! ``` +//! +//! RSASSA-PSS-SHAKE128/256 (RFC 8702 §3.2.1, [`rsa_2048::pss_shake128_sign`]/`_verify` and +//! siblings at RSA-3072/4096) follow the exact same `sign`/`sign_with_salt`/`verify` shape as +//! `pss_sign_sha256`/`pss_verify_sha256` above, just with a different function name per §5's +//! recommended pairing (SHAKE128 at 2048/3072, SHAKE256 at 4096) -- 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`] @@ -66,6 +87,61 @@ //! `mgf1`), 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. +//! +//! # 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 | +//! +//! All values are in bytes. "On disk" is [`keys::RsaPublicKey::encode`]/[`keys::RsaPrivateKey::encode`]'s +//! raw layout (`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_LEN = 8 * L` +//! bytes: 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 `L`, not by which hash or +//! scheme fed into RSASP1/RSAVP1's modular exponentiation. +//! +//! # 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. +//! - **This crate does not generate or validate primality of `p`/`q`.** [`keys::RsaPrivateKey::from_crt_components`] +//! checks that `p`/`q` are odd and distinct and that `dP`/`dQ`/`qInv` are in range, but it has no +//! way to check that `p` and `q` are actually prime (that would need a primality test this crate +//! does not implement) or that `e` is coprime to `λ(n)`. Supplying non-prime or otherwise +//! malformed CRT components produces a key that computes *something*, silently, rather than +//! being rejected -- validating the inputs' number-theoretic properties before construction is +//! entirely the caller's responsibility. +//! - **RSASSA-PSS's salt comes from the caller's RNG.** 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 +//! weakens that argument even though it will not directly leak `d`. +//! - **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. +//! - **RSASSA-PSS's salt length is fixed to the hash's own output length** (RFC 8017 §9.1 note +//! 4's "typical" choice) rather than being caller-configurable. A verifier that expects a +//! different salt length (including the zero-length salt some other implementations default +//! to) will not interoperate with signatures this crate produces, and this crate's own verifier +//! will reject signatures made with a different salt length. #![no_std] #![forbid(unsafe_code)] diff --git a/crypto/rsa/src/modexp.rs b/crypto/rsa/src/modexp.rs index a10f6b7f..a035624d 100644 --- a/crypto/rsa/src/modexp.rs +++ b/crypto/rsa/src/modexp.rs @@ -27,9 +27,9 @@ //! 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). RSA's private-key signing operation (a later addition to this crate) applies -//! message blinding on top of this primitive; this module does not do that itself; it is a -//! general-purpose engine, not the full defence. +//! (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; diff --git a/mem_usage_benches/src/bench_rsa_mem_usage.rs b/mem_usage_benches/src/bench_rsa_mem_usage.rs index 355416ec..e49bb9f0 100644 --- a/mem_usage_benches/src/bench_rsa_mem_usage.rs +++ b/mem_usage_benches/src/bench_rsa_mem_usage.rs @@ -34,39 +34,49 @@ use bouncycastle::rsa::{rsa_1024, rsa_1536, rsa_2048, rsa_3072, rsa_4096, rsa_81 const MSG: &[u8] = b"peak stack usage of RSA sign/verify, held constant across every modulus size"; -/// This prints the on-disk encoded length of each modulus size's private/public keys and -/// signatures (`bouncycastle_rsa` has no in-memory key struct exposed here to `size_of` across -/// modules the way ECDSA's mem usage bench does, since each RSA key type is a distinct -/// `RsaPrivateKey`/`RsaPublicKey` monomorphization -- the byte lengths below are what -/// actually varies with 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", 8 * 16 + 4); - println!("signature: {} bytes", 8 * 16); + 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", 8 * 24 + 4); - println!("signature: {} bytes", 8 * 24); + 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", 5 * 8 * 16); - println!("public key on disk (n || e): {} bytes", 8 * 32 + 4); - println!("signature: {} bytes", 8 * 32); + 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!("signature: {} bytes", 256); println!("\nRSA-3072"); - println!("private key on disk (p||q||dP||dQ||qInv): {} bytes", 5 * 8 * 24); - println!("public key on disk (n || e): {} bytes", 8 * 48 + 4); - println!("signature: {} bytes", 8 * 48); + 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!("signature: {} bytes", 384); println!("\nRSA-4096"); - println!("private key on disk (p||q||dP||dQ||qInv): {} bytes", 5 * 8 * 32); - println!("public key on disk (n || e): {} bytes", 8 * 64 + 4); - println!("signature: {} bytes", 8 * 64); + 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!("signature: {} bytes", 512); println!("\nRSA-8192"); - println!("private key on disk (p||q||dP||dQ||qInv): {} bytes", 5 * 8 * 64); - println!("public key on disk (n || e): {} bytes", 8 * 128 + 4); - println!("signature: {} bytes", 8 * 128); + 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!("signature: {} bytes", 1024); } /// This exists that /usr/bin/time can be used to measure the base memory footprint of the cargo bench harness From d61b97ce93e525a7d64d0f7e7c470e9ff490f925 Mon Sep 17 00:00:00 2001 From: David Hook Date: Sun, 20 Sep 2026 07:57:44 +1000 Subject: [PATCH 11/55] rsa: fix test-coverage gaps found by the consolidated mutants run The mutants run in progress against the whole crate (648 mutants) found that this crate's per-hash test coverage was inconsistent rather than uniform: SHA-256 is thoroughly tested everywhere via real Wycheproof vectors, but SHA-384/512's rejection paths, and most non-2048 sizes' non-primary sign functions, were often only self-consistency-tested (a sign-then-verify-the-same-message round trip, which can never catch a mutation that breaks rejection) or not exercised by any test at all. ASN.1 leading-byte/block-type check (emsa_pkcs1_v1_5.rs): `em[0] != 0x00 || em[1] != 0x01` had no test flipping just one of the two bytes independently -- a mutant weakening the `||` to `&&` (accept if either byte alone is correct) still passed the whole suite, since no existing vector happens to produce "one byte right, one wrong" from a chosen signature representative. Added `verify_rejects_wrong_block_type` and `verify_rejects_wrong_leading_byte`. PKCS#1 v1.5 verify-rejection coverage: `pkcs1_v1_5_verify_sha384` (RSA 1024/1536/3072) and `_sha512` (1536/3072) had accepts-genuine-signature tests but no rejects-wrong-message test of their own -- only SHA-256's did. A whole-function-body mutant replacing any of these with `Ok(())` passed. Fixed 1024/1536 by generalizing the existing SHA-256-only rejection test over `sha`/`verify` and adding the missing hashes. Fixed 3072 by wiring its already-generic `run_pkcs1_v1_5_verify_vectors` helper to the real `rsa_signature_3072_sha384/512_test.json` files that already existed but were never used (the file's own module docs already claimed this coverage) -- the helper needed its hardcoded expected valid/invalid counts (8/250, SHA-256's own) turned into parameters, since SHA-384 is 7/251 and SHA-512 is 8/251 (a second, one-test `SmallSignature` group in that file's own key). PSS verify-rejection and uncalled `pss_sign_*` wrappers (3072/4096/8192): every self-consistency PSS test picked one salt source (RNG or `_with_salt`) per hash and never asserted rejection, so up to six `pss_sign_sha{256,384,512}[_with_salt]` functions per size, and `pss_verify_sha384`/`_sha512`'s rejection paths, were never reached by any test. Replaced each combined round-trip test with `rsa_2048_pss_sha384_sha512_tests.rs`'s own established shape: one `_fixed_salt_round_trips` test per hash (exercises `_with_salt`, and asserts a wrong message is rejected) plus one `_rng_produces_fresh_salts_that_both_verify` test per hash (exercises the RNG variant, and confirms two signatures of the same message differ). This calls every sign function at this crate offers at least once and gives every verify function real rejection coverage. Also documented two mutants that turned out to be genuine equivalences (not gaps) rather than fixed: `inner_end > t.len()` in `decode_digest_info` mutating to `>=` is caught one check later by `t.get(pos) != Some(&0x04)` regardless; `(acc[i] << 1) | carry` in `ct_shift_in_bit_mod` mutating to `^` is identical because the shifted value's low bit is always clear before the OR. Every touched test file was run individually after these changes and passes in full (rsa_1024_tests, rsa_1536_tests: instant; rsa_3072_tests: 12/12 in 211s; rsa_4096_tests: 14/14 in 569s; rsa_8192_tests: 12/12 in 175s), and the new `emsa_pkcs1_v1_5` unit tests pass under `cargo test --lib`. The consolidated mutants run itself is still in progress against the pre-fix source and will need a follow-up pass once it completes to confirm these new tests actually kill the mutants that found them. Co-Authored-By: Claude Sonnet 5 --- crypto/rsa/src/emsa_pkcs1_v1_5.rs | 23 ++++++ crypto/rsa/src/modexp.rs | 3 + crypto/rsa/tests/rsa_1024_tests.rs | 29 +++++-- crypto/rsa/tests/rsa_1536_tests.rs | 37 +++++++-- crypto/rsa/tests/rsa_3072_tests.rs | 120 +++++++++++++++++++++++++---- crypto/rsa/tests/rsa_4096_tests.rs | 101 +++++++++++++++++++++++- crypto/rsa/tests/rsa_8192_tests.rs | 80 +++++++++++++++---- 7 files changed, 350 insertions(+), 43 deletions(-) diff --git a/crypto/rsa/src/emsa_pkcs1_v1_5.rs b/crypto/rsa/src/emsa_pkcs1_v1_5.rs index 004b2238..a6f12339 100644 --- a/crypto/rsa/src/emsa_pkcs1_v1_5.rs +++ b/crypto/rsa/src/emsa_pkcs1_v1_5.rs @@ -116,6 +116,11 @@ fn decode_digest_info` 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; } @@ -404,4 +409,22 @@ mod tests { assert_eq!(em[2..2 + 8], [0xff; 8], "this construction must exercise ps_len == 8 exactly"); assert!(emsa_pkcs1_v1_5_verify::(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 = emsa_pkcs1_v1_5_encode::(b"hello"); + em[1] = 0x02; + assert!(!emsa_pkcs1_v1_5_verify::(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 = emsa_pkcs1_v1_5_encode::(b"hello"); + em[0] = 0x01; + assert!(!emsa_pkcs1_v1_5_verify::(b"hello", &em)); + } } diff --git a/crypto/rsa/src/modexp.rs b/crypto/rsa/src/modexp.rs index a035624d..1ad12f92 100644 --- a/crypto/rsa/src/modexp.rs +++ b/crypto/rsa/src/modexp.rs @@ -179,6 +179,9 @@ fn ct_shift_in_bit_mod(acc: &[u64; N], bit: u64, modulus: &[u64; 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; } diff --git a/crypto/rsa/tests/rsa_1024_tests.rs b/crypto/rsa/tests/rsa_1024_tests.rs index 762db074..518dacd5 100644 --- a/crypto/rsa/tests/rsa_1024_tests.rs +++ b/crypto/rsa/tests/rsa_1024_tests.rs @@ -89,15 +89,17 @@ fn pkcs1_v1_5_sha384_accepts_genuine_sig_gen_signatures() { }); } -#[test] -fn pkcs1_v1_5_rejects_wrong_message() { +fn run_sig_gen_group_rejects_wrong_message( + sha: &str, + verify: impl Fn(&Rsa1024PublicKey, &[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-256" && g["tests"].as_array().unwrap().len() == 8) + .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 = @@ -106,7 +108,22 @@ fn pkcs1_v1_5_rejects_wrong_message() { 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!( - pkcs1_v1_5_verify_sha256(&pk, b"a message this signature was not made for", &sig).is_err() - ); + 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| { + pkcs1_v1_5_verify_sha256(pk, msg, sig).is_ok() + }); +} + +/// Mutation testing found that `pkcs1_v1_5_verify_sha384` 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| { + pkcs1_v1_5_verify_sha384(pk, msg, sig).is_ok() + }); } diff --git a/crypto/rsa/tests/rsa_1536_tests.rs b/crypto/rsa/tests/rsa_1536_tests.rs index 3a6d0989..a025cd68 100644 --- a/crypto/rsa/tests/rsa_1536_tests.rs +++ b/crypto/rsa/tests/rsa_1536_tests.rs @@ -94,12 +94,13 @@ fn pkcs1_v1_5_sha512_accepts_genuine_sig_gen_signatures() { }); } -#[test] -fn pkcs1_v1_5_rejects_wrong_message() { +fn run_sig_gen_group_rejects_wrong_message( + sha: &str, + verify: impl Fn(&Rsa1536PublicKey, &[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-256").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(); @@ -107,7 +108,29 @@ fn pkcs1_v1_5_rejects_wrong_message() { 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!( - pkcs1_v1_5_verify_sha256(&pk, b"a message this signature was not made for", &sig).is_err() - ); + 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| { + pkcs1_v1_5_verify_sha256(pk, msg, sig).is_ok() + }); +} + +/// Mutation testing found that `pkcs1_v1_5_verify_sha384`/`_sha512` 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| { + pkcs1_v1_5_verify_sha384(pk, msg, sig).is_ok() + }); +} + +#[test] +fn pkcs1_v1_5_sha512_rejects_wrong_message() { + run_sig_gen_group_rejects_wrong_message("SHA-512", |pk, msg, sig| { + pkcs1_v1_5_verify_sha512(pk, msg, sig).is_ok() + }); } diff --git a/crypto/rsa/tests/rsa_3072_tests.rs b/crypto/rsa/tests/rsa_3072_tests.rs index 643798af..cdee2641 100644 --- a/crypto/rsa/tests/rsa_3072_tests.rs +++ b/crypto/rsa/tests/rsa_3072_tests.rs @@ -1,7 +1,9 @@ //! 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). +//! 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_sign_sha{256,384,512}[_with_salt]` function 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 @@ -13,8 +15,9 @@ use bouncycastle_rng::DefaultRNG; use bouncycastle_rsa::rsa_3072::{ Rsa3072PrivateKey, Rsa3072PublicKey, pkcs1_v1_5_sign_sha256, pkcs1_v1_5_sign_sha384, pkcs1_v1_5_sign_sha512, pkcs1_v1_5_verify_sha256, pkcs1_v1_5_verify_sha384, - pkcs1_v1_5_verify_sha512, pss_sign_sha256, pss_sign_sha384_with_salt, pss_sign_sha512, - pss_verify_sha256, pss_verify_sha384, pss_verify_sha512, + pkcs1_v1_5_verify_sha512, pss_sign_sha256, pss_sign_sha256_with_salt, pss_sign_sha384, + pss_sign_sha384_with_salt, pss_sign_sha512, pss_sign_sha512_with_salt, pss_verify_sha256, + pss_verify_sha384, pss_verify_sha512, }; use serde_json::Value; use std::fs; @@ -132,27 +135,86 @@ fn pkcs1_v1_5_sha384_and_sha512_round_trip() { pkcs1_v1_5_verify_sha512(&pk, b"hello", &sig512).unwrap(); } +/// Mutation testing found that `pss_sign_sha256_with_salt`, `pss_sign_sha384` (the RNG variant), +/// `pss_sign_sha512_with_salt`, and `pss_verify_sha384`/`pss_verify_sha512`'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_sha384_sha512_round_trip() { +fn pss_sha256_fixed_salt_round_trips() { + let sk = genuine_key(); + let pk = Rsa3072PublicKey::new(sk.n(), 0x10001).unwrap(); + let salt = [0x22u8; 32]; + let sig = pss_sign_sha256_with_salt(&sk, b"hello", &salt).expect("signing must succeed"); + pss_verify_sha256(&pk, b"hello", &sig).expect("must verify"); + assert!(pss_verify_sha256(&pk, b"goodbye", &sig).is_err()); +} + +#[test] +fn pss_sha256_rng_produces_fresh_salts_that_both_verify() { let sk = genuine_key(); let pk = Rsa3072PublicKey::new(sk.n(), 0x10001).unwrap(); let mut rng = DefaultRNG::default(); + let sig_a = pss_sign_sha256(&sk, b"hello", &mut rng).expect("signing must succeed"); + let sig_b = pss_sign_sha256(&sk, b"hello", &mut rng).expect("signing must succeed"); + assert_ne!(sig_a, sig_b, "PSS is randomized: two signatures of the same message must differ"); + pss_verify_sha256(&pk, b"hello", &sig_a).expect("sig_a must verify"); + pss_verify_sha256(&pk, b"hello", &sig_b).expect("sig_b must verify"); +} - let sig256 = pss_sign_sha256(&sk, b"hello", &mut rng).unwrap(); - pss_verify_sha256(&pk, b"hello", &sig256).unwrap(); +#[test] +fn pss_sha384_fixed_salt_round_trips() { + let sk = genuine_key(); + let pk = Rsa3072PublicKey::new(sk.n(), 0x10001).unwrap(); + let salt = [0x11u8; 48]; + let sig = pss_sign_sha384_with_salt(&sk, b"hello", &salt).expect("signing must succeed"); + pss_verify_sha384(&pk, b"hello", &sig).expect("must verify"); + assert!(pss_verify_sha384(&pk, b"goodbye", &sig).is_err()); +} + +#[test] +fn pss_sha384_rng_produces_fresh_salts_that_both_verify() { + let sk = genuine_key(); + let pk = Rsa3072PublicKey::new(sk.n(), 0x10001).unwrap(); + let mut rng = DefaultRNG::default(); + let sig_a = pss_sign_sha384(&sk, b"hello", &mut rng).expect("signing must succeed"); + let sig_b = pss_sign_sha384(&sk, b"hello", &mut rng).expect("signing must succeed"); + assert_ne!(sig_a, sig_b, "PSS is randomized: two signatures of the same message must differ"); + pss_verify_sha384(&pk, b"hello", &sig_a).expect("sig_a must verify"); + pss_verify_sha384(&pk, b"hello", &sig_b).expect("sig_b must verify"); +} - let salt384 = [0x11u8; 48]; - let sig384 = pss_sign_sha384_with_salt(&sk, b"hello", &salt384).unwrap(); - pss_verify_sha384(&pk, b"hello", &sig384).unwrap(); +#[test] +fn pss_sha512_fixed_salt_round_trips() { + let sk = genuine_key(); + let pk = Rsa3072PublicKey::new(sk.n(), 0x10001).unwrap(); + let salt = [0x33u8; 64]; + let sig = pss_sign_sha512_with_salt(&sk, b"hello", &salt).expect("signing must succeed"); + pss_verify_sha512(&pk, b"hello", &sig).expect("must verify"); + assert!(pss_verify_sha512(&pk, b"goodbye", &sig).is_err()); +} - let sig512 = pss_sign_sha512(&sk, b"hello", &mut rng).unwrap(); - pss_verify_sha512(&pk, b"hello", &sig512).unwrap(); +#[test] +fn pss_sha512_rng_produces_fresh_salts_that_both_verify() { + let sk = genuine_key(); + let pk = Rsa3072PublicKey::new(sk.n(), 0x10001).unwrap(); + let mut rng = DefaultRNG::default(); + let sig_a = pss_sign_sha512(&sk, b"hello", &mut rng).expect("signing must succeed"); + let sig_b = pss_sign_sha512(&sk, b"hello", &mut rng).expect("signing must succeed"); + assert_ne!(sig_a, sig_b, "PSS is randomized: two signatures of the same message must differ"); + pss_verify_sha512(&pk, b"hello", &sig_a).expect("sig_a must verify"); + pss_verify_sha512(&pk, b"hello", &sig_b).expect("sig_b must verify"); } fn run_pkcs1_v1_5_verify_vectors( filename: &str, verify: impl Fn(&Rsa3072PublicKey, &[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; @@ -198,8 +260,8 @@ fn run_pkcs1_v1_5_verify_vectors( } } assert_eq!(num_missing_null, 1); - assert_eq!(num_valid, 8, "for {filename}"); - assert_eq!(num_invalid, 250, "for {filename}"); + assert_eq!(num_valid, expected_valid, "for {filename}"); + assert_eq!(num_invalid, expected_invalid, "for {filename}"); } #[test] @@ -208,6 +270,38 @@ fn rsa_signature_3072_sha256_wycheproof_vectors() { "rsa_signature_3072_sha256_test.json", |pk, msg, sig| pkcs1_v1_5_verify_sha256(pk, msg, sig).is_ok(), "SHA-256", + 8, + 250, + ); +} + +/// Mutation testing found `pkcs1_v1_5_verify_sha384` 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| pkcs1_v1_5_verify_sha384(pk, msg, sig).is_ok(), + "SHA-384", + 7, + 251, + ); +} + +/// As [`rsa_signature_3072_sha384_wycheproof_vectors`], for `pkcs1_v1_5_verify_sha512`. 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| pkcs1_v1_5_verify_sha512(pk, msg, sig).is_ok(), + "SHA-512", + 8, + 251, ); } diff --git a/crypto/rsa/tests/rsa_4096_tests.rs b/crypto/rsa/tests/rsa_4096_tests.rs index 30d51fb5..4e9d7ac4 100644 --- a/crypto/rsa/tests/rsa_4096_tests.rs +++ b/crypto/rsa/tests/rsa_4096_tests.rs @@ -1,17 +1,24 @@ //! 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). +//! 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 +//! function (`pkcs1_v1_5_sign_sha384`/`_sha512`, and all six `pss_sign_sha{256,384,512} +//! [_with_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_hex::decode as hex_decode; +use bouncycastle_rng::DefaultRNG; use bouncycastle_rsa::rsa_4096::{ - Rsa4096PrivateKey, Rsa4096PublicKey, pkcs1_v1_5_sign_sha256, pkcs1_v1_5_verify_sha256, - pkcs1_v1_5_verify_sha384, pkcs1_v1_5_verify_sha512, pss_verify_sha256, pss_verify_sha384, - pss_verify_sha512, + Rsa4096PrivateKey, Rsa4096PublicKey, pkcs1_v1_5_sign_sha256, pkcs1_v1_5_sign_sha384, + pkcs1_v1_5_sign_sha512, pkcs1_v1_5_verify_sha256, pkcs1_v1_5_verify_sha384, + pkcs1_v1_5_verify_sha512, pss_sign_sha256, pss_sign_sha256_with_salt, pss_sign_sha384, + pss_sign_sha384_with_salt, pss_sign_sha512, pss_sign_sha512_with_salt, pss_verify_sha256, + pss_verify_sha384, pss_verify_sha512, }; use serde_json::Value; use std::fs; @@ -129,6 +136,20 @@ fn pkcs1_v1_5_sig_gen_4096_sha256() { assert_eq!(num_tests, 8); } +/// Mutation testing found that `pkcs1_v1_5_sign_sha384`/`_sha512` 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 = Rsa4096PublicKey::new(sk.n(), 0x10001).unwrap(); + let sig384 = pkcs1_v1_5_sign_sha384(&sk, b"hello").unwrap(); + pkcs1_v1_5_verify_sha384(&pk, b"hello", &sig384).unwrap(); + let sig512 = pkcs1_v1_5_sign_sha512(&sk, b"hello").unwrap(); + pkcs1_v1_5_verify_sha512(&pk, b"hello", &sig512).unwrap(); +} + fn run_pkcs1_v1_5_verify_vectors( filename: &str, verify: impl Fn(&Rsa4096PublicKey, &[u8], &[u8; 512]) -> bool, @@ -300,3 +321,75 @@ fn rsa_pss_4096_sha512_mgf1_64_wycheproof_vectors() { 47, ); } + +/// Mutation testing found that none of the six `pss_sign_sha{256,384,512}[_with_salt]` functions +/// 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 = Rsa4096PublicKey::new(sk.n(), 0x10001).unwrap(); + let salt = [0x22u8; 32]; + let sig = pss_sign_sha256_with_salt(&sk, b"hello", &salt).expect("signing must succeed"); + pss_verify_sha256(&pk, b"hello", &sig).expect("must verify"); + assert!(pss_verify_sha256(&pk, b"goodbye", &sig).is_err()); +} + +#[test] +fn pss_sha256_rng_produces_fresh_salts_that_both_verify() { + let sk = genuine_key(); + let pk = Rsa4096PublicKey::new(sk.n(), 0x10001).unwrap(); + let mut rng = DefaultRNG::default(); + let sig_a = pss_sign_sha256(&sk, b"hello", &mut rng).expect("signing must succeed"); + let sig_b = pss_sign_sha256(&sk, b"hello", &mut rng).expect("signing must succeed"); + assert_ne!(sig_a, sig_b, "PSS is randomized: two signatures of the same message must differ"); + pss_verify_sha256(&pk, b"hello", &sig_a).expect("sig_a must verify"); + pss_verify_sha256(&pk, b"hello", &sig_b).expect("sig_b must verify"); +} + +#[test] +fn pss_sha384_fixed_salt_round_trips() { + let sk = genuine_key(); + let pk = Rsa4096PublicKey::new(sk.n(), 0x10001).unwrap(); + let salt = [0x11u8; 48]; + let sig = pss_sign_sha384_with_salt(&sk, b"hello", &salt).expect("signing must succeed"); + pss_verify_sha384(&pk, b"hello", &sig).expect("must verify"); + assert!(pss_verify_sha384(&pk, b"goodbye", &sig).is_err()); +} + +#[test] +fn pss_sha384_rng_produces_fresh_salts_that_both_verify() { + let sk = genuine_key(); + let pk = Rsa4096PublicKey::new(sk.n(), 0x10001).unwrap(); + let mut rng = DefaultRNG::default(); + let sig_a = pss_sign_sha384(&sk, b"hello", &mut rng).expect("signing must succeed"); + let sig_b = pss_sign_sha384(&sk, b"hello", &mut rng).expect("signing must succeed"); + assert_ne!(sig_a, sig_b, "PSS is randomized: two signatures of the same message must differ"); + pss_verify_sha384(&pk, b"hello", &sig_a).expect("sig_a must verify"); + pss_verify_sha384(&pk, b"hello", &sig_b).expect("sig_b must verify"); +} + +#[test] +fn pss_sha512_fixed_salt_round_trips() { + let sk = genuine_key(); + let pk = Rsa4096PublicKey::new(sk.n(), 0x10001).unwrap(); + let salt = [0x33u8; 64]; + let sig = pss_sign_sha512_with_salt(&sk, b"hello", &salt).expect("signing must succeed"); + pss_verify_sha512(&pk, b"hello", &sig).expect("must verify"); + assert!(pss_verify_sha512(&pk, b"goodbye", &sig).is_err()); +} + +#[test] +fn pss_sha512_rng_produces_fresh_salts_that_both_verify() { + let sk = genuine_key(); + let pk = Rsa4096PublicKey::new(sk.n(), 0x10001).unwrap(); + let mut rng = DefaultRNG::default(); + let sig_a = pss_sign_sha512(&sk, b"hello", &mut rng).expect("signing must succeed"); + let sig_b = pss_sign_sha512(&sk, b"hello", &mut rng).expect("signing must succeed"); + assert_ne!(sig_a, sig_b, "PSS is randomized: two signatures of the same message must differ"); + pss_verify_sha512(&pk, b"hello", &sig_a).expect("sig_a must verify"); + pss_verify_sha512(&pk, b"hello", &sig_b).expect("sig_b must verify"); +} diff --git a/crypto/rsa/tests/rsa_8192_tests.rs b/crypto/rsa/tests/rsa_8192_tests.rs index 06457df5..aee4dc0e 100644 --- a/crypto/rsa/tests/rsa_8192_tests.rs +++ b/crypto/rsa/tests/rsa_8192_tests.rs @@ -25,8 +25,9 @@ use bouncycastle_rng::DefaultRNG; use bouncycastle_rsa::rsa_8192::{ Rsa8192PrivateKey, Rsa8192PublicKey, pkcs1_v1_5_sign_sha256, pkcs1_v1_5_sign_sha384, pkcs1_v1_5_sign_sha512, pkcs1_v1_5_verify_sha256, pkcs1_v1_5_verify_sha384, - pkcs1_v1_5_verify_sha512, pss_sign_sha256, pss_verify_sha256, pss_verify_sha384, - pss_verify_sha512, + pkcs1_v1_5_verify_sha512, pss_sign_sha256, pss_sign_sha256_with_salt, pss_sign_sha384, + pss_sign_sha384_with_salt, pss_sign_sha512, pss_sign_sha512_with_salt, pss_verify_sha256, + pss_verify_sha384, pss_verify_sha512, }; use serde_json::Value; use std::collections::HashSet; @@ -199,23 +200,76 @@ fn pss_verifies_bc_java_sha256_signature() { .expect("BC Java's PSS/SHA-256 signature (default salt length = hLen) must verify"); } +/// Mutation testing found that `pss_sign_sha256_with_salt`, `pss_sign_sha384`/`pss_sign_sha512` +/// (the RNG variants), and `pss_verify_sha384`/`pss_verify_sha512`'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_self_consistency_sha256_sha384_sha512() { +fn pss_sha256_fixed_salt_round_trips() { + let sk = genuine_key(); + let pk = Rsa8192PublicKey::new(sk.n(), 0x10001).unwrap(); + let salt = [0x33u8; 32]; + let sig = pss_sign_sha256_with_salt(&sk, b"hello", &salt).expect("signing must succeed"); + pss_verify_sha256(&pk, b"hello", &sig).expect("must verify"); + assert!(pss_verify_sha256(&pk, b"goodbye", &sig).is_err()); +} + +#[test] +fn pss_sha256_rng_produces_fresh_salts_that_both_verify() { let sk = genuine_key(); let pk = Rsa8192PublicKey::new(sk.n(), 0x10001).unwrap(); let mut rng = DefaultRNG::default(); + let sig_a = pss_sign_sha256(&sk, b"hello", &mut rng).expect("signing must succeed"); + let sig_b = pss_sign_sha256(&sk, b"hello", &mut rng).expect("signing must succeed"); + assert_ne!(sig_a, sig_b, "PSS is randomized: two signatures of the same message must differ"); + pss_verify_sha256(&pk, b"hello", &sig_a).expect("sig_a must verify"); + pss_verify_sha256(&pk, b"hello", &sig_b).expect("sig_b must verify"); +} - let sig = pss_sign_sha256(&sk, b"hello", &mut rng).unwrap(); - pss_verify_sha256(&pk, b"hello", &sig).unwrap(); +#[test] +fn pss_sha384_fixed_salt_round_trips() { + let sk = genuine_key(); + let pk = Rsa8192PublicKey::new(sk.n(), 0x10001).unwrap(); + let salt = [0x11u8; 48]; + let sig = pss_sign_sha384_with_salt(&sk, b"hello", &salt).expect("signing must succeed"); + pss_verify_sha384(&pk, b"hello", &sig).expect("must verify"); + assert!(pss_verify_sha384(&pk, b"goodbye", &sig).is_err()); +} - // pss_sign_sha384/512 need a salt of their own hash's length; reuse sign_with_salt directly - // via the crate's generic engine is unnecessary here since rsa_8192 already exposes - // pss_sign_sha384/512 -- see rsa_2048_pss_sha384_sha512_tests.rs for the identical pattern. - use bouncycastle_rsa::rsa_8192::{pss_sign_sha384_with_salt, pss_sign_sha512_with_salt}; - let sig384 = pss_sign_sha384_with_salt(&sk, b"hello", &[0x11u8; 48]).unwrap(); - pss_verify_sha384(&pk, b"hello", &sig384).unwrap(); - let sig512 = pss_sign_sha512_with_salt(&sk, b"hello", &[0x22u8; 64]).unwrap(); - pss_verify_sha512(&pk, b"hello", &sig512).unwrap(); +#[test] +fn pss_sha384_rng_produces_fresh_salts_that_both_verify() { + let sk = genuine_key(); + let pk = Rsa8192PublicKey::new(sk.n(), 0x10001).unwrap(); + let mut rng = DefaultRNG::default(); + let sig_a = pss_sign_sha384(&sk, b"hello", &mut rng).expect("signing must succeed"); + let sig_b = pss_sign_sha384(&sk, b"hello", &mut rng).expect("signing must succeed"); + assert_ne!(sig_a, sig_b, "PSS is randomized: two signatures of the same message must differ"); + pss_verify_sha384(&pk, b"hello", &sig_a).expect("sig_a must verify"); + pss_verify_sha384(&pk, b"hello", &sig_b).expect("sig_b must verify"); +} + +#[test] +fn pss_sha512_fixed_salt_round_trips() { + let sk = genuine_key(); + let pk = Rsa8192PublicKey::new(sk.n(), 0x10001).unwrap(); + let salt = [0x22u8; 64]; + let sig = pss_sign_sha512_with_salt(&sk, b"hello", &salt).expect("signing must succeed"); + pss_verify_sha512(&pk, b"hello", &sig).expect("must verify"); + assert!(pss_verify_sha512(&pk, b"goodbye", &sig).is_err()); +} + +#[test] +fn pss_sha512_rng_produces_fresh_salts_that_both_verify() { + let sk = genuine_key(); + let pk = Rsa8192PublicKey::new(sk.n(), 0x10001).unwrap(); + let mut rng = DefaultRNG::default(); + let sig_a = pss_sign_sha512(&sk, b"hello", &mut rng).expect("signing must succeed"); + let sig_b = pss_sign_sha512(&sk, b"hello", &mut rng).expect("signing must succeed"); + assert_ne!(sig_a, sig_b, "PSS is randomized: two signatures of the same message must differ"); + pss_verify_sha512(&pk, b"hello", &sig_a).expect("sig_a must verify"); + pss_verify_sha512(&pk, b"hello", &sig_b).expect("sig_b must verify"); } /// Every distinct `(result, flags)` combination in `filename`'s (single) test group, in file From 8bf5d831a9546583b60219d28b8750eef40368d3 Mon Sep 17 00:00:00 2001 From: David Hook Date: Sun, 20 Sep 2026 12:19:03 +1000 Subject: [PATCH 12/55] rsa: remove dead MontgomeryContext::modulus() An API-surface audit found this accessor has no caller anywhere in the crate: MontgomeryContext is only ever built and immediately handed to mod_pow/mul_mod/sub_mod, which use its private fields directly from within the same module -- nothing needs to read the modulus back out of a context after constructing it, since the caller already had it to build the context in the first place. Every other pub item modexp.rs exposes (mont_n_prime, mod_pow, mul_mod, sub_mod, reduce_wide, MontgomeryContext::new) is exercised by modexp_tests.rs; this one alone never was. Confirmed safe to remove against the scoped mutants follow-up run (emsa_pkcs1_v1_5.rs, modexp.rs, rsa_1024/1536/3072/4096/8192.rs) once it had fully processed modexp.rs's 49 mutants (44 caught, 3 pre-documented equivalents, 2 unviable, all expected) -- editing beforehand risked corrupting line-number alignment for mutants not yet applied to that file's then-current source. Co-Authored-By: Claude Sonnet 5 --- crypto/rsa/src/modexp.rs | 5 ----- 1 file changed, 5 deletions(-) diff --git a/crypto/rsa/src/modexp.rs b/crypto/rsa/src/modexp.rs index 1ad12f92..3a73531c 100644 --- a/crypto/rsa/src/modexp.rs +++ b/crypto/rsa/src/modexp.rs @@ -248,11 +248,6 @@ impl MontgomeryContext { let r2_mod_n = pow2_mod(128 * L as u32, modulus); Some(Self { modulus: *modulus, n_prime, r_mod_n, r2_mod_n }) } - - /// The modulus this context was built for. - pub fn modulus(&self) -> &[u64; L] { - &self.modulus - } } /// `base^exponent mod ctx.modulus()`, constant-time in `exponent`: every one of the modulus's From 2c0166e24e9b5e42e74a01baa5231de97b9b06dd Mon Sep 17 00:00:00 2001 From: David Hook Date: Mon, 21 Sep 2026 09:16:02 +1000 Subject: [PATCH 13/55] rsa: hand the EMSA encoders/verifiers the message hash instead of the message, and add *_from_hash entry points at the RSASSA layer Behaviour-preserving refactor ahead of wiring this crate into bouncycastle_core's Signer/SignatureVerifier traits: a streaming signer hashes the message incrementally and only has mHash by the time it can encode, but every EMSA function here (emsa_pkcs1_v1_5_encode/verify, emsa_pss_encode/verify, emsa_pss_encode_shake/verify_shake) took the whole message and computed `Hash(M)` itself on its first line. The EMSA layer now only has the hash-taking form -- EMSA-PKCS1-V1_5-ENCODE (RFC 8017 SS9.2) from step 2 onward, EMSA-PSS-ENCODE/VERIFY (SS9.1.1/SS9.1.2) from step 3/step 4 onward -- named *_from_hash so the spec operation's own name, which takes M, is not attached to a function that doesn't. Its message-taking wrappers are gone rather than kept as dead code; the unit tests that spoke in terms of messages get a two-line hashing helper each instead, so their KATs (which are EMs over specific messages) are unchanged. decode_digest_info compares against the caller's digest directly, dropping its Hash/Default bounds. The RSASSA layer (rsassa_pkcs1_v1_5, rsassa_pss, rsassa_pss_shake) gains sign_from_hash/verify_from_hash (and, for PSS, sign_from_hash_with_salt) alongside the existing message-taking sign/verify/sign_with_salt, which now hash and delegate -- so there is exactly one encoding path per scheme for either shape of caller to go through. The only observable change is ordering: PSS's salt is now drawn after the message is hashed rather than before (identical RNG consumption), and PKCS#1 v1.5 verification hashes the message before RSAVP1 rather than after the DigestInfo parse; both on public data only. cargo test -p bouncycastle-rsa: 143 passed, 0 failed, unchanged set. Co-Authored-By: Claude Fable 5.1 --- crypto/rsa/src/emsa_pkcs1_v1_5.rs | 175 +++++++++++++++------------- crypto/rsa/src/emsa_pss.rs | 64 +++++----- crypto/rsa/src/emsa_pss_shake.rs | 49 ++++---- crypto/rsa/src/rsassa_pkcs1_v1_5.rs | 61 ++++++++-- crypto/rsa/src/rsassa_pss.rs | 131 +++++++++++++++++++-- crypto/rsa/src/rsassa_pss_shake.rs | 126 ++++++++++++++++++-- 6 files changed, 450 insertions(+), 156 deletions(-) diff --git a/crypto/rsa/src/emsa_pkcs1_v1_5.rs b/crypto/rsa/src/emsa_pkcs1_v1_5.rs index a6f12339..48fb7323 100644 --- a/crypto/rsa/src/emsa_pkcs1_v1_5.rs +++ b/crypto/rsa/src/emsa_pkcs1_v1_5.rs @@ -1,10 +1,12 @@ //! EMSA-PKCS1-v1_5 (RFC 8017 §9.2): deterministic signature encoding, generic over the hash -//! function `H` via its [`Hash`]/[`HashAlgParams`]/[`AlgorithmOID`] impls (e.g. +//! 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. +//! 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, Hash, HashAlgParams}; +use bouncycastle_core::traits::{AlgorithmOID, HashAlgParams}; /// `T`, the DER encoding of `DigestInfo { digestAlgorithm, digest }` (RFC 8017 §9.2 step 2): /// @@ -50,25 +52,26 @@ fn digest_info( - message: &[u8], + digest: &[u8; H_LEN], ) -> [u8; K_LEN] { - let mut digest = [0u8; H_LEN]; - H::default().hash_out(message, &mut digest); - let t: [u8; T_LEN] = digest_info::(&digest); + let t: [u8; T_LEN] = digest_info::(digest); debug_assert!(K_LEN >= T_LEN + 11, "emsa_pkcs1_v1_5_encode: modulus too short for this hash"); @@ -81,24 +84,22 @@ pub fn emsa_pkcs1_v1_5_encode< } /// 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`]) or `bytes` doesn't reach +/// 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 `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`]'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], - message: &[u8], -) -> bool { +/// 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; H_LEN]) -> bool { let mut pos = 0; if t.first() != Some(&0x30) { return false; @@ -141,9 +142,9 @@ fn decode_digest_info( - message: &[u8], +pub fn emsa_pkcs1_v1_5_verify_from_hash( + digest: &[u8; H_LEN], em: &[u8; K_LEN], ) -> bool { if em[0] != 0x00 || em[1] != 0x01 { @@ -194,20 +193,38 @@ pub fn emsa_pkcs1_v1_5_verify< return false; } - decode_digest_info::(&em[i + 1..], message) + decode_digest_info::(&em[i + 1..], digest) } #[cfg(test)] mod tests { - //! `digest_info` is crate-private (only [`emsa_pkcs1_v1_5_encode`] 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. + //! `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::Hash; 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::default().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::default().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]; @@ -249,7 +266,7 @@ mod tests { #[test] fn encode_layout_is_00_01_ff_dot_dot_dot_00_t() { - let em = emsa_pkcs1_v1_5_encode::(b"hello"); + 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)); @@ -259,33 +276,33 @@ mod tests { #[test] fn encode_is_deterministic() { - let a = emsa_pkcs1_v1_5_encode::(b"same message"); - let b = emsa_pkcs1_v1_5_encode::(b"same message"); + 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 = emsa_pkcs1_v1_5_encode::(b"message one"); - let b = emsa_pkcs1_v1_5_encode::(b"message two"); + 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 = emsa_pkcs1_v1_5_encode::(b"hello"); - assert!(emsa_pkcs1_v1_5_verify::(b"hello", &em)); + let em = encode::<256>(b"hello"); + assert!(verify::<256>(b"hello", &em)); } #[test] fn verify_rejects_wrong_message() { - let em = emsa_pkcs1_v1_5_encode::(b"hello"); - assert!(!emsa_pkcs1_v1_5_verify::(b"goodbye", &em)); + 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`] always includes. + /// 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]; @@ -311,7 +328,7 @@ mod tests { em[256 - 49 - 1] = 0x00; em[256 - 49..].copy_from_slice(&t); - assert!(emsa_pkcs1_v1_5_verify::(b"hello", &em)); + assert!(verify::<256>(b"hello", &em)); } /// Wycheproof's `BerEncodedPadding`: a `DigestInfo` length re-encoded in BER long form (top @@ -320,21 +337,21 @@ mod tests { /// Bleichenbacher-style forgeries exploit, regardless of what value it happens to encode. #[test] fn verify_rejects_ber_long_form_length() { - let mut em = emsa_pkcs1_v1_5_encode::(b"hello"); + 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!(!emsa_pkcs1_v1_5_verify::(b"hello", &em)); + 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 = emsa_pkcs1_v1_5_encode::(b"hello"); + let mut em = encode::<256>(b"hello"); let t_start = 256 - 51; em[t_start + 1] += 1; - assert!(!emsa_pkcs1_v1_5_verify::(b"hello", &em)); + assert!(!verify::<256>(b"hello", &em)); } /// Wycheproof's `ModifiedPadding` ("appending 0's to digestInfo"): two extra zero bytes appended @@ -343,14 +360,14 @@ mod tests { /// 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 = emsa_pkcs1_v1_5_encode::(b"hello"); + 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!(!emsa_pkcs1_v1_5_verify::(b"hello", &em)); + assert!(!verify::<256>(b"hello", &em)); } /// Wycheproof's `ShortPadding`: fewer than the required 8 `0xff` bytes. @@ -360,17 +377,17 @@ mod tests { em[0] = 0x00; em[1] = 0x01; em[2] = 0x00; // PS has length 0, not >= 8 - assert!(!emsa_pkcs1_v1_5_verify::(b"hello", &em)); + 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 = emsa_pkcs1_v1_5_encode::(b"hello"); + let mut em = encode::<256>(b"hello"); let t_start = 256 - 51; em[t_start + 4] ^= 0xff; // flip a byte inside the OID - assert!(!emsa_pkcs1_v1_5_verify::(b"hello", &em)); + assert!(!verify::<256>(b"hello", &em)); } /// A crafted `EM` whose `DigestInfo` claims an `AlgorithmIdentifier` length long enough to run @@ -395,36 +412,36 @@ mod tests { em[253] = 0x02; em[254] = 0x30; em[255] = 0x64; - assert!(!emsa_pkcs1_v1_5_verify::(b"hello", &em)); + 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`]'s docs describe), which pins `PS` to exactly 8 bytes -- the one + /// [`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 = emsa_pkcs1_v1_5_encode::(b"hello"); + let em = encode::<62>(b"hello"); assert_eq!(em[2..2 + 8], [0xff; 8], "this construction must exercise ps_len == 8 exactly"); - assert!(emsa_pkcs1_v1_5_verify::(b"hello", &em)); + 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 = emsa_pkcs1_v1_5_encode::(b"hello"); + let mut em = encode::<256>(b"hello"); em[1] = 0x02; - assert!(!emsa_pkcs1_v1_5_verify::(b"hello", &em)); + 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 = emsa_pkcs1_v1_5_encode::(b"hello"); + let mut em = encode::<256>(b"hello"); em[0] = 0x01; - assert!(!emsa_pkcs1_v1_5_verify::(b"hello", &em)); + assert!(!verify::<256>(b"hello", &em)); } } diff --git a/crypto/rsa/src/emsa_pss.rs b/crypto/rsa/src/emsa_pss.rs index 3fe2c91c..c3aec041 100644 --- a/crypto/rsa/src/emsa_pss.rs +++ b/crypto/rsa/src/emsa_pss.rs @@ -13,13 +13,16 @@ use crate::mgf1::mgf1; use bouncycastle_core::traits::Hash; -/// EMSA-PSS-ENCODE (RFC 8017 §9.1.1), with `emBits` fixed to `8 * K_LEN - 1` (see the module -/// docs) and the salt supplied by the caller 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. -pub fn emsa_pss_encode< +/// 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. +pub fn emsa_pss_encode_from_hash< H: Hash + Default, const H_LEN: usize, const SEED_LEN: usize, @@ -28,7 +31,7 @@ pub fn emsa_pss_encode< const DB_LEN: usize, const K_LEN: usize, >( - message: &[u8], + m_hash: &[u8; H_LEN], salt: &[u8; S_LEN], ) -> [u8; K_LEN] { debug_assert_eq!(M_PRIME_LEN, 8 + H_LEN + S_LEN, "emsa_pss_encode: M_PRIME_LEN mismatch"); @@ -38,13 +41,9 @@ pub fn emsa_pss_encode< "emsa_pss_encode: modulus too short for this hash/salt" ); - // Steps 1-2: mHash = Hash(M). - let mut m_hash = [0u8; H_LEN]; - H::default().hash_out(message, &mut m_hash); - // Steps 5-6: M' = 8 zero octets || mHash || salt; H = Hash(M'). let mut m_prime = [0u8; M_PRIME_LEN]; - m_prime[8..8 + H_LEN].copy_from_slice(&m_hash); + m_prime[8..8 + H_LEN].copy_from_slice(m_hash); m_prime[8 + H_LEN..].copy_from_slice(salt); let mut h = [0u8; H_LEN]; H::default().hash_out(&m_prime, &mut h); @@ -70,10 +69,11 @@ pub fn emsa_pss_encode< em } -/// EMSA-PSS-VERIFY (RFC 8017 §9.1.2), with `emBits` fixed as [`emsa_pss_encode`]'s is. Step 1's -/// message-length limit and step 3's minimum-`emLen` check are not reachable for this crate's -/// fixed sizes, for the same reasons given there. -pub fn emsa_pss_verify< +/// EMSA-PSS-VERIFY (RFC 8017 §9.1.2) from step 4 onward, with `emBits` fixed as +/// [`emsa_pss_encode_from_hash`]'s is and step 2's `mHash = Hash(M)` supplied by the caller the +/// same way. Step 1's message-length limit and step 3's minimum-`emLen` check are not reachable +/// for this crate's fixed sizes, for the same reasons given there. +pub fn emsa_pss_verify_from_hash< H: Hash + Default, const H_LEN: usize, const SEED_LEN: usize, @@ -82,7 +82,7 @@ pub fn emsa_pss_verify< const DB_LEN: usize, const K_LEN: usize, >( - message: &[u8], + m_hash: &[u8; H_LEN], em: &[u8; K_LEN], ) -> bool { // Step 4. @@ -118,11 +118,9 @@ pub fn emsa_pss_verify< let mut salt = [0u8; S_LEN]; salt.copy_from_slice(&db[DB_LEN - S_LEN..]); - // Steps 12-14. - let mut m_hash = [0u8; H_LEN]; - H::default().hash_out(message, &mut m_hash); + // Steps 12-14 (step 2's mHash is the caller's `m_hash`). let mut m_prime = [0u8; M_PRIME_LEN]; - m_prime[8..8 + H_LEN].copy_from_slice(&m_hash); + m_prime[8..8 + H_LEN].copy_from_slice(m_hash); m_prime[8 + H_LEN..].copy_from_slice(&salt); let mut h_prime = [0u8; H_LEN]; H::default().hash_out(&m_prime, &mut h_prime); @@ -132,11 +130,13 @@ pub fn emsa_pss_verify< #[cfg(test)] mod tests { - //! `emsa_pss_encode`/`emsa_pss_verify` 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. + //! `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 bouncycastle_sha2::SHA256; @@ -167,12 +167,18 @@ mod tests { 0xbc, ]; + fn m_hash(message: &[u8]) -> [u8; 32] { + let mut m_hash = [0u8; 32]; + SHA256::default().hash_out(message, &mut m_hash); + m_hash + } + fn encode(message: &[u8], salt: &[u8; 32]) -> [u8; 256] { - emsa_pss_encode::(message, salt) + emsa_pss_encode_from_hash::(&m_hash(message), salt) } fn verify(message: &[u8], em: &[u8; 256]) -> bool { - emsa_pss_verify::(message, em) + emsa_pss_verify_from_hash::(&m_hash(message), em) } #[test] diff --git a/crypto/rsa/src/emsa_pss_shake.rs b/crypto/rsa/src/emsa_pss_shake.rs index 81a7f49d..a7fe1582 100644 --- a/crypto/rsa/src/emsa_pss_shake.rs +++ b/crypto/rsa/src/emsa_pss_shake.rs @@ -15,9 +15,11 @@ use bouncycastle_core::traits::XOF; -/// EMSA-PSS-ENCODE (RFC 8017 §9.1.1) with the mask generation function replaced by native SHAKE -/// output (RFC 8702 §3.2.1). See the module docs for `emBits` and the salt argument. -pub fn emsa_pss_encode_shake< +/// EMSA-PSS-ENCODE (RFC 8017 §9.1.1) from step 3 onward with the mask generation function +/// replaced by native SHAKE output (RFC 8702 §3.2.1), given steps 1-2's `mHash = Hash(M)` by the +/// caller exactly as [`crate::emsa_pss::emsa_pss_encode_from_hash`] is. See the module docs for +/// `emBits` and the salt argument. +pub fn emsa_pss_encode_shake_from_hash< X: XOF + Default, const H_LEN: usize, const S_LEN: usize, @@ -25,7 +27,7 @@ pub fn emsa_pss_encode_shake< const DB_LEN: usize, const K_LEN: usize, >( - message: &[u8], + m_hash: &[u8; H_LEN], salt: &[u8; S_LEN], ) -> [u8; K_LEN] { debug_assert_eq!(M_PRIME_LEN, 8 + H_LEN + S_LEN, "emsa_pss_encode_shake: M_PRIME_LEN mismatch"); @@ -35,13 +37,9 @@ pub fn emsa_pss_encode_shake< "emsa_pss_encode_shake: modulus too short for this hash/salt" ); - // Steps 1-2: mHash = Hash(M). - let mut m_hash = [0u8; H_LEN]; - X::default().hash_out(message, &mut m_hash); - // Steps 5-6: M' = 8 zero octets || mHash || salt; H = Hash(M'). let mut m_prime = [0u8; M_PRIME_LEN]; - m_prime[8..8 + H_LEN].copy_from_slice(&m_hash); + m_prime[8..8 + H_LEN].copy_from_slice(m_hash); m_prime[8 + H_LEN..].copy_from_slice(salt); let mut h = [0u8; H_LEN]; X::default().hash_out(&m_prime, &mut h); @@ -69,9 +67,10 @@ pub fn emsa_pss_encode_shake< em } -/// EMSA-PSS-VERIFY (RFC 8017 §9.1.2) with the mask generation function replaced by native SHAKE -/// output, as [`emsa_pss_encode_shake`]. -pub fn emsa_pss_verify_shake< +/// EMSA-PSS-VERIFY (RFC 8017 §9.1.2) from step 4 onward with the mask generation function +/// replaced by native SHAKE output, as [`emsa_pss_encode_shake_from_hash`], and step 2's +/// `mHash = Hash(M)` supplied by the caller the same way. +pub fn emsa_pss_verify_shake_from_hash< X: XOF + Default, const H_LEN: usize, const S_LEN: usize, @@ -79,7 +78,7 @@ pub fn emsa_pss_verify_shake< const DB_LEN: usize, const K_LEN: usize, >( - message: &[u8], + m_hash: &[u8; H_LEN], em: &[u8; K_LEN], ) -> bool { // Step 4. @@ -116,11 +115,9 @@ pub fn emsa_pss_verify_shake< let mut salt = [0u8; S_LEN]; salt.copy_from_slice(&db[DB_LEN - S_LEN..]); - // Steps 12-14. - let mut m_hash = [0u8; H_LEN]; - X::default().hash_out(message, &mut m_hash); + // Steps 12-14 (step 2's mHash is the caller's `m_hash`). let mut m_prime = [0u8; M_PRIME_LEN]; - m_prime[8..8 + H_LEN].copy_from_slice(&m_hash); + m_prime[8..8 + H_LEN].copy_from_slice(m_hash); m_prime[8 + H_LEN..].copy_from_slice(&salt); let mut h_prime = [0u8; H_LEN]; X::default().hash_out(&m_prime, &mut h_prime); @@ -130,14 +127,16 @@ pub fn emsa_pss_verify_shake< #[cfg(test)] mod tests { - //! `emsa_pss_encode_shake`/`emsa_pss_verify_shake` are crate-private (only - //! [`crate::rsassa_pss_shake`] needs them), so they are exercised here rather than from + //! `emsa_pss_encode_shake_from_hash`/`emsa_pss_verify_shake_from_hash` are crate-private + //! (only [`crate::rsassa_pss_shake`] 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 with RFC 8702 SS3.2.1's native-SHAKE mask substituted for MGF1 (not from - //! recall), using `hashlib.shake_128`. + //! 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::*; + use bouncycastle_core::traits::Hash; use bouncycastle_sha3::SHAKE128; const SALT: [u8; 32] = [ @@ -146,12 +145,18 @@ mod tests { 0x1e, 0x1f, ]; + fn m_hash(message: &[u8]) -> [u8; 32] { + let mut m_hash = [0u8; 32]; + SHAKE128::default().hash_out(message, &mut m_hash); + m_hash + } + fn encode(message: &[u8], salt: &[u8; 32]) -> [u8; 256] { - emsa_pss_encode_shake::(message, salt) + emsa_pss_encode_shake_from_hash::(&m_hash(message), salt) } fn verify(message: &[u8], em: &[u8; 256]) -> bool { - emsa_pss_verify_shake::(message, em) + emsa_pss_verify_shake_from_hash::(&m_hash(message), em) } #[test] diff --git a/crypto/rsa/src/rsassa_pkcs1_v1_5.rs b/crypto/rsa/src/rsassa_pkcs1_v1_5.rs index f2982030..3012c098 100644 --- a/crypto/rsa/src/rsassa_pkcs1_v1_5.rs +++ b/crypto/rsa/src/rsassa_pkcs1_v1_5.rs @@ -6,7 +6,7 @@ //! literals (e.g. RSA-2048/SHA-256 in [`crate::rsa_2048`]) rather than a caller choosing them. use crate::codec::{be_bytes_from_limbs, limbs_from_be_bytes}; -use crate::emsa_pkcs1_v1_5::{emsa_pkcs1_v1_5_encode, emsa_pkcs1_v1_5_verify}; +use crate::emsa_pkcs1_v1_5::{emsa_pkcs1_v1_5_encode_from_hash, emsa_pkcs1_v1_5_verify_from_hash}; use crate::keys::{RsaPrivateKey, RsaPublicKey}; use crate::rsa_core::{rsasp1, rsavp1}; use bouncycastle_core::errors::SignatureError; @@ -14,10 +14,12 @@ use bouncycastle_core::traits::{AlgorithmOID, Hash, HashAlgParams}; /// RSASSA-PKCS1-V1_5-SIGN (RFC 8017 §8.2.1): `S = I2OSP(RSASP1(K, OS2IP(EM)), k)`, where /// `EM = EMSA-PKCS1-V1_5-ENCODE(M, k)`. Step 1's two errors ("message too long" -- unreachable -/// here, since [`emsa_pkcs1_v1_5_encode`]'s own length is fixed at compile time by `K_LEN`, never -/// computed from `message`'s length -- and "RSA modulus too short") are folded into -/// [`emsa_pkcs1_v1_5_encode`]'s `debug_assert`, not raised here as a runtime error, for the same -/// reason given there. +/// here, since the encoding's own length is fixed at compile time by `K_LEN`, never computed from +/// `message`'s length -- and "RSA modulus too short") are folded into +/// [`emsa_pkcs1_v1_5_encode_from_hash`]'s `debug_assert`, not raised here as a runtime error, for +/// the same reason given there. +/// +/// Hashes `message` (EMSA-PKCS1-v1_5 step 1) and hands the digest to [`sign_from_hash`]. pub fn sign< H: Hash + HashAlgParams + AlgorithmOID + Default, const H_LEN: usize, @@ -33,7 +35,31 @@ pub fn sign< sk: &RsaPrivateKey, message: &[u8], ) -> Result<[u8; K_LEN], SignatureError> { - let em = emsa_pkcs1_v1_5_encode::(message); + let mut digest = [0u8; H_LEN]; + H::default().hash_out(message, &mut digest); + sign_from_hash::(sk, &digest) +} + +/// [`sign`] given the message's hash `digest` (`H`'s output over the message) instead of the +/// message itself -- for a caller that hashed the message incrementally, such as a streaming +/// `Signer`. The `H` bound is only what [`emsa_pkcs1_v1_5_encode_from_hash`] needs to build the +/// `DigestInfo`; no hashing happens here. +pub fn sign_from_hash< + H: HashAlgParams + AlgorithmOID, + const H_LEN: usize, + const T_LEN: usize, + const L: usize, + const L2: usize, + const L21: usize, + const HALF: usize, + const HALF2: usize, + const HALF21: usize, + const K_LEN: usize, +>( + sk: &RsaPrivateKey, + digest: &[u8; H_LEN], +) -> Result<[u8; K_LEN], SignatureError> { + let em = emsa_pkcs1_v1_5_encode_from_hash::(digest); let m = limbs_from_be_bytes::(&em); let s = rsasp1::(sk, &m)?; Ok(be_bytes_from_limbs::(&s)) @@ -52,6 +78,8 @@ pub fn sign< /// CAVP/wycheproof-style vectors needs to tell "malformed input" apart from "well-formed but /// wrong", the same distinction RFC 8017 itself draws by giving the range check its own error /// text. +/// +/// Hashes `message` and hands the digest to [`verify_from_hash`]. pub fn verify< H: Hash + HashAlgParams + AlgorithmOID + Default, const H_LEN: usize, @@ -63,12 +91,31 @@ pub fn verify< pk: &RsaPublicKey, message: &[u8], signature: &[u8; K_LEN], +) -> Result<(), SignatureError> { + let mut digest = [0u8; H_LEN]; + H::default().hash_out(message, &mut digest); + verify_from_hash::(pk, &digest, signature) +} + +/// [`verify`] given the message's hash `digest` instead of the message -- the counterpart of +/// [`sign_from_hash`], for a streaming `SignatureVerifier`. +pub fn verify_from_hash< + H: AlgorithmOID, + const H_LEN: usize, + const L: usize, + const L2: usize, + const L21: usize, + const K_LEN: usize, +>( + pk: &RsaPublicKey, + digest: &[u8; H_LEN], + signature: &[u8; K_LEN], ) -> Result<(), SignatureError> { let s = limbs_from_be_bytes::(signature); let m = rsavp1::(pk, &s)?; let em_prime = be_bytes_from_limbs::(&m); - if emsa_pkcs1_v1_5_verify::(message, &em_prime) { + if emsa_pkcs1_v1_5_verify_from_hash::(digest, &em_prime) { Ok(()) } else { Err(SignatureError::SignatureVerificationFailed) diff --git a/crypto/rsa/src/rsassa_pss.rs b/crypto/rsa/src/rsassa_pss.rs index f69f9565..8944da91 100644 --- a/crypto/rsa/src/rsassa_pss.rs +++ b/crypto/rsa/src/rsassa_pss.rs @@ -5,7 +5,7 @@ //! [`crate::rsa_2048`]). use crate::codec::{be_bytes_from_limbs, limbs_from_be_bytes}; -use crate::emsa_pss::{emsa_pss_encode, emsa_pss_verify}; +use crate::emsa_pss::{emsa_pss_encode_from_hash, emsa_pss_verify_from_hash}; use crate::keys::{RsaPrivateKey, RsaPublicKey}; use crate::rsa_core::{rsasp1, rsavp1}; use bouncycastle_core::errors::SignatureError; @@ -15,6 +15,8 @@ use bouncycastle_core::traits::{Hash, RNG}; /// RNG: EMSA-PSS is randomized only in its choice of salt (§9.1's own note 5), so fixing it makes /// this deterministic and directly testable against a known salt. [`sign`] is the RNG-backed /// entry point real callers want. +/// +/// Hashes `message` (EMSA-PSS step 2) and hands `mHash` to [`sign_from_hash_with_salt`]. pub fn sign_with_salt< H: Hash + Default, const H_LEN: usize, @@ -34,15 +36,58 @@ pub fn sign_with_salt< message: &[u8], salt: &[u8; S_LEN], ) -> Result<[u8; K_LEN], SignatureError> { - let em = - emsa_pss_encode::(message, salt); + let mut m_hash = [0u8; H_LEN]; + H::default().hash_out(message, &mut m_hash); + sign_from_hash_with_salt::< + H, + H_LEN, + SEED_LEN, + S_LEN, + M_PRIME_LEN, + DB_LEN, + L, + L2, + L21, + HALF, + HALF2, + HALF21, + K_LEN, + >(sk, &m_hash, salt) +} + +/// [`sign_with_salt`] given the message's hash `m_hash` (`H`'s output over the message) instead of +/// the message itself -- for a caller that hashed the message incrementally, such as a streaming +/// `Signer`. +pub fn sign_from_hash_with_salt< + H: Hash + Default, + const H_LEN: usize, + const SEED_LEN: usize, + const S_LEN: usize, + const M_PRIME_LEN: usize, + const DB_LEN: usize, + const L: usize, + const L2: usize, + const L21: usize, + const HALF: usize, + const HALF2: usize, + const HALF21: usize, + const K_LEN: usize, +>( + sk: &RsaPrivateKey, + m_hash: &[u8; H_LEN], + salt: &[u8; S_LEN], +) -> Result<[u8; K_LEN], SignatureError> { + let em = emsa_pss_encode_from_hash::( + m_hash, salt, + ); let m = limbs_from_be_bytes::(&em); let s = rsasp1::(sk, &m)?; Ok(be_bytes_from_limbs::(&s)) } /// RSASSA-PSS-SIGN (RFC 8017 §8.1.1), drawing a fresh `S_LEN`-byte salt from `rng` for each -/// signature (step 4 of EMSA-PSS-ENCODE). +/// signature (step 4 of EMSA-PSS-ENCODE). Hashes `message` and hands `mHash` to +/// [`sign_from_hash`]. pub fn sign< H: Hash + Default, const H_LEN: usize, @@ -61,10 +106,50 @@ pub fn sign< sk: &RsaPrivateKey, message: &[u8], rng: &mut dyn RNG, +) -> Result<[u8; K_LEN], SignatureError> { + let mut m_hash = [0u8; H_LEN]; + H::default().hash_out(message, &mut m_hash); + sign_from_hash::< + H, + H_LEN, + SEED_LEN, + S_LEN, + M_PRIME_LEN, + DB_LEN, + L, + L2, + L21, + HALF, + HALF2, + HALF21, + K_LEN, + >(sk, &m_hash, rng) +} + +/// [`sign`] given the message's hash `m_hash` instead of the message: draws the salt from `rng` +/// (EMSA-PSS-ENCODE step 4) and hands both to [`sign_from_hash_with_salt`]. +pub fn sign_from_hash< + H: Hash + Default, + const H_LEN: usize, + const SEED_LEN: usize, + const S_LEN: usize, + const M_PRIME_LEN: usize, + const DB_LEN: usize, + const L: usize, + const L2: usize, + const L21: usize, + const HALF: usize, + const HALF2: usize, + const HALF21: usize, + const K_LEN: usize, +>( + sk: &RsaPrivateKey, + m_hash: &[u8; H_LEN], + rng: &mut dyn RNG, ) -> Result<[u8; K_LEN], SignatureError> { let mut salt = [0u8; S_LEN]; rng.next_bytes_out(&mut salt).map_err(SignatureError::RNGError)?; - sign_with_salt::< + sign_from_hash_with_salt::< H, H_LEN, SEED_LEN, @@ -78,12 +163,13 @@ pub fn sign< HALF2, HALF21, K_LEN, - >(sk, message, &salt) + >(sk, m_hash, &salt) } /// RSASSA-PSS-VERIFY (RFC 8017 §8.1.2): recovers `EM = I2OSP(RSAVP1((n, e), OS2IP(S)), emLen)` -/// and checks it against `message` via [`emsa_pss_verify`], which recovers the salt from `EM` -/// itself (EMSA-PSS's own verification operation, §9.1.2) rather than needing it supplied. +/// and checks it against `message` via EMSA-PSS-VERIFY, which recovers the salt from `EM` itself +/// (EMSA-PSS's own verification operation, §9.1.2) rather than needing it supplied. Hashes +/// `message` and hands `mHash` to [`verify_from_hash`]. pub fn verify< H: Hash + Default, const H_LEN: usize, @@ -99,12 +185,39 @@ pub fn verify< pk: &RsaPublicKey, message: &[u8], signature: &[u8; K_LEN], +) -> Result<(), SignatureError> { + let mut m_hash = [0u8; H_LEN]; + H::default().hash_out(message, &mut m_hash); + verify_from_hash::( + pk, &m_hash, signature, + ) +} + +/// [`verify`] given the message's hash `m_hash` instead of the message -- the counterpart of +/// [`sign_from_hash`], for a streaming `SignatureVerifier`. +pub fn verify_from_hash< + H: Hash + Default, + const H_LEN: usize, + const SEED_LEN: usize, + const S_LEN: usize, + const M_PRIME_LEN: usize, + const DB_LEN: usize, + const L: usize, + const L2: usize, + const L21: usize, + const K_LEN: usize, +>( + pk: &RsaPublicKey, + m_hash: &[u8; H_LEN], + signature: &[u8; K_LEN], ) -> Result<(), SignatureError> { let s = limbs_from_be_bytes::(signature); let m = rsavp1::(pk, &s)?; let em = be_bytes_from_limbs::(&m); - if emsa_pss_verify::(message, &em) { + if emsa_pss_verify_from_hash::( + m_hash, &em, + ) { Ok(()) } else { Err(SignatureError::SignatureVerificationFailed) diff --git a/crypto/rsa/src/rsassa_pss_shake.rs b/crypto/rsa/src/rsassa_pss_shake.rs index 894ba81e..64504e51 100644 --- a/crypto/rsa/src/rsassa_pss_shake.rs +++ b/crypto/rsa/src/rsassa_pss_shake.rs @@ -5,7 +5,7 @@ //! [`crate::emsa_pss`]. use crate::codec::{be_bytes_from_limbs, limbs_from_be_bytes}; -use crate::emsa_pss_shake::{emsa_pss_encode_shake, emsa_pss_verify_shake}; +use crate::emsa_pss_shake::{emsa_pss_encode_shake_from_hash, emsa_pss_verify_shake_from_hash}; use crate::keys::{RsaPrivateKey, RsaPublicKey}; use crate::rsa_core::{rsasp1, rsavp1}; use bouncycastle_core::errors::SignatureError; @@ -14,7 +14,8 @@ use bouncycastle_core::traits::{RNG, XOF}; /// RSASSA-PSS-SIGN (RFC 8017 §8.1.1) with the salt supplied directly rather than drawn from an /// RNG, mirroring [`crate::rsassa_pss::sign_with_salt`]: EMSA-PSS is randomized only in its choice /// of salt, so fixing it makes this deterministic and directly testable. [`sign`] is the -/// RNG-backed entry point real callers want. +/// RNG-backed entry point real callers want. Hashes `message` (EMSA-PSS step 2) and hands `mHash` +/// to [`sign_from_hash_with_salt`]. pub fn sign_with_salt< X: XOF + Default, const H_LEN: usize, @@ -33,7 +34,48 @@ pub fn sign_with_salt< message: &[u8], salt: &[u8; S_LEN], ) -> Result<[u8; K_LEN], SignatureError> { - let em = emsa_pss_encode_shake::(message, salt); + let mut m_hash = [0u8; H_LEN]; + X::default().hash_out(message, &mut m_hash); + sign_from_hash_with_salt::< + X, + H_LEN, + S_LEN, + M_PRIME_LEN, + DB_LEN, + L, + L2, + L21, + HALF, + HALF2, + HALF21, + K_LEN, + >(sk, &m_hash, salt) +} + +/// [`sign_with_salt`] given the message's hash `m_hash` (`X`'s `H_LEN`-byte output over the +/// message) instead of the message itself -- for a caller that hashed the message incrementally, +/// such as a streaming `Signer`. +pub fn sign_from_hash_with_salt< + X: XOF + Default, + const H_LEN: usize, + const S_LEN: usize, + const M_PRIME_LEN: usize, + const DB_LEN: usize, + const L: usize, + const L2: usize, + const L21: usize, + const HALF: usize, + const HALF2: usize, + const HALF21: usize, + const K_LEN: usize, +>( + sk: &RsaPrivateKey, + m_hash: &[u8; H_LEN], + salt: &[u8; S_LEN], +) -> Result<[u8; K_LEN], SignatureError> { + let em = emsa_pss_encode_shake_from_hash::( + m_hash, salt, + ); let m = limbs_from_be_bytes::(&em); let s = rsasp1::(sk, &m)?; Ok(be_bytes_from_limbs::(&s)) @@ -41,7 +83,8 @@ pub fn sign_with_salt< /// RSASSA-PSS-SIGN (RFC 8017 §8.1.1), drawing a fresh `S_LEN`-byte salt from `rng` for each /// signature (step 4 of EMSA-PSS-ENCODE). RFC 8702 §3.2.1 fixes `S_LEN` at 32 bytes for -/// `id-RSASSA-PSS-SHAKE128` and 64 for `id-RSASSA-PSS-SHAKE256`. +/// `id-RSASSA-PSS-SHAKE128` and 64 for `id-RSASSA-PSS-SHAKE256`. Hashes `message` and hands +/// `mHash` to [`sign_from_hash`]. pub fn sign< X: XOF + Default, const H_LEN: usize, @@ -59,16 +102,55 @@ pub fn sign< sk: &RsaPrivateKey, message: &[u8], rng: &mut dyn RNG, +) -> Result<[u8; K_LEN], SignatureError> { + let mut m_hash = [0u8; H_LEN]; + X::default().hash_out(message, &mut m_hash); + sign_from_hash::( + sk, &m_hash, rng, + ) +} + +/// [`sign`] given the message's hash `m_hash` instead of the message: draws the salt from `rng` +/// (EMSA-PSS-ENCODE step 4) and hands both to [`sign_from_hash_with_salt`]. +pub fn sign_from_hash< + X: XOF + Default, + const H_LEN: usize, + const S_LEN: usize, + const M_PRIME_LEN: usize, + const DB_LEN: usize, + const L: usize, + const L2: usize, + const L21: usize, + const HALF: usize, + const HALF2: usize, + const HALF21: usize, + const K_LEN: usize, +>( + sk: &RsaPrivateKey, + m_hash: &[u8; H_LEN], + rng: &mut dyn RNG, ) -> Result<[u8; K_LEN], SignatureError> { let mut salt = [0u8; S_LEN]; rng.next_bytes_out(&mut salt).map_err(SignatureError::RNGError)?; - sign_with_salt::( - sk, message, &salt, - ) + sign_from_hash_with_salt::< + X, + H_LEN, + S_LEN, + M_PRIME_LEN, + DB_LEN, + L, + L2, + L21, + HALF, + HALF2, + HALF21, + K_LEN, + >(sk, m_hash, &salt) } -/// RSASSA-PSS-VERIFY (RFC 8017 §8.1.2), mirroring [`crate::rsassa_pss::verify`] but built on -/// [`emsa_pss_verify_shake`], which recovers the salt from `EM` itself. +/// RSASSA-PSS-VERIFY (RFC 8017 §8.1.2), mirroring [`crate::rsassa_pss::verify`] but built on the +/// SHAKE-native EMSA-PSS-VERIFY, which recovers the salt from `EM` itself. Hashes `message` and +/// hands `mHash` to [`verify_from_hash`]. pub fn verify< X: XOF + Default, const H_LEN: usize, @@ -83,12 +165,36 @@ pub fn verify< pk: &RsaPublicKey, message: &[u8], signature: &[u8; K_LEN], +) -> Result<(), SignatureError> { + let mut m_hash = [0u8; H_LEN]; + X::default().hash_out(message, &mut m_hash); + verify_from_hash::( + pk, &m_hash, signature, + ) +} + +/// [`verify`] given the message's hash `m_hash` instead of the message -- the counterpart of +/// [`sign_from_hash`], for a streaming `SignatureVerifier`. +pub fn verify_from_hash< + X: XOF + Default, + const H_LEN: usize, + const S_LEN: usize, + const M_PRIME_LEN: usize, + const DB_LEN: usize, + const L: usize, + const L2: usize, + const L21: usize, + const K_LEN: usize, +>( + pk: &RsaPublicKey, + m_hash: &[u8; H_LEN], + signature: &[u8; K_LEN], ) -> Result<(), SignatureError> { let s = limbs_from_be_bytes::(signature); let m = rsavp1::(pk, &s)?; let em = be_bytes_from_limbs::(&m); - if emsa_pss_verify_shake::(message, &em) { + if emsa_pss_verify_shake_from_hash::(m_hash, &em) { Ok(()) } else { Err(SignatureError::SignatureVerificationFailed) From a9961640e92ca0d56303d38e2ceea8596b4b0f0a Mon Sep 17 00:00:00 2001 From: David Hook Date: Mon, 21 Sep 2026 09:55:58 +1000 Subject: [PATCH 14/55] rsa: implement bouncycastle_core's Signer/SignatureVerifier and SignaturePrivateKey/SignaturePublicKey for every scheme, hash and modulus size Until now this crate sat outside the workspace's trait -> factory -> CLI layering: every other primitive here implements its core trait, but RSA signatures were free functions only (pkcs1_v1_5_sign_sha256 and siblings) with their own key types, so nothing written against Signer/SignatureVerifier -- the shared conformance suite, the generic ECDSA-style CLI, a caller switching algorithms behind a trait bound -- could use them. Algorithm types. One generic streaming-state struct per scheme, in the scheme's own module -- rsassa_pkcs1_v1_5::RSASSA_PKCS1_v1_5, rsassa_pss::RSASSA_PSS, rsassa_pss_shake::RSASSA_PSS_SHAKE (spec spelling, per QUALITY_AND_STYLE's rule for identifiers a specification names) -- over the same const-generic width list the existing free functions take plus the key encoding lengths SK_LEN/PK_LEN the key traits are indexed by. Each size module fixes the widths in aliases: rsa_2048::RSASSA_PKCS1_v1_5_SHA256, RSASSA_PSS_SHA384, RSASSA_PSS_SHAKE128, and so on, so a caller never spells out the list. The state holds the hash being streamed plus Option/Option, exactly one Some, the same one-type-both-roles shape as bouncycastle_ecdsa::ECDSAP256 (and the same GenericError when the wrong role's _final is called). One generic impl per scheme is one place for cargo mutants to look, instead of ~40 hand-written per-size copies. Both shapes go through the *_from_hash functions the previous commit introduced, so the trait path and the free functions are one encoding path; the tests pin that they agree byte for byte (PKCS#1 v1.5) or cross-verify (PSS). Semantics. ctx is accepted and ignored (RFC 8017 has no context input), as ECDSA does. Signer::sign for PSS has no RNG parameter and the trait's own docs define it as sourcing randomness from the library's default OS-backed RNG, so sign_final draws the salt from a fresh DefaultRNG; the free functions pss_sign_*(rng)/pss_sign_*_with_salt remain the way to supply an RNG or a fixed salt, the same split as ECDSA's Signer::sign versus its inherent sign_randomized. SignatureVerifier::verify takes a &[u8], so RFC 8017 SS8.1.2/SS8.2.2 step 1 ("If the length of the signature S is not k octets, output 'invalid signature'") becomes a runtime check here -- the free functions' [u8; K_LEN] parameter made it a type error -- and step 2.b's RSAVP1 "signature representative out of range" is folded into SignatureVerificationFailed on the trait path (the RFC's single "invalid signature" answer, which core-test-framework's bit-flip pass requires), while the free functions keep RSAVP1's own DecodingError for vector-driven callers, as their docs already explain. Keys. RsaPrivateKey/RsaPublicKey implement SignaturePrivateKey/SignaturePublicKey per concrete size (stable Rust cannot derive 8 * L + 4 from L), in each size module at that size's new SK_LEN/PK_LEN/SIG_LEN constants, using the existing raw `p || q || dP || dQ || qInv` / `n || e` layouts. The generic inherent encode/from_bytes methods that carried those layouts become crate-private encode_raw/from_bytes_raw: their only stated purpose was the CLI's key files, which the trait impls now serve, and left public they would shadow the trait methods on the concrete key types (`pk.encode()` would resolve to the inherent one and fail to infer N_BYTES). RsaPublicKey gains the Display impl the trait requires (n as one big-endian hex string). Verification-only sizes. RSA-1024/1536's aliases implement SignatureVerifier only: Signer is implemented under the bound `RsaPrivateKey: SignaturePrivateKey`, and no size module declares that for RsaPrivateKey<16, 8>/<24, 12>, so the compiler enforces the crate's `# Scope`; a compile_fail doctest in rsa_1024.rs pins it. Their aliases still name the signing-side widths (HALF = 8, SK_LEN = 320) the generic type needs, documented as inert. CLI. parse_sk/parse_pk in cli/src/rsa_cmd.rs use the trait from_bytes now that the inherent methods are gone (a wrong-length key file is one of its DecodingErrors); the rest of the RSA CLI is unchanged in this commit. Tests. core-test-framework's test_signature conformance suite for every pairing at RSA-2048 (with the exhaustive bit-flip pass, once per generic type: PKCS1-v1_5/SHA-256, PSS/SHA-256, PSS-SHAKE128) and RSA-3072, and for the SHA-256 pairings at 4096/8192 with round trips plus free-function cross-verification for the rest (an RSA-8192 private-key operation is slow enough in a debug build that a dozen per pairing add up; only the width constants differ from the fully-suited sizes); test_keys at every signing size; the trait path against BC Java's RSA-8192 signatures; Wycheproof's rsa_signature_2048_sha256 file re-run through SignatureVerifier::verify so its wrong-length vectors reach the step 1 check instead of the test's own try_into; the out-of-range representative case; wrong-role _final; key layout, Display and wrong-length decoding in keys_tests.rs; and, for 1024/1536, the trait verifier against the genuine sig-gen signatures. The crate docs gain a Usage Example through the traits. ./dev_scripts/quality_stats.sh ./crypto/rsa: core-code fallibility unchanged (2 unwraps, 20 Err()); docstring lines 766 -> 1013. Co-Authored-By: Claude Fable 5.1 --- cli/src/rsa_cmd.rs | 61 ++-- crypto/rsa/src/keys.rs | 91 ++++-- crypto/rsa/src/lib.rs | 110 +++++-- crypto/rsa/src/rsa_1024.rs | 56 ++++ crypto/rsa/src/rsa_1536.rs | 45 +++ crypto/rsa/src/rsa_2048.rs | 92 +++++- crypto/rsa/src/rsa_3072.rs | 82 ++++- crypto/rsa/src/rsa_4096.rs | 82 ++++- crypto/rsa/src/rsa_8192.rs | 77 ++++- crypto/rsa/src/rsassa_pkcs1_v1_5.rs | 188 ++++++++++- crypto/rsa/src/rsassa_pss.rs | 304 +++++++++++++++++- crypto/rsa/src/rsassa_pss_shake.rs | 274 +++++++++++++++- crypto/rsa/tests/keys_tests.rs | 96 +++++- crypto/rsa/tests/rsa_1024_tests.rs | 69 +++- crypto/rsa/tests/rsa_1536_tests.rs | 69 ++++ ...rsa_2048_pkcs1_v1_5_sha384_sha512_tests.rs | 54 +++- crypto/rsa/tests/rsa_2048_pkcs1_v1_5_tests.rs | 170 +++++++++- .../tests/rsa_2048_pss_sha384_sha512_tests.rs | 57 +++- .../rsa/tests/rsa_2048_pss_shake128_tests.rs | 123 ++++++- crypto/rsa/tests/rsa_2048_pss_tests.rs | 126 +++++++- .../rsa/tests/rsa_3072_pss_shake128_tests.rs | 37 ++- crypto/rsa/tests/rsa_3072_tests.rs | 111 ++++++- .../rsa/tests/rsa_4096_pss_shake256_tests.rs | 23 +- crypto/rsa/tests/rsa_4096_tests.rs | 91 +++++- crypto/rsa/tests/rsa_8192_tests.rs | 90 +++++- 25 files changed, 2463 insertions(+), 115 deletions(-) diff --git a/cli/src/rsa_cmd.rs b/cli/src/rsa_cmd.rs index ebb500c0..bd77f8a5 100644 --- a/cli/src/rsa_cmd.rs +++ b/cli/src/rsa_cmd.rs @@ -11,9 +11,10 @@ //! `bouncycastle_rsa` does not generate keys (see that crate's `keys` module docs), so there is no //! `Keygen` action here, and no `PkFromSk` either -- a private key's CRT components alone do not //! determine the public exponent `e`, so there is nothing to derive a public key from. Private and -//! public key files use `RsaPrivateKey::encode`/`RsaPublicKey::encode`'s raw fixed-width layout -//! (documented on those methods): 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. +//! public key files use the raw fixed-width layout `RsaPrivateKey`/`RsaPublicKey`'s +//! `SignaturePrivateKey`/`SignaturePublicKey` 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. @@ -25,7 +26,7 @@ use crate::helpers::{read_from_file, write_bytes_or_hex}; use bouncycastle::core::errors::SignatureError; -use bouncycastle::core::traits::RNG; +use bouncycastle::core::traits::{RNG, SignaturePrivateKey, SignaturePublicKey}; use bouncycastle::rng::DefaultRNG; use bouncycastle::rsa::keys::{RsaPrivateKey, RsaPublicKey}; use clap::ValueEnum; @@ -98,37 +99,43 @@ type PssSignFn = type VerifyFn = fn(&RsaPublicKey, &[u8], &[u8; SIG_LEN]) -> Result<(), SignatureError>; -/// See [`RsaPrivateKey::from_bytes`] for the expected layout. +/// See [`RsaPrivateKey`]'s `# Encoding` docs for the expected layout; a wrong-length file is one +/// of the `DecodingError`s `SignaturePrivateKey::from_bytes` reports. fn parse_sk( bytes: &[u8], alg_name: &str, -) -> RsaPrivateKey { - let Ok(arr): Result<[u8; SK_LEN], _> = bytes.try_into() else { - eprintln!("Error: {alg_name} private key file must be exactly {SK_LEN} bytes."); - exit(-1); - }; - match RsaPrivateKey::::from_bytes::(&arr) { +) -> RsaPrivateKey +where + RsaPrivateKey: SignaturePrivateKey, +{ + match as SignaturePrivateKey>::from_bytes(bytes) { Ok(sk) => sk, Err(_) => { - eprintln!("Error: couldn't parse the input as a valid {alg_name} private key."); + eprintln!( + "Error: couldn't parse the input as a valid {alg_name} private key (must be \ + exactly {SK_LEN} bytes)." + ); exit(-1); } } } -/// See [`RsaPublicKey::from_bytes`] for the expected layout. +/// See [`RsaPublicKey`]'s `# Encoding` docs for the expected layout; a wrong-length file is one of +/// the `DecodingError`s `SignaturePublicKey::from_bytes` reports. fn parse_pk( bytes: &[u8], alg_name: &str, -) -> RsaPublicKey { - let Ok(arr): Result<[u8; PK_LEN], _> = bytes.try_into() else { - eprintln!("Error: {alg_name} public key file must be exactly {PK_LEN} bytes."); - exit(-1); - }; - match RsaPublicKey::::from_bytes::(&arr) { +) -> RsaPublicKey +where + RsaPublicKey: SignaturePublicKey, +{ + match as SignaturePublicKey>::from_bytes(bytes) { Ok(pk) => pk, Err(_) => { - eprintln!("Error: couldn't parse the input as a valid {alg_name} public key."); + eprintln!( + "Error: couldn't parse the input as a valid {alg_name} public key (must be exactly \ + {PK_LEN} bytes)." + ); exit(-1); } } @@ -141,7 +148,9 @@ fn do_verify, sigfile: &Option, alg_name: &str, -) { +) where + RsaPublicKey: SignaturePublicKey, +{ let pk_bytes = require_file(pkfile, "pkfile"); let pk = parse_pk::(&pk_bytes, alg_name); let sig_bytes = require_file(sigfile, "sigfile"); @@ -178,7 +187,10 @@ fn rsa_pkcs1_cmd< sigfile: &Option, output_hex: bool, alg_name: &str, -) { +) where + RsaPrivateKey: SignaturePrivateKey, + RsaPublicKey: SignaturePublicKey, +{ match action { RSAAction::Sign => { let sk_bytes = require_file(skfile, "skfile"); @@ -217,7 +229,10 @@ fn rsa_pss_cmd< sigfile: &Option, output_hex: bool, alg_name: &str, -) { +) where + RsaPrivateKey: SignaturePrivateKey, + RsaPublicKey: SignaturePublicKey, +{ match action { RSAAction::Sign => { let sk_bytes = require_file(skfile, "skfile"); diff --git a/crypto/rsa/src/keys.rs b/crypto/rsa/src/keys.rs index 08da584d..98951a90 100644 --- a/crypto/rsa/src/keys.rs +++ b/crypto/rsa/src/keys.rs @@ -7,14 +7,32 @@ //! implementation), not from primes generated here. 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. +//! +//! Each concrete modulus size's aliases of these types (`crate::rsa_2048::Rsa2048PrivateKey` and +//! siblings) implement `bouncycastle_core`'s `SignaturePrivateKey`/`SignaturePublicKey` traits, +//! in that size's module, with the byte layouts described on each type below; the generic types +//! here only carry the layout's implementation (`encode_raw`/`from_bytes_raw`, crate-private), +//! since the traits' `SK_LEN`/`PK_LEN` are fixed per size and stable Rust cannot derive them from +//! `L`. use crate::codec::{be_bytes_from_limbs, limbs_from_be_bytes}; use bouncycastle_core::errors::SignatureError; use bouncycastle_ec::montgomery; use bouncycastle_ec::nat; use bouncycastle_utils::secret::Secret; +use core::fmt; +use core::fmt::{Display, Formatter}; /// An RSA public key: RFC 8017 §3.1's `(n, e)`. +/// +/// # Encoding +/// +/// `SignaturePublicKey::encode`/`from_bytes` (implemented per size, e.g. for +/// `crate::rsa_2048::Rsa2048PublicKey`) use the raw layout `n || e`: `n` as `8 * L` big-endian +/// bytes (RFC 8017 §4.1's I2OSP), then `e` as 4 big-endian bytes, `PK_LEN = 8 * L + 4` 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. #[derive(Clone, Debug, PartialEq, Eq)] pub struct RsaPublicKey { n: [u64; L], @@ -50,28 +68,32 @@ impl RsaPublicKey { self.e } - /// Encodes as `n || e`: `n` as `N_BYTES = 8 * L` big-endian bytes (RFC 8017 §4.1's I2OSP), - /// then `e` as 4 big-endian bytes. Not an RFC 8017 or ASN.1 format -- this crate has no DER - /// encoder/decoder -- just a fixed-width raw layout [`Self::from_bytes`] round-trips, for - /// `cli/src/rsa_cmd.rs` to read and write public keys as files. - pub fn encode(&self) -> [u8; PK_LEN] { - debug_assert_eq!(N_BYTES, 8 * L, "RsaPublicKey::encode needs N_BYTES == 8 * L"); - debug_assert_eq!(PK_LEN, N_BYTES + 4, "RsaPublicKey::encode needs PK_LEN == N_BYTES + 4"); + /// The `# Encoding` layout (see the type's docs), `n || e`, with `N_BYTES = 8 * L` and + /// `PK_LEN = N_BYTES + 4` supplied by the per-size `SignaturePublicKey` impl that wraps this. + pub(crate) fn encode_raw(&self) -> [u8; PK_LEN] { + debug_assert_eq!(N_BYTES, 8 * L, "RsaPublicKey::encode_raw needs N_BYTES == 8 * L"); + debug_assert_eq!( + PK_LEN, + N_BYTES + 4, + "RsaPublicKey::encode_raw needs PK_LEN == N_BYTES + 4" + ); let mut out = [0u8; PK_LEN]; out[..N_BYTES].copy_from_slice(&be_bytes_from_limbs::(&self.n)); out[N_BYTES..].copy_from_slice(&self.e.to_be_bytes()); out } - /// Decodes [`Self::encode`]'s layout, validated the same way [`Self::new`] validates `(n, e)`. - pub fn from_bytes( + /// Decodes [`Self::encode_raw`]'s layout, validated the same way [`Self::new`] validates + /// `(n, e)`. Takes the exact-length array; the per-size `SignaturePublicKey::from_bytes` that + /// wraps this is where a wrong-length slice is rejected. + pub(crate) fn from_bytes_raw( bytes: &[u8; PK_LEN], ) -> Result { - debug_assert_eq!(N_BYTES, 8 * L, "RsaPublicKey::from_bytes needs N_BYTES == 8 * L"); + debug_assert_eq!(N_BYTES, 8 * L, "RsaPublicKey::from_bytes_raw needs N_BYTES == 8 * L"); debug_assert_eq!( PK_LEN, N_BYTES + 4, - "RsaPublicKey::from_bytes needs PK_LEN == N_BYTES + 4" + "RsaPublicKey::from_bytes_raw needs PK_LEN == N_BYTES + 4" ); let n_bytes: [u8; N_BYTES] = bytes[..N_BYTES].try_into().expect("N_BYTES-byte slice"); let n = limbs_from_be_bytes::(&n_bytes); @@ -80,6 +102,19 @@ impl RsaPublicKey { } } +/// `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 +/// `SignaturePublicKey`'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<{L}> {{ n: ")?; + for limb in self.n.iter().rev() { + write!(f, "{limb:016x}")?; + } + write!(f, ", e: {:x} }}", self.e) + } +} + /// An RSA private key in RFC 8017 §3.2's CRT ("second representation") form: `p`, `q`, `dP`, /// `dQ`, `qInv`. `L` (the modulus's limb count) must be exactly `2 * HALF`; like /// `bouncycastle_ec::montgomery`'s `L2 = 2 * L`, that relationship is enforced at construction @@ -95,6 +130,15 @@ impl RsaPublicKey { /// 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 +/// +/// `SignaturePrivateKey::encode`/`from_bytes` (implemented per size, e.g. for +/// `crate::rsa_2048::Rsa2048PrivateKey`) use the raw layout `p || q || dP || dQ || qInv`, each +/// `8 * HALF` big-endian bytes, `SK_LEN = 40 * HALF` 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 RsaPrivateKey { p: Secret<[u64; HALF]>, @@ -192,20 +236,19 @@ impl RsaPrivateKey { &self.q_inv } - /// Encodes as `p || q || dP || dQ || qInv`, each `HALF_BYTES = 8 * HALF` big-endian bytes. Not - /// an RFC 8017 or ASN.1 format -- see [`RsaPublicKey::encode`]'s docs for why -- just a - /// fixed-width raw layout [`Self::from_bytes`] round-trips, for `cli/src/rsa_cmd.rs` to read - /// and write private keys as files. - pub fn encode(&self) -> [u8; SK_LEN] { + /// The `# Encoding` layout (see the type's docs), `p || q || dP || dQ || qInv`, with + /// `HALF_BYTES = 8 * HALF` and `SK_LEN = 5 * HALF_BYTES` supplied by the per-size + /// `SignaturePrivateKey` impl that wraps this. + pub(crate) fn encode_raw(&self) -> [u8; SK_LEN] { debug_assert_eq!( HALF_BYTES, 8 * HALF, - "RsaPrivateKey::encode needs HALF_BYTES == 8 * HALF" + "RsaPrivateKey::encode_raw needs HALF_BYTES == 8 * HALF" ); debug_assert_eq!( SK_LEN, 5 * HALF_BYTES, - "RsaPrivateKey::encode needs SK_LEN == 5 * HALF_BYTES" + "RsaPrivateKey::encode_raw needs SK_LEN == 5 * HALF_BYTES" ); let mut out = [0u8; SK_LEN]; out[..HALF_BYTES].copy_from_slice(&be_bytes_from_limbs::(&self.p)); @@ -220,20 +263,22 @@ impl RsaPrivateKey { out } - /// Decodes [`Self::encode`]'s layout, validated the same way - /// [`Self::from_crt_components`] validates its five components. - pub fn from_bytes( + /// Decodes [`Self::encode_raw`]'s layout, validated the same way + /// [`Self::from_crt_components`] validates its five components. Takes the exact-length array; + /// the per-size `SignaturePrivateKey::from_bytes` that wraps this is where a wrong-length + /// slice is rejected. + pub(crate) fn from_bytes_raw( bytes: &[u8; SK_LEN], ) -> Result { debug_assert_eq!( HALF_BYTES, 8 * HALF, - "RsaPrivateKey::from_bytes needs HALF_BYTES == 8 * HALF" + "RsaPrivateKey::from_bytes_raw needs HALF_BYTES == 8 * HALF" ); debug_assert_eq!( SK_LEN, 5 * HALF_BYTES, - "RsaPrivateKey::from_bytes needs SK_LEN == 5 * HALF_BYTES" + "RsaPrivateKey::from_bytes_raw needs SK_LEN == 5 * HALF_BYTES" ); let p_bytes: [u8; HALF_BYTES] = bytes[..HALF_BYTES].try_into().expect("HALF_BYTES bytes"); let q_bytes: [u8; HALF_BYTES] = diff --git a/crypto/rsa/src/lib.rs b/crypto/rsa/src/lib.rs index 2ed78989..3a1e30ae 100644 --- a/crypto/rsa/src/lib.rs +++ b/crypto/rsa/src/lib.rs @@ -10,12 +10,72 @@ //! Signature schemes only -- no RSAES-OAEP or RSAES-PKCS1-v1_5 encryption. Modulus sizes 2048 //! through 8192 bits ([`rsa_2048`], [`rsa_3072`], [`rsa_4096`], [`rsa_8192`]) support both signing //! and verification; 1024- and 1536-bit moduli ([`rsa_1024`], [`rsa_1536`]) support verification -//! only, enforced by the absence of a private-key/signer type for those sizes rather than a -//! runtime check. +//! only, enforced by the absence of a private-key type (and so of any `Signer` impl) for those +//! sizes rather than a runtime check. +//! +//! Every (scheme, hash, modulus size) pairing is available two ways over one implementation: +//! as a pair of free functions taking a whole message (`pkcs1_v1_5_sign_sha256`/`..._verify_...` +//! in each size module), and as a type implementing [`bouncycastle_core`]'s +//! [`Signer`](bouncycastle_core::traits::Signer)/[`SignatureVerifier`](bouncycastle_core::traits::SignatureVerifier) +//! traits (`RSASSA_PKCS1_v1_5_SHA256` and siblings in each size module), which adds the +//! streaming `_init`/`_update`/`_final` form. The key types implement +//! [`SignaturePrivateKey`](bouncycastle_core::traits::SignaturePrivateKey)/[`SignaturePublicKey`](bouncycastle_core::traits::SignaturePublicKey) +//! per size. //! //! # Usage Examples //! -//! RSA-2048 with SHA-256, the one concrete pairing wired up so far ([`rsa_2048`]): +//! RSA-2048 with SHA-256 through the `bouncycastle_core` signature traits ([`rsa_2048`]), the +//! way code written against those traits (and this workspace's CLI) uses every signature scheme: +//! +//! ``` +//! use bouncycastle_core::traits::{SignaturePrivateKey, SignaturePublicKey, SignatureVerifier, Signer}; +//! use bouncycastle_rsa::rsa_2048::{RSASSA_PKCS1_v1_5_SHA256, RSASSA_PSS_SHA256, Rsa2048PrivateKey, Rsa2048PublicKey}; +//! # // The same genuine RSA-2048 keypair as the next example; see there for its provenance. +//! # const P: [u64; 16] = [0x0ea36cfb3a5b18f1, 0x48a6e65332119129, 0x110ad9e7b48a1c93, 0x569156b90113e2e9, 0xe79813a575cfad9c, 0x69d659d143ec6f17, 0xe81e6bab5ddaa783, 0xbff1c5b80a69f788, 0x978f6c35814f50ee, 0xe6a289ad4cfbf78f, 0x34d5681e5809d415, 0xbb028bda42eeb5d2, 0x41c56e4de086b0d5, 0x58b8d1e24f3b55d0, 0xfb5248247d98cb7d, 0xdc431050f782e894]; +//! # const Q: [u64; 16] = [0x669f140cfbc20f25, 0xb97bb03677207d95, 0xfd4e06f3ed7299d4, 0x160f90536abc9492, 0xf5b131f39098f7bc, 0xae8d72c57088d7ab, 0x89b94fbde542aba9, 0x3d3f9880ec47d5e0, 0x1378a6868af3b7a0, 0x5544070beb057c94, 0x16611debc472fac4, 0xe500ffb79f5b8868, 0x308a5e32196603b2, 0xea5fb19eb4eabc38, 0x122273ae3222b598, 0xbd1a81e7977f9898]; +//! # const D_P: [u64; 16] = [0x209f33f09515d7c1, 0xb4a9b37656917205, 0x276933bb07e4efb9, 0x8c14019808e00414, 0x289f96da220711e5, 0xfbbd2923d31532fe, 0xc06b414e61c0e1e7, 0x4c23c4588488961d, 0x4dc48ae34514759c, 0x9c786961ae3e2c35, 0x497e8d9c650688e0, 0x18bf08472612dbe5, 0x8885fb161870ee12, 0xf21d7c1479d99d47, 0x9121d91952ffd1c7, 0xa94b528b28f29159]; +//! # const D_Q: [u64; 16] = [0xf7597ffb68011d8d, 0x7b3cc538c4bab8c9, 0xa8fa480a81a925af, 0x6d6ede7251a383bf, 0x8a63f788ce3a0f85, 0x0b920502eb478bc9, 0x7e37e755edfe70d9, 0x9cf9948422a16555, 0x0d6d9ea1f2ef71fd, 0xf7efa32ea0cb6e00, 0x0629b114ca7f780f, 0xcf51176359654348, 0x540cdcbd4ad35435, 0x31c02ff1a2bc437c, 0xff2503df78bafed5, 0x3af0e72a933aef09]; +//! # const Q_INV: [u64; 16] = [0x552fe4bfce945f7b, 0x67e50c999c67247b, 0xfb54ef17be3b2853, 0x241f5921b5ad3983, 0x02de5eccd143cf31, 0x74e45f6fcc60f216, 0xafa5428a74f12708, 0x88d42294b6a2759b, 0xe923e1097c0c562f, 0xc968b48a91c38b5b, 0x933e85179c0320b0, 0x7993d0445f758d51, 0x9bfc042ee0924b1b, 0x41f956d90fa8a793, 0xee7a87b6483a66ee, 0x2640fbfbcfefb163]; +//! let sk = Rsa2048PrivateKey::from_crt_components(&P, &Q, &D_P, &D_Q, &Q_INV)?; +//! let pk = Rsa2048PublicKey::new(sk.n(), 0x10001)?; +//! +//! // One-shot. RSA has no context string, so `ctx` is `None` (a `Some` is accepted and ignored). +//! let signature = RSASSA_PKCS1_v1_5_SHA256::sign(&sk, b"the message to sign", None)?; +//! RSASSA_PKCS1_v1_5_SHA256::verify(&pk, b"the message to sign", None, &signature)?; +//! +//! // Streaming: the message arrives in chunks and is hashed as it goes. +//! let mut signer = RSASSA_PKCS1_v1_5_SHA256::sign_init(&sk, None)?; +//! signer.sign_update(b"the message "); +//! signer.sign_update(b"to sign"); +//! let streamed = signer.sign_final()?; +//! assert_eq!(streamed, signature); // PKCS#1 v1.5 is deterministic +//! +//! let mut verifier = RSASSA_PKCS1_v1_5_SHA256::verify_init(&pk, None)?; +//! verifier.verify_update(b"the message to sign"); +//! verifier.verify_final(&streamed)?; +//! +//! // `verify` takes a `&[u8]`: a signature of the wrong length is rejected as invalid +//! // (RFC 8017 §8.2.2 step 1), as is one over a different message. +//! assert!(RSASSA_PKCS1_v1_5_SHA256::verify(&pk, b"the message to sign", None, &signature[1..]).is_err()); +//! assert!(RSASSA_PKCS1_v1_5_SHA256::verify(&pk, b"a different message", None, &signature).is_err()); +//! +//! // RSASSA-PSS through the same traits draws its salt from the library's default RNG. +//! let sig_a = RSASSA_PSS_SHA256::sign(&sk, b"the message to sign", None)?; +//! let sig_b = RSASSA_PSS_SHA256::sign(&sk, b"the message to sign", None)?; +//! assert_ne!(sig_a, sig_b); +//! RSASSA_PSS_SHA256::verify(&pk, b"the message to sign", None, &sig_a)?; +//! RSASSA_PSS_SHA256::verify(&pk, b"the message to sign", None, &sig_b)?; +//! +//! // Keys round-trip through the traits' raw fixed-width encoding (see `keys`'s docs). +//! let pk_again = Rsa2048PublicKey::from_bytes(&pk.encode())?; +//! assert_eq!(pk_again, pk); +//! let sk_again = Rsa2048PrivateKey::from_bytes(&sk.encode())?; +//! assert_eq!(sk_again, sk); +//! # Ok::<(), bouncycastle_core::errors::SignatureError>(()) +//! ``` +//! +//! The same RSA-2048/SHA-256 pairing through the free functions, which take a whole message and +//! (for PSS) an explicit RNG or salt: //! //! ``` //! use bouncycastle_rsa::rsa_2048::{Rsa2048PrivateKey, Rsa2048PublicKey, pkcs1_v1_5_sign_sha256, pkcs1_v1_5_verify_sha256}; @@ -79,7 +139,9 @@ //! 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. +//! own tests for the specifics at each size. Every pairing also implements `bouncycastle_core`'s +//! `Signer`/`SignatureVerifier` traits (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 @@ -99,15 +161,18 @@ //! | RSA-4096 | 516 | 520 | 1280 | 1792 | //! | RSA-8192 | 1028 | 1032 | 2560 | 3584 | //! -//! All values are in bytes. "On disk" is [`keys::RsaPublicKey::encode`]/[`keys::RsaPrivateKey::encode`]'s -//! raw layout (`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_LEN = 8 * L` -//! bytes: 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 `L`, not by which hash or -//! scheme fed into RSASP1/RSAVP1's modular exponentiation. +//! All values are in bytes. "On disk" is the `SignaturePublicKey`/`SignaturePrivateKey` 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_LEN = 8 * L` bytes: 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 `L`, not by which hash or scheme fed into +//! RSASP1/RSAVP1's modular exponentiation. A `Signer`/`SignatureVerifier` streaming state +//! (`RSASSA_*` in each size module) additionally holds a clone of its key for its lifetime -- +//! the "SK size in memory" column, for a signer -- plus the hash state. //! //! # Security Considerations //! @@ -126,12 +191,19 @@ //! malformed CRT components produces a key that computes *something*, silently, rather than //! being rejected -- validating the inputs' number-theoretic properties before construction is //! entirely the caller's responsibility. -//! - **RSASSA-PSS's salt comes from the caller's RNG.** 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 -//! weakens that argument even though it will not directly leak `d`. +//! - **RSASSA-PSS's salt is only as good as its source.** `Signer::sign` draws it from the +//! library's default OS-backed RNG; `sign_randomized` takes the caller's RNG and +//! `set_signer_salt` 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; `Signer`/`SignatureVerifier`'s `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`) diff --git a/crypto/rsa/src/rsa_1024.rs b/crypto/rsa/src/rsa_1024.rs index e1545e80..354b28e2 100644 --- a/crypto/rsa/src/rsa_1024.rs +++ b/crypto/rsa/src/rsa_1024.rs @@ -9,15 +9,71 @@ //! pairing against at this size -- both remain mathematically expressible through //! [`crate::rsassa_pkcs1_v1_5`]/[`crate::rsassa_pss`] directly if a caller ever needs them, just //! not exposed here without real vectors behind them. +//! +//! The same verification-only scope holds for the `bouncycastle_core` trait types +//! ([`RSASSA_PKCS1_v1_5_SHA256`], [`RSASSA_PKCS1_v1_5_SHA384`]): they implement +//! `SignatureVerifier` but not `Signer`, because `Signer` is only implemented where the private +//! key type implements `SignaturePrivateKey`, and `RsaPrivateKey<16, 8>` does not (no size module +//! declares it). Enforced by the compiler, as this doctest pins: +//! +//! ```compile_fail +//! use bouncycastle_core::traits::Signer; +//! use bouncycastle_rsa::keys::RsaPrivateKey; +//! use bouncycastle_rsa::rsa_1024::RSASSA_PKCS1_v1_5_SHA256; +//! +//! fn sign_1024(sk: &RsaPrivateKey<16, 8>) { +//! // error: no function or associated item named `sign` -- there is no `Signer` impl. +//! let _ = RSASSA_PKCS1_v1_5_SHA256::sign(sk, b"", None); +//! } +//! ``` use crate::keys::RsaPublicKey; use crate::rsassa_pkcs1_v1_5; +use crate::rsassa_pkcs1_v1_5::RSASSA_PKCS1_v1_5; use bouncycastle_core::errors::SignatureError; +use bouncycastle_core::traits::SignaturePublicKey; use bouncycastle_sha2::{SHA256, SHA384}; /// An RSA-1024 public key. pub type Rsa1024PublicKey = RsaPublicKey<16>; +/// Encoded length of an [`Rsa1024PublicKey`] under [`SignaturePublicKey`]: 128 + 4 bytes (see +/// [`RsaPublicKey`]'s `# Encoding`). +pub const PK_LEN: usize = 132; +/// Signature length: `k`, the modulus length in octets (RFC 8017 §8.2.1 step 2.c). +pub const SIG_LEN: usize = 128; + +impl SignaturePublicKey for Rsa1024PublicKey { + fn encode(&self) -> [u8; PK_LEN] { + self.encode_raw::<128, PK_LEN>() + } + + fn encode_out(&self, out: &mut [u8; PK_LEN]) -> usize { + *out = self.encode_raw::<128, PK_LEN>(); + PK_LEN + } + + fn from_bytes(bytes: &[u8]) -> Result { + let bytes: &[u8; PK_LEN] = bytes + .try_into() + .map_err(|_| SignatureError::DecodingError("RSA-1024 public key must be 132 bytes"))?; + Self::from_bytes_raw::<128, PK_LEN>(bytes) + } +} + +/// RSASSA-PKCS1-v1_5/SHA-256 over RSA-1024 as a `SignatureVerifier` only (see the module docs): +/// [`RSASSA_PKCS1_v1_5`] at the widths [`pkcs1_v1_5_verify_sha256`] passes. The signing-side +/// widths the generic type also needs (`HALF = 8`, `HALF2 = 16`, `HALF21 = 17`, `SK_LEN = 320`) +/// are what an RSA-1024 CRT key would have if one existed; they name the type but nothing uses +/// them, since the `Signer` impl they would feed does not exist for `RsaPrivateKey<16, 8>`. +#[allow(non_camel_case_types)] +pub type RSASSA_PKCS1_v1_5_SHA256 = + RSASSA_PKCS1_v1_5; +/// RSASSA-PKCS1-v1_5/SHA-384 over RSA-1024, verify-only; see [`RSASSA_PKCS1_v1_5_SHA256`]. +#[allow(non_camel_case_types)] +pub type RSASSA_PKCS1_v1_5_SHA384 = + RSASSA_PKCS1_v1_5; + /// RSASSA-PKCS1-v1_5 (RFC 8017 §8.2) verification against a SHA-256 digest. See /// [`rsassa_pkcs1_v1_5::verify`] for what each error means. pub fn pkcs1_v1_5_verify_sha256( diff --git a/crypto/rsa/src/rsa_1536.rs b/crypto/rsa/src/rsa_1536.rs index 805d60f4..6f0c7be8 100644 --- a/crypto/rsa/src/rsa_1536.rs +++ b/crypto/rsa/src/rsa_1536.rs @@ -6,14 +6,59 @@ //! would PSS be paired with a modulus this small in practice -- it postdates PKCS#1 v1.5 and //! became common alongside longer keys), so there is nothing to validate a PSS pairing against at //! this size. +//! +//! The `SignatureVerifier` types ([`RSASSA_PKCS1_v1_5_SHA256`] and siblings) are verify-only for +//! the same reason and in the same way as [`crate::rsa_1024`]'s -- see that module's docs. + use crate::keys::RsaPublicKey; use crate::rsassa_pkcs1_v1_5; +use crate::rsassa_pkcs1_v1_5::RSASSA_PKCS1_v1_5; use bouncycastle_core::errors::SignatureError; +use bouncycastle_core::traits::SignaturePublicKey; use bouncycastle_sha2::{SHA256, SHA384, SHA512}; /// An RSA-1536 public key. pub type Rsa1536PublicKey = RsaPublicKey<24>; +/// Encoded length of an [`Rsa1536PublicKey`] under [`SignaturePublicKey`]: 192 + 4 bytes (see +/// [`RsaPublicKey`]'s `# Encoding`). +pub const PK_LEN: usize = 196; +/// Signature length: `k`, the modulus length in octets (RFC 8017 §8.2.1 step 2.c). +pub const SIG_LEN: usize = 192; + +impl SignaturePublicKey for Rsa1536PublicKey { + fn encode(&self) -> [u8; PK_LEN] { + self.encode_raw::<192, PK_LEN>() + } + + fn encode_out(&self, out: &mut [u8; PK_LEN]) -> usize { + *out = self.encode_raw::<192, PK_LEN>(); + PK_LEN + } + + fn from_bytes(bytes: &[u8]) -> Result { + let bytes: &[u8; PK_LEN] = bytes + .try_into() + .map_err(|_| SignatureError::DecodingError("RSA-1536 public key must be 196 bytes"))?; + Self::from_bytes_raw::<192, PK_LEN>(bytes) + } +} + +/// RSASSA-PKCS1-v1_5/SHA-256 over RSA-1536 as a `SignatureVerifier` only -- see +/// [`crate::rsa_1024::RSASSA_PKCS1_v1_5_SHA256`] for why the signing-side widths (`HALF = 12`, +/// `SK_LEN = 480`) are named but inert. +#[allow(non_camel_case_types)] +pub type RSASSA_PKCS1_v1_5_SHA256 = + RSASSA_PKCS1_v1_5; +/// RSASSA-PKCS1-v1_5/SHA-384 over RSA-1536, verify-only; see [`RSASSA_PKCS1_v1_5_SHA256`]. +#[allow(non_camel_case_types)] +pub type RSASSA_PKCS1_v1_5_SHA384 = + RSASSA_PKCS1_v1_5; +/// RSASSA-PKCS1-v1_5/SHA-512 over RSA-1536, verify-only; see [`RSASSA_PKCS1_v1_5_SHA256`]. +#[allow(non_camel_case_types)] +pub type RSASSA_PKCS1_v1_5_SHA512 = + RSASSA_PKCS1_v1_5; + /// RSASSA-PKCS1-v1_5 (RFC 8017 §8.2) verification against a SHA-256 digest. See /// [`rsassa_pkcs1_v1_5::verify`] for what each error means. pub fn pkcs1_v1_5_verify_sha256( diff --git a/crypto/rsa/src/rsa_2048.rs b/crypto/rsa/src/rsa_2048.rs index dd71409c..0264d7ea 100644 --- a/crypto/rsa/src/rsa_2048.rs +++ b/crypto/rsa/src/rsa_2048.rs @@ -6,13 +6,23 @@ //! own widths. PSS's salt length is fixed to each hash's own output length (`H_LEN`) throughout, //! matching RFC 8017 §9.1 note 4's "typical" choice and Wycheproof's own //! `rsa_pss_2048_sha256_mgf1_32_test.json`/`..._sha384_mgf1_48_test.json`. +//! +//! Each (scheme, hash) pairing is offered two ways over the same code path: a pair of free +//! functions taking a whole message (`pkcs1_v1_5_sign_sha256`/`pkcs1_v1_5_verify_sha256`, ...), +//! and a type implementing `bouncycastle_core`'s `Signer`/`SignatureVerifier` traits +//! ([`RSASSA_PKCS1_v1_5_SHA256`], ...) for streaming use and for code written against those +//! traits. The key types implement `SignaturePrivateKey`/`SignaturePublicKey` here, at this +//! size's [`SK_LEN`]/[`PK_LEN`]. use crate::keys::{RsaPrivateKey, RsaPublicKey}; use crate::rsassa_pkcs1_v1_5; +use crate::rsassa_pkcs1_v1_5::RSASSA_PKCS1_v1_5; use crate::rsassa_pss; +use crate::rsassa_pss::RSASSA_PSS; use crate::rsassa_pss_shake; +use crate::rsassa_pss_shake::RSASSA_PSS_SHAKE; use bouncycastle_core::errors::SignatureError; -use bouncycastle_core::traits::RNG; +use bouncycastle_core::traits::{RNG, SignaturePrivateKey, SignaturePublicKey}; use bouncycastle_sha2::{SHA256, SHA384, SHA512}; use bouncycastle_sha3::SHAKE128; @@ -21,6 +31,86 @@ pub type Rsa2048PrivateKey = RsaPrivateKey<32, 16>; /// An RSA-2048 public key. pub type Rsa2048PublicKey = RsaPublicKey<32>; +/// Encoded length of an [`Rsa2048PrivateKey`] under [`SignaturePrivateKey`]: `p || q || dP || dQ +/// || qInv`, five 128-byte values (see [`RsaPrivateKey`]'s `# Encoding`). +pub const SK_LEN: usize = 640; +/// Encoded length of an [`Rsa2048PublicKey`] under [`SignaturePublicKey`]: `n || e`, 256 + 4 +/// bytes (see [`RsaPublicKey`]'s `# Encoding`). +pub const PK_LEN: usize = 260; +/// Signature length: `k`, the modulus length in octets (RFC 8017 §8.1.1/§8.2.1 step 2.c). +pub const SIG_LEN: usize = 256; + +impl SignaturePrivateKey for Rsa2048PrivateKey { + fn encode(&self) -> [u8; SK_LEN] { + self.encode_raw::<128, SK_LEN>() + } + + fn encode_out(&self, out: &mut [u8; SK_LEN]) -> usize { + *out = self.encode_raw::<128, SK_LEN>(); + SK_LEN + } + + fn from_bytes(bytes: &[u8]) -> Result { + let bytes: &[u8; SK_LEN] = bytes + .try_into() + .map_err(|_| SignatureError::DecodingError("RSA-2048 private key must be 640 bytes"))?; + Self::from_bytes_raw::<128, SK_LEN>(bytes) + } +} + +impl SignaturePublicKey for Rsa2048PublicKey { + fn encode(&self) -> [u8; PK_LEN] { + self.encode_raw::<256, PK_LEN>() + } + + fn encode_out(&self, out: &mut [u8; PK_LEN]) -> usize { + *out = self.encode_raw::<256, PK_LEN>(); + PK_LEN + } + + fn from_bytes(bytes: &[u8]) -> Result { + let bytes: &[u8; PK_LEN] = bytes + .try_into() + .map_err(|_| SignatureError::DecodingError("RSA-2048 public key must be 260 bytes"))?; + Self::from_bytes_raw::<256, PK_LEN>(bytes) + } +} + +/// RSASSA-PKCS1-v1_5/SHA-256 over RSA-2048 as a `Signer`/`SignatureVerifier`: [`RSASSA_PKCS1_v1_5`] +/// at the widths [`pkcs1_v1_5_sign_sha256`] passes. Deterministic, so `Signer::sign` reproduces +/// that function's output byte for byte. +#[allow(non_camel_case_types)] +pub type RSASSA_PKCS1_v1_5_SHA256 = + RSASSA_PKCS1_v1_5; +/// RSASSA-PKCS1-v1_5/SHA-384 over RSA-2048; see [`RSASSA_PKCS1_v1_5_SHA256`]. +#[allow(non_camel_case_types)] +pub type RSASSA_PKCS1_v1_5_SHA384 = + RSASSA_PKCS1_v1_5; +/// RSASSA-PKCS1-v1_5/SHA-512 over RSA-2048; see [`RSASSA_PKCS1_v1_5_SHA256`]. +#[allow(non_camel_case_types)] +pub type RSASSA_PKCS1_v1_5_SHA512 = + RSASSA_PKCS1_v1_5; + +/// RSASSA-PSS/SHA-256 (MGF1-SHA-256, 32-byte salt) over RSA-2048 as a `Signer`/`SignatureVerifier`: +/// [`RSASSA_PSS`] at the widths [`pss_sign_sha256`] passes, drawing its salt from the library's +/// default RNG (see that type's docs). +#[allow(non_camel_case_types)] +pub type RSASSA_PSS_SHA256 = + RSASSA_PSS; +/// RSASSA-PSS/SHA-384 (48-byte salt) over RSA-2048; see [`RSASSA_PSS_SHA256`]. +#[allow(non_camel_case_types)] +pub type RSASSA_PSS_SHA384 = + RSASSA_PSS; +/// RSASSA-PSS/SHA-512 (64-byte salt) over RSA-2048; see [`RSASSA_PSS_SHA256`]. +#[allow(non_camel_case_types)] +pub type RSASSA_PSS_SHA512 = + RSASSA_PSS; +/// RSASSA-PSS-SHAKE128 (RFC 8702 §3.2.1) over RSA-2048 as a `Signer`/`SignatureVerifier`: +/// [`RSASSA_PSS_SHAKE`] at the widths [`pss_shake128_sign`] passes. +#[allow(non_camel_case_types)] +pub type RSASSA_PSS_SHAKE128 = + RSASSA_PSS_SHAKE; + /// RSASSA-PKCS1-v1_5 (RFC 8017 §8.2) signing, `s = m^d mod n` over an EMSA-PKCS1-v1_5/SHA-256 /// encoded message. See [`rsassa_pkcs1_v1_5::sign`] for what each error means. pub fn pkcs1_v1_5_sign_sha256( diff --git a/crypto/rsa/src/rsa_3072.rs b/crypto/rsa/src/rsa_3072.rs index 40ca76d6..04b3db14 100644 --- a/crypto/rsa/src/rsa_3072.rs +++ b/crypto/rsa/src/rsa_3072.rs @@ -3,10 +3,13 @@ use crate::keys::{RsaPrivateKey, RsaPublicKey}; use crate::rsassa_pkcs1_v1_5; +use crate::rsassa_pkcs1_v1_5::RSASSA_PKCS1_v1_5; use crate::rsassa_pss; +use crate::rsassa_pss::RSASSA_PSS; use crate::rsassa_pss_shake; +use crate::rsassa_pss_shake::RSASSA_PSS_SHAKE; use bouncycastle_core::errors::SignatureError; -use bouncycastle_core::traits::RNG; +use bouncycastle_core::traits::{RNG, SignaturePrivateKey, SignaturePublicKey}; use bouncycastle_sha2::{SHA256, SHA384, SHA512}; use bouncycastle_sha3::SHAKE128; @@ -15,6 +18,83 @@ pub type Rsa3072PrivateKey = RsaPrivateKey<48, 24>; /// An RSA-3072 public key. pub type Rsa3072PublicKey = RsaPublicKey<48>; +/// Encoded length of an [`Rsa3072PrivateKey`] under [`SignaturePrivateKey`]: five 192-byte +/// values (see [`RsaPrivateKey`]'s `# Encoding`). +pub const SK_LEN: usize = 960; +/// Encoded length of an [`Rsa3072PublicKey`] under [`SignaturePublicKey`]: 384 + 4 bytes (see +/// [`RsaPublicKey`]'s `# Encoding`). +pub const PK_LEN: usize = 388; +/// Signature length: `k`, the modulus length in octets (RFC 8017 §8.1.1/§8.2.1 step 2.c). +pub const SIG_LEN: usize = 384; + +impl SignaturePrivateKey for Rsa3072PrivateKey { + fn encode(&self) -> [u8; SK_LEN] { + self.encode_raw::<192, SK_LEN>() + } + + fn encode_out(&self, out: &mut [u8; SK_LEN]) -> usize { + *out = self.encode_raw::<192, SK_LEN>(); + SK_LEN + } + + fn from_bytes(bytes: &[u8]) -> Result { + let bytes: &[u8; SK_LEN] = bytes + .try_into() + .map_err(|_| SignatureError::DecodingError("RSA-3072 private key must be 960 bytes"))?; + Self::from_bytes_raw::<192, SK_LEN>(bytes) + } +} + +impl SignaturePublicKey for Rsa3072PublicKey { + fn encode(&self) -> [u8; PK_LEN] { + self.encode_raw::<384, PK_LEN>() + } + + fn encode_out(&self, out: &mut [u8; PK_LEN]) -> usize { + *out = self.encode_raw::<384, PK_LEN>(); + PK_LEN + } + + fn from_bytes(bytes: &[u8]) -> Result { + let bytes: &[u8; PK_LEN] = bytes + .try_into() + .map_err(|_| SignatureError::DecodingError("RSA-3072 public key must be 388 bytes"))?; + Self::from_bytes_raw::<384, PK_LEN>(bytes) + } +} + +/// RSASSA-PKCS1-v1_5/SHA-256 over RSA-3072 as a `Signer`/`SignatureVerifier`; see +/// [`crate::rsa_2048::RSASSA_PKCS1_v1_5_SHA256`] for the pattern. +#[allow(non_camel_case_types)] +pub type RSASSA_PKCS1_v1_5_SHA256 = + RSASSA_PKCS1_v1_5; +/// RSASSA-PKCS1-v1_5/SHA-384 over RSA-3072. +#[allow(non_camel_case_types)] +pub type RSASSA_PKCS1_v1_5_SHA384 = + RSASSA_PKCS1_v1_5; +/// RSASSA-PKCS1-v1_5/SHA-512 over RSA-3072. +#[allow(non_camel_case_types)] +pub type RSASSA_PKCS1_v1_5_SHA512 = + RSASSA_PKCS1_v1_5; + +/// RSASSA-PSS/SHA-256 over RSA-3072 as a `Signer`/`SignatureVerifier`; see +/// [`crate::rsa_2048::RSASSA_PSS_SHA256`] for the pattern (including where the salt comes from). +#[allow(non_camel_case_types)] +pub type RSASSA_PSS_SHA256 = + RSASSA_PSS; +/// RSASSA-PSS/SHA-384 over RSA-3072. +#[allow(non_camel_case_types)] +pub type RSASSA_PSS_SHA384 = + RSASSA_PSS; +/// RSASSA-PSS/SHA-512 over RSA-3072. +#[allow(non_camel_case_types)] +pub type RSASSA_PSS_SHA512 = + RSASSA_PSS; +/// RSASSA-PSS-SHAKE128 (RFC 8702 §3.2.1) over RSA-3072 as a `Signer`/`SignatureVerifier`. +#[allow(non_camel_case_types)] +pub type RSASSA_PSS_SHAKE128 = + RSASSA_PSS_SHAKE; + /// RSASSA-PKCS1-v1_5 (RFC 8017 §8.2) signing with SHA-256. See [`rsassa_pkcs1_v1_5::sign`] for /// what each error means. pub fn pkcs1_v1_5_sign_sha256( diff --git a/crypto/rsa/src/rsa_4096.rs b/crypto/rsa/src/rsa_4096.rs index c743c3b4..f6b2bb9b 100644 --- a/crypto/rsa/src/rsa_4096.rs +++ b/crypto/rsa/src/rsa_4096.rs @@ -3,10 +3,13 @@ use crate::keys::{RsaPrivateKey, RsaPublicKey}; use crate::rsassa_pkcs1_v1_5; +use crate::rsassa_pkcs1_v1_5::RSASSA_PKCS1_v1_5; use crate::rsassa_pss; +use crate::rsassa_pss::RSASSA_PSS; use crate::rsassa_pss_shake; +use crate::rsassa_pss_shake::RSASSA_PSS_SHAKE; use bouncycastle_core::errors::SignatureError; -use bouncycastle_core::traits::RNG; +use bouncycastle_core::traits::{RNG, SignaturePrivateKey, SignaturePublicKey}; use bouncycastle_sha2::{SHA256, SHA384, SHA512}; use bouncycastle_sha3::SHAKE256; @@ -15,6 +18,83 @@ pub type Rsa4096PrivateKey = RsaPrivateKey<64, 32>; /// An RSA-4096 public key. pub type Rsa4096PublicKey = RsaPublicKey<64>; +/// Encoded length of an [`Rsa4096PrivateKey`] under [`SignaturePrivateKey`]: five 256-byte +/// values (see [`RsaPrivateKey`]'s `# Encoding`). +pub const SK_LEN: usize = 1280; +/// Encoded length of an [`Rsa4096PublicKey`] under [`SignaturePublicKey`]: 512 + 4 bytes (see +/// [`RsaPublicKey`]'s `# Encoding`). +pub const PK_LEN: usize = 516; +/// Signature length: `k`, the modulus length in octets (RFC 8017 §8.1.1/§8.2.1 step 2.c). +pub const SIG_LEN: usize = 512; + +impl SignaturePrivateKey for Rsa4096PrivateKey { + fn encode(&self) -> [u8; SK_LEN] { + self.encode_raw::<256, SK_LEN>() + } + + fn encode_out(&self, out: &mut [u8; SK_LEN]) -> usize { + *out = self.encode_raw::<256, SK_LEN>(); + SK_LEN + } + + fn from_bytes(bytes: &[u8]) -> Result { + let bytes: &[u8; SK_LEN] = bytes.try_into().map_err(|_| { + SignatureError::DecodingError("RSA-4096 private key must be 1280 bytes") + })?; + Self::from_bytes_raw::<256, SK_LEN>(bytes) + } +} + +impl SignaturePublicKey for Rsa4096PublicKey { + fn encode(&self) -> [u8; PK_LEN] { + self.encode_raw::<512, PK_LEN>() + } + + fn encode_out(&self, out: &mut [u8; PK_LEN]) -> usize { + *out = self.encode_raw::<512, PK_LEN>(); + PK_LEN + } + + fn from_bytes(bytes: &[u8]) -> Result { + let bytes: &[u8; PK_LEN] = bytes + .try_into() + .map_err(|_| SignatureError::DecodingError("RSA-4096 public key must be 516 bytes"))?; + Self::from_bytes_raw::<512, PK_LEN>(bytes) + } +} + +/// RSASSA-PKCS1-v1_5/SHA-256 over RSA-4096 as a `Signer`/`SignatureVerifier`; see +/// [`crate::rsa_2048::RSASSA_PKCS1_v1_5_SHA256`] for the pattern. +#[allow(non_camel_case_types)] +pub type RSASSA_PKCS1_v1_5_SHA256 = + RSASSA_PKCS1_v1_5; +/// RSASSA-PKCS1-v1_5/SHA-384 over RSA-4096. +#[allow(non_camel_case_types)] +pub type RSASSA_PKCS1_v1_5_SHA384 = + RSASSA_PKCS1_v1_5; +/// RSASSA-PKCS1-v1_5/SHA-512 over RSA-4096. +#[allow(non_camel_case_types)] +pub type RSASSA_PKCS1_v1_5_SHA512 = + RSASSA_PKCS1_v1_5; + +/// RSASSA-PSS/SHA-256 over RSA-4096 as a `Signer`/`SignatureVerifier`; see +/// [`crate::rsa_2048::RSASSA_PSS_SHA256`] for the pattern (including where the salt comes from). +#[allow(non_camel_case_types)] +pub type RSASSA_PSS_SHA256 = + RSASSA_PSS; +/// RSASSA-PSS/SHA-384 over RSA-4096. +#[allow(non_camel_case_types)] +pub type RSASSA_PSS_SHA384 = + RSASSA_PSS; +/// RSASSA-PSS/SHA-512 over RSA-4096. +#[allow(non_camel_case_types)] +pub type RSASSA_PSS_SHA512 = + RSASSA_PSS; +/// RSASSA-PSS-SHAKE256 (RFC 8702 §3.2.1) over RSA-4096 as a `Signer`/`SignatureVerifier`. +#[allow(non_camel_case_types)] +pub type RSASSA_PSS_SHAKE256 = + RSASSA_PSS_SHAKE; + /// RSASSA-PKCS1-v1_5 (RFC 8017 §8.2) signing with SHA-256. See [`rsassa_pkcs1_v1_5::sign`] for /// what each error means. pub fn pkcs1_v1_5_sign_sha256( diff --git a/crypto/rsa/src/rsa_8192.rs b/crypto/rsa/src/rsa_8192.rs index b4914b41..ab0daeb1 100644 --- a/crypto/rsa/src/rsa_8192.rs +++ b/crypto/rsa/src/rsa_8192.rs @@ -3,9 +3,11 @@ use crate::keys::{RsaPrivateKey, RsaPublicKey}; use crate::rsassa_pkcs1_v1_5; +use crate::rsassa_pkcs1_v1_5::RSASSA_PKCS1_v1_5; use crate::rsassa_pss; +use crate::rsassa_pss::RSASSA_PSS; use bouncycastle_core::errors::SignatureError; -use bouncycastle_core::traits::RNG; +use bouncycastle_core::traits::{RNG, SignaturePrivateKey, SignaturePublicKey}; use bouncycastle_sha2::{SHA256, SHA384, SHA512}; /// An RSA-8192 private key (`p`, `q` each 4096 bits). @@ -13,6 +15,79 @@ pub type Rsa8192PrivateKey = RsaPrivateKey<128, 64>; /// An RSA-8192 public key. pub type Rsa8192PublicKey = RsaPublicKey<128>; +/// Encoded length of an [`Rsa8192PrivateKey`] under [`SignaturePrivateKey`]: five 512-byte +/// values (see [`RsaPrivateKey`]'s `# Encoding`). +pub const SK_LEN: usize = 2560; +/// Encoded length of an [`Rsa8192PublicKey`] under [`SignaturePublicKey`]: 1024 + 4 bytes (see +/// [`RsaPublicKey`]'s `# Encoding`). +pub const PK_LEN: usize = 1028; +/// Signature length: `k`, the modulus length in octets (RFC 8017 §8.1.1/§8.2.1 step 2.c). +pub const SIG_LEN: usize = 1024; + +impl SignaturePrivateKey for Rsa8192PrivateKey { + fn encode(&self) -> [u8; SK_LEN] { + self.encode_raw::<512, SK_LEN>() + } + + fn encode_out(&self, out: &mut [u8; SK_LEN]) -> usize { + *out = self.encode_raw::<512, SK_LEN>(); + SK_LEN + } + + fn from_bytes(bytes: &[u8]) -> Result { + let bytes: &[u8; SK_LEN] = bytes.try_into().map_err(|_| { + SignatureError::DecodingError("RSA-8192 private key must be 2560 bytes") + })?; + Self::from_bytes_raw::<512, SK_LEN>(bytes) + } +} + +impl SignaturePublicKey for Rsa8192PublicKey { + fn encode(&self) -> [u8; PK_LEN] { + self.encode_raw::<1024, PK_LEN>() + } + + fn encode_out(&self, out: &mut [u8; PK_LEN]) -> usize { + *out = self.encode_raw::<1024, PK_LEN>(); + PK_LEN + } + + fn from_bytes(bytes: &[u8]) -> Result { + let bytes: &[u8; PK_LEN] = bytes + .try_into() + .map_err(|_| SignatureError::DecodingError("RSA-8192 public key must be 1028 bytes"))?; + Self::from_bytes_raw::<1024, PK_LEN>(bytes) + } +} + +/// RSASSA-PKCS1-v1_5/SHA-256 over RSA-8192 as a `Signer`/`SignatureVerifier`; see +/// [`crate::rsa_2048::RSASSA_PKCS1_v1_5_SHA256`] for the pattern. +#[allow(non_camel_case_types)] +pub type RSASSA_PKCS1_v1_5_SHA256 = + RSASSA_PKCS1_v1_5; +/// RSASSA-PKCS1-v1_5/SHA-384 over RSA-8192. +#[allow(non_camel_case_types)] +pub type RSASSA_PKCS1_v1_5_SHA384 = + RSASSA_PKCS1_v1_5; +/// RSASSA-PKCS1-v1_5/SHA-512 over RSA-8192. +#[allow(non_camel_case_types)] +pub type RSASSA_PKCS1_v1_5_SHA512 = + RSASSA_PKCS1_v1_5; + +/// RSASSA-PSS/SHA-256 over RSA-8192 as a `Signer`/`SignatureVerifier`; see +/// [`crate::rsa_2048::RSASSA_PSS_SHA256`] for the pattern (including where the salt comes from). +#[allow(non_camel_case_types)] +pub type RSASSA_PSS_SHA256 = + RSASSA_PSS; +/// RSASSA-PSS/SHA-384 over RSA-8192. +#[allow(non_camel_case_types)] +pub type RSASSA_PSS_SHA384 = + RSASSA_PSS; +/// RSASSA-PSS/SHA-512 over RSA-8192. +#[allow(non_camel_case_types)] +pub type RSASSA_PSS_SHA512 = + RSASSA_PSS; + /// RSASSA-PKCS1-v1_5 (RFC 8017 §8.2) signing with SHA-256. See [`rsassa_pkcs1_v1_5::sign`] for /// what each error means. pub fn pkcs1_v1_5_sign_sha256( diff --git a/crypto/rsa/src/rsassa_pkcs1_v1_5.rs b/crypto/rsa/src/rsassa_pkcs1_v1_5.rs index 3012c098..e9783196 100644 --- a/crypto/rsa/src/rsassa_pkcs1_v1_5.rs +++ b/crypto/rsa/src/rsassa_pkcs1_v1_5.rs @@ -4,13 +4,188 @@ //! for each CRT prime, `K_LEN = 8 * L` for the encoded message/signature byte length) and over //! the hash function `H` (`H_LEN`/`T_LEN` sized to it) -- a concrete modulus size wires these to //! literals (e.g. RSA-2048/SHA-256 in [`crate::rsa_2048`]) rather than a caller choosing them. +//! +//! Two shapes of the same operation: the free functions [`sign`]/[`verify`] take a whole message, +//! and [`RSASSA_PKCS1_v1_5`] implements `bouncycastle_core`'s [`Signer`]/[`SignatureVerifier`] +//! traits over the same widths, adding the streaming (`sign_init`/`sign_update`/`sign_final`) +//! form and a `&[u8]`-typed signature on the verify side. Both go through [`sign_from_hash`]/ +//! [`verify_from_hash`], so there is exactly one encoding path to test. use crate::codec::{be_bytes_from_limbs, limbs_from_be_bytes}; use crate::emsa_pkcs1_v1_5::{emsa_pkcs1_v1_5_encode_from_hash, emsa_pkcs1_v1_5_verify_from_hash}; use crate::keys::{RsaPrivateKey, RsaPublicKey}; use crate::rsa_core::{rsasp1, rsavp1}; use bouncycastle_core::errors::SignatureError; -use bouncycastle_core::traits::{AlgorithmOID, Hash, HashAlgParams}; +use bouncycastle_core::traits::{ + AlgorithmOID, Hash, HashAlgParams, SignaturePrivateKey, SignaturePublicKey, SignatureVerifier, + Signer, +}; + +/// Streaming state for RSASSA-PKCS1-v1_5's [`Signer`] and [`SignatureVerifier`] impls, at the +/// widths the const parameters fix (the same list [`sign`] takes, plus the key encoding lengths +/// `SK_LEN`/`PK_LEN` the key traits are indexed by). One type serves both roles, mirroring +/// `bouncycastle_ecdsa::ecdsa_p256::ECDSAP256`: exactly one of `sk`/`pk` is `Some`, chosen by +/// which trait's `_init` constructed this value, and calling the other trait's `_final` on it is +/// reported as [`SignatureError::GenericError`] rather than silently doing the wrong operation. +/// +/// Concrete (hash, modulus size) pairings are type aliases in the per-size modules -- +/// `crate::rsa_2048::RSASSA_PKCS1_v1_5_SHA256` and siblings -- so a caller never spells out the +/// width list. The spec's own spelling `RSASSA-PKCS1-v1_5` is kept (hyphens as underscores), per +/// this repo's naming convention for identifiers a specification names. +/// +/// `ctx` is accepted but ignored by every method: RSASSA-PKCS1-v1_5 (RFC 8017 §8.2) has no +/// context-string input, the same position `bouncycastle_ecdsa` takes for ECDSA. +/// +/// The key is cloned into this state by `sign_init`/`verify_init` (the traits leave no room for a +/// borrow), so a signing state for the largest modulus size holds a copy of its +/// `RsaPrivateKey`'s `Secret` fields for as long as the state lives -- see the crate docs' +/// `# Memory Usage`. +#[allow(non_camel_case_types)] +pub struct RSASSA_PKCS1_v1_5< + H, + const H_LEN: usize, + const T_LEN: usize, + const L: usize, + const L2: usize, + const L21: usize, + const HALF: usize, + const HALF2: usize, + const HALF21: usize, + const K_LEN: usize, + const SK_LEN: usize, + const PK_LEN: usize, +> { + hash: H, + sk: Option>, + pk: Option>, +} + +impl< + H: Hash + HashAlgParams + AlgorithmOID + Default, + const H_LEN: usize, + const T_LEN: usize, + const L: usize, + const L2: usize, + const L21: usize, + const HALF: usize, + const HALF2: usize, + const HALF21: usize, + const K_LEN: usize, + const SK_LEN: usize, + const PK_LEN: usize, +> Signer, SK_LEN, K_LEN> + for RSASSA_PKCS1_v1_5 +where + // Only a private key type this crate has declared signable (a `SignaturePrivateKey` impl in + // its size module) gets a `Signer`: the verify-only sizes, RSA-1024/1536, have none, so this + // impl does not exist for them and there is nothing to call -- compile-time enforcement of the + // crate's `# Scope`, not a runtime check. + RsaPrivateKey: SignaturePrivateKey, +{ + fn sign( + sk: &RsaPrivateKey, + msg: &[u8], + ctx: Option<&[u8]>, + ) -> Result<[u8; K_LEN], SignatureError> { + let mut s = Self::sign_init(sk, ctx)?; + s.sign_update(msg); + s.sign_final() + } + + fn sign_out( + sk: &RsaPrivateKey, + msg: &[u8], + ctx: Option<&[u8]>, + output: &mut [u8; K_LEN], + ) -> Result { + output.fill(0); + *output = Self::sign(sk, msg, ctx)?; + Ok(K_LEN) + } + + fn sign_init(sk: &RsaPrivateKey, _ctx: Option<&[u8]>) -> Result { + // ctx ignored -- see the type's docs. + Ok(Self { hash: H::default(), sk: Some(sk.clone()), pk: None }) + } + + fn sign_update(&mut self, msg_chunk: &[u8]) { + self.hash.do_update(msg_chunk); + } + + fn sign_final(self) -> Result<[u8; K_LEN], SignatureError> { + let sk = self.sk.ok_or(SignatureError::GenericError( + "sign_final called on a verify-initialized RSASSA_PKCS1_v1_5; call verify_final instead", + ))?; + // EMSA-PKCS1-v1_5 step 1, `H = Hash(M)`, completed here over the streamed chunks. + let mut digest = [0u8; H_LEN]; + self.hash.do_final_out(&mut digest); + sign_from_hash::(&sk, &digest) + } + + fn sign_final_out(self, output: &mut [u8; K_LEN]) -> Result { + output.fill(0); + *output = self.sign_final()?; + Ok(K_LEN) + } +} + +impl< + H: Hash + HashAlgParams + AlgorithmOID + Default, + const H_LEN: usize, + const T_LEN: usize, + const L: usize, + const L2: usize, + const L21: usize, + const HALF: usize, + const HALF2: usize, + const HALF21: usize, + const K_LEN: usize, + const SK_LEN: usize, + const PK_LEN: usize, +> SignatureVerifier, PK_LEN, K_LEN> + for RSASSA_PKCS1_v1_5 +where + RsaPublicKey: SignaturePublicKey, +{ + fn verify( + pk: &RsaPublicKey, + msg: &[u8], + ctx: Option<&[u8]>, + sig: &[u8], + ) -> Result<(), SignatureError> { + let mut v = Self::verify_init(pk, ctx)?; + v.verify_update(msg); + v.verify_final(sig) + } + + fn verify_init(pk: &RsaPublicKey, _ctx: Option<&[u8]>) -> Result { + Ok(Self { hash: H::default(), sk: None, pk: Some(pk.clone()) }) + } + + fn verify_update(&mut self, msg_chunk: &[u8]) { + self.hash.do_update(msg_chunk); + } + + fn verify_final(self, sig: &[u8]) -> Result<(), SignatureError> { + let pk = self.pk.ok_or(SignatureError::GenericError( + "verify_final called on a sign-initialized RSASSA_PKCS1_v1_5; call sign_final instead", + ))?; + // RFC 8017 §8.2.2 step 1: "Length checking: If the length of the signature S is not k + // octets, output "invalid signature" and stop." -- the one place in this crate that step + // is a runtime check, since the trait hands over a `&[u8]` rather than the `[u8; K_LEN]` + // the free functions take. + let sig: &[u8; K_LEN] = + sig.try_into().map_err(|_| SignatureError::SignatureVerificationFailed)?; + let mut digest = [0u8; H_LEN]; + self.hash.do_final_out(&mut digest); + // Step 2.b: "If RSAVP1 outputs "signature representative out of range", output "invalid + // signature" and stop." The free function [`verify`] deliberately lets RSAVP1's own error + // through instead (see its docs); the trait's contract is the RFC's -- one "invalid + // signature" answer for every way a signature can fail -- so it is folded in here. + verify_from_hash::(&pk, &digest, sig) + .map_err(|_| SignatureError::SignatureVerificationFailed) + } +} /// RSASSA-PKCS1-V1_5-SIGN (RFC 8017 §8.2.1): `S = I2OSP(RSASP1(K, OS2IP(EM)), k)`, where /// `EM = EMSA-PKCS1-V1_5-ENCODE(M, k)`. Step 1's two errors ("message too long" -- unreachable @@ -66,11 +241,12 @@ pub fn sign_from_hash< } /// RSASSA-PKCS1-V1_5-VERIFY (RFC 8017 §8.2.2): recovers `EM' = I2OSP(RSAVP1((n, e), OS2IP(S)), -/// k)` and checks it against `message` via [`emsa_pkcs1_v1_5_verify`] -- a decode, not RFC 8017's -/// own step 4 (re-encode `message` and compare bytes to `EM'`), because a byte comparison against -/// this crate's own (always-`NULL`-including) encoding would reject an otherwise-valid signature -/// whose `DigestInfo` omits the `AlgorithmIdentifier`'s `NULL` parameters -- a real-world -/// leniency [`emsa_pkcs1_v1_5_verify`]'s docs explain. Step 1's length check (`S` must be exactly +/// k)` and checks it against `message` via [`emsa_pkcs1_v1_5_verify_from_hash`] -- a decode, not +/// RFC 8017's own step 4 (re-encode `message` and compare bytes to `EM'`), because a byte +/// comparison against this crate's own (always-`NULL`-including) encoding would reject an +/// otherwise-valid signature whose `DigestInfo` omits the `AlgorithmIdentifier`'s `NULL` +/// parameters -- a real-world leniency [`emsa_pkcs1_v1_5_verify_from_hash`]'s docs explain. Step +/// 1's length check (`S` must be exactly /// `k` octets) doesn't apply: `signature` is already a fixed `K_LEN`-byte array, not an /// arbitrary-length octet string, so a wrong length is a compile-time type error at the call site /// instead. Step 2's "signature representative out of range" surfaces as [`rsavp1`]'s own `Err`, diff --git a/crypto/rsa/src/rsassa_pss.rs b/crypto/rsa/src/rsassa_pss.rs index 8944da91..c3c19426 100644 --- a/crypto/rsa/src/rsassa_pss.rs +++ b/crypto/rsa/src/rsassa_pss.rs @@ -3,13 +3,315 @@ //! [`crate::rsassa_pkcs1_v1_5`] plus PSS's own `S_LEN` (salt length) and `M_PRIME_LEN` //! (`8 + H_LEN + S_LEN`); a concrete modulus size wires these to literals (RSA-2048/SHA-256 in //! [`crate::rsa_2048`]). +//! +//! As in [`crate::rsassa_pkcs1_v1_5`], the free functions take a whole message (and, for +//! signing, an explicit RNG or salt) while [`RSASSA_PSS`] implements `bouncycastle_core`'s +//! [`Signer`]/[`SignatureVerifier`] traits over the same widths, streaming the message and +//! drawing its salt from the library's default RNG. Both go through the `*_from_hash` functions. use crate::codec::{be_bytes_from_limbs, limbs_from_be_bytes}; use crate::emsa_pss::{emsa_pss_encode_from_hash, emsa_pss_verify_from_hash}; use crate::keys::{RsaPrivateKey, RsaPublicKey}; use crate::rsa_core::{rsasp1, rsavp1}; use bouncycastle_core::errors::SignatureError; -use bouncycastle_core::traits::{Hash, RNG}; +use bouncycastle_core::traits::{ + Hash, RNG, SignaturePrivateKey, SignaturePublicKey, SignatureVerifier, Signer, +}; +use bouncycastle_rng::DefaultRNG; + +/// Streaming state for RSASSA-PSS's [`Signer`] and [`SignatureVerifier`] impls, at the widths the +/// const parameters fix (the list [`sign`] takes, plus the key encoding lengths `SK_LEN`/`PK_LEN` +/// the key traits are indexed by). The same one-type-both-roles shape as +/// [`crate::rsassa_pkcs1_v1_5::RSASSA_PKCS1_v1_5`], whose docs cover the `sk`/`pk` arrangement, +/// the ignored `ctx`, the naming, and the cloned key; concrete pairings are aliases such as +/// `crate::rsa_2048::RSASSA_PSS_SHA256`. +/// +/// [`Signer::sign`] has no RNG parameter, and that trait's docs define it as sourcing any +/// randomness it needs from the library's default OS-backed RNG, so `sign_final` draws the salt +/// (EMSA-PSS-ENCODE step 4) from a fresh [`DefaultRNG`] unless the caller fixed one. Two +/// `Signer::sign` calls over the same key and message therefore produce different, both valid, +/// signatures. Control over that randomness follows the workspace's other signature crates: +/// [`Self::sign_randomized`] takes a caller-supplied RNG (as `bouncycastle_ecdsa`'s and +/// `bouncycastle_sm2`'s `sign_randomized` do), and [`Self::set_signer_salt`] fixes the salt on a +/// streaming state (as `bouncycastle_mldsa`'s `set_signer_rnd` fixes its nonce), which makes the +/// signature deterministic. +#[allow(non_camel_case_types)] +pub struct RSASSA_PSS< + H, + const H_LEN: usize, + const SEED_LEN: usize, + const S_LEN: usize, + const M_PRIME_LEN: usize, + const DB_LEN: usize, + const L: usize, + const L2: usize, + const L21: usize, + const HALF: usize, + const HALF2: usize, + const HALF21: usize, + const K_LEN: usize, + const SK_LEN: usize, + const PK_LEN: usize, +> { + hash: H, + sk: Option>, + pk: Option>, + /// The salt `sign_final` will use, if [`Self::set_signer_salt`] fixed one; `None` means a + /// fresh one from [`DefaultRNG`]. + salt: Option<[u8; S_LEN]>, +} + +impl< + H: Hash + Default, + const H_LEN: usize, + const SEED_LEN: usize, + const S_LEN: usize, + const M_PRIME_LEN: usize, + const DB_LEN: usize, + const L: usize, + const L2: usize, + const L21: usize, + const HALF: usize, + const HALF2: usize, + const HALF21: usize, + const K_LEN: usize, + const SK_LEN: usize, + const PK_LEN: usize, +> + RSASSA_PSS< + H, + H_LEN, + SEED_LEN, + S_LEN, + M_PRIME_LEN, + DB_LEN, + L, + L2, + L21, + HALF, + HALF2, + HALF21, + K_LEN, + SK_LEN, + PK_LEN, + > +where + RsaPrivateKey: SignaturePrivateKey, +{ + /// RSASSA-PSS-SIGN (RFC 8017 §8.1.1) with the salt drawn from the caller's `rng` rather than + /// the library's default -- an additional capability alongside [`Signer::sign`], the same + /// shape as `bouncycastle_ecdsa`'s `ECDSAP256::sign_randomized` and `bouncycastle_sm2`'s + /// `SM2::sign_randomized`. `ctx` is not taken: it is ignored throughout this type. + pub fn sign_randomized( + sk: &RsaPrivateKey, + msg: &[u8], + rng: &mut dyn RNG, + ) -> Result<[u8; K_LEN], SignatureError> { + let mut salt = [0u8; S_LEN]; + rng.next_bytes_out(&mut salt).map_err(SignatureError::RNGError)?; + let mut signer = Self::sign_init(sk, None)?; + signer.set_signer_salt(salt); + signer.sign_update(msg); + signer.sign_final() + } + + /// Fixes the salt [`Signer::sign_final`] will use (EMSA-PSS-ENCODE step 4) instead of drawing + /// one from the default RNG -- the counterpart of `bouncycastle_mldsa`'s `set_signer_rnd`, for + /// a caller with its own randomness source, a device without an RNG, or a test against a known + /// salt. With the salt fixed, signing is deterministic; PSS's security argument assumes a + /// fresh, unpredictable salt per signature (see the crate docs' `# Security Considerations`), + /// so a fixed salt should itself be fresh randomness the caller obtained elsewhere. Has no + /// effect on a verify-initialised state. + pub fn set_signer_salt(&mut self, salt: [u8; S_LEN]) { + self.salt = Some(salt); + } +} + +impl< + H: Hash + Default, + const H_LEN: usize, + const SEED_LEN: usize, + const S_LEN: usize, + const M_PRIME_LEN: usize, + const DB_LEN: usize, + const L: usize, + const L2: usize, + const L21: usize, + const HALF: usize, + const HALF2: usize, + const HALF21: usize, + const K_LEN: usize, + const SK_LEN: usize, + const PK_LEN: usize, +> Signer, SK_LEN, K_LEN> + for RSASSA_PSS< + H, + H_LEN, + SEED_LEN, + S_LEN, + M_PRIME_LEN, + DB_LEN, + L, + L2, + L21, + HALF, + HALF2, + HALF21, + K_LEN, + SK_LEN, + PK_LEN, + > +where + // See `RSASSA_PKCS1_v1_5`'s `Signer` impl: no `SignaturePrivateKey`, no `Signer`. + RsaPrivateKey: SignaturePrivateKey, +{ + fn sign( + sk: &RsaPrivateKey, + msg: &[u8], + ctx: Option<&[u8]>, + ) -> Result<[u8; K_LEN], SignatureError> { + let mut s = Self::sign_init(sk, ctx)?; + s.sign_update(msg); + s.sign_final() + } + + fn sign_out( + sk: &RsaPrivateKey, + msg: &[u8], + ctx: Option<&[u8]>, + output: &mut [u8; K_LEN], + ) -> Result { + output.fill(0); + *output = Self::sign(sk, msg, ctx)?; + Ok(K_LEN) + } + + fn sign_init(sk: &RsaPrivateKey, _ctx: Option<&[u8]>) -> Result { + // ctx ignored -- see the type's docs. + Ok(Self { hash: H::default(), sk: Some(sk.clone()), pk: None, salt: None }) + } + + fn sign_update(&mut self, msg_chunk: &[u8]) { + self.hash.do_update(msg_chunk); + } + + fn sign_final(self) -> Result<[u8; K_LEN], SignatureError> { + let sk = self.sk.ok_or(SignatureError::GenericError( + "sign_final called on a verify-initialized RSASSA_PSS; call verify_final instead", + ))?; + // EMSA-PSS step 2, `mHash = Hash(M)`, completed here over the streamed chunks. + let mut m_hash = [0u8; H_LEN]; + self.hash.do_final_out(&mut m_hash); + // EMSA-PSS-ENCODE step 4's salt: the one `set_signer_salt` fixed, else fresh from the + // library's default RNG (see the type's docs). + let salt = match self.salt { + Some(salt) => salt, + None => { + let mut salt = [0u8; S_LEN]; + DefaultRNG::default() + .next_bytes_out(&mut salt) + .map_err(SignatureError::RNGError)?; + salt + } + }; + sign_from_hash_with_salt::< + H, + H_LEN, + SEED_LEN, + S_LEN, + M_PRIME_LEN, + DB_LEN, + L, + L2, + L21, + HALF, + HALF2, + HALF21, + K_LEN, + >(&sk, &m_hash, &salt) + } + + fn sign_final_out(self, output: &mut [u8; K_LEN]) -> Result { + output.fill(0); + *output = self.sign_final()?; + Ok(K_LEN) + } +} + +impl< + H: Hash + Default, + const H_LEN: usize, + const SEED_LEN: usize, + const S_LEN: usize, + const M_PRIME_LEN: usize, + const DB_LEN: usize, + const L: usize, + const L2: usize, + const L21: usize, + const HALF: usize, + const HALF2: usize, + const HALF21: usize, + const K_LEN: usize, + const SK_LEN: usize, + const PK_LEN: usize, +> SignatureVerifier, PK_LEN, K_LEN> + for RSASSA_PSS< + H, + H_LEN, + SEED_LEN, + S_LEN, + M_PRIME_LEN, + DB_LEN, + L, + L2, + L21, + HALF, + HALF2, + HALF21, + K_LEN, + SK_LEN, + PK_LEN, + > +where + RsaPublicKey: SignaturePublicKey, +{ + fn verify( + pk: &RsaPublicKey, + msg: &[u8], + ctx: Option<&[u8]>, + sig: &[u8], + ) -> Result<(), SignatureError> { + let mut v = Self::verify_init(pk, ctx)?; + v.verify_update(msg); + v.verify_final(sig) + } + + fn verify_init(pk: &RsaPublicKey, _ctx: Option<&[u8]>) -> Result { + Ok(Self { hash: H::default(), sk: None, pk: Some(pk.clone()), salt: None }) + } + + fn verify_update(&mut self, msg_chunk: &[u8]) { + self.hash.do_update(msg_chunk); + } + + fn verify_final(self, sig: &[u8]) -> Result<(), SignatureError> { + let pk = self.pk.ok_or(SignatureError::GenericError( + "verify_final called on a sign-initialized RSASSA_PSS; call sign_final instead", + ))?; + // RFC 8017 §8.1.2 step 1: "Length checking: If the length of the signature S is not k + // octets, output "invalid signature" and stop." (See `RSASSA_PKCS1_v1_5::verify_final`.) + let sig: &[u8; K_LEN] = + sig.try_into().map_err(|_| SignatureError::SignatureVerificationFailed)?; + let mut m_hash = [0u8; H_LEN]; + self.hash.do_final_out(&mut m_hash); + // Step 2.b: RSAVP1's "signature representative out of range" is "invalid signature" here + // (see `RSASSA_PKCS1_v1_5::verify_final`). + verify_from_hash::( + &pk, &m_hash, sig, + ) + .map_err(|_| SignatureError::SignatureVerificationFailed) + } +} /// RSASSA-PSS-SIGN (RFC 8017 §8.1.1) with the salt supplied directly rather than drawn from an /// RNG: EMSA-PSS is randomized only in its choice of salt (§9.1's own note 5), so fixing it makes diff --git a/crypto/rsa/src/rsassa_pss_shake.rs b/crypto/rsa/src/rsassa_pss_shake.rs index 64504e51..d72ecebe 100644 --- a/crypto/rsa/src/rsassa_pss_shake.rs +++ b/crypto/rsa/src/rsassa_pss_shake.rs @@ -2,14 +2,284 @@ //! generation function -- `id-RSASSA-PSS-SHAKE128`/`id-RSASSA-PSS-SHAKE256` (RFC 8702 §3.2.1). //! Otherwise identical to [`crate::rsassa_pss`] (RFC 8017 §8.1): same RSASP1/RSAVP1 orchestration, //! same fresh-salt-per-signature approach, just built on [`crate::emsa_pss_shake`] in place of -//! [`crate::emsa_pss`]. +//! [`crate::emsa_pss`] -- and the same free-function/[`RSASSA_PSS_SHAKE`]-trait-type split, +//! with `X: XOF` in place of `H: Hash` and no `SEED_LEN` (there is no MGF1 counter to size). use crate::codec::{be_bytes_from_limbs, limbs_from_be_bytes}; use crate::emsa_pss_shake::{emsa_pss_encode_shake_from_hash, emsa_pss_verify_shake_from_hash}; use crate::keys::{RsaPrivateKey, RsaPublicKey}; use crate::rsa_core::{rsasp1, rsavp1}; use bouncycastle_core::errors::SignatureError; -use bouncycastle_core::traits::{RNG, XOF}; +use bouncycastle_core::traits::{ + RNG, SignaturePrivateKey, SignaturePublicKey, SignatureVerifier, Signer, XOF, +}; +use bouncycastle_rng::DefaultRNG; + +/// Streaming state for RSASSA-PSS-SHAKE's [`Signer`] and [`SignatureVerifier`] impls: exactly +/// [`crate::rsassa_pss::RSASSA_PSS`] (whose docs cover the shared behaviour, including where the +/// salt comes from and the [`Self::sign_randomized`]/[`Self::set_signer_salt`] ways to control +/// it) built on the SHAKE-native encoding instead. `X`'s `Hash` methods (a `XOF` is a `Hash`) +/// absorb the streamed message; its `H_LEN`-byte output is `mHash`, as in the free functions. +/// Concrete pairings are aliases such as `crate::rsa_2048::RSASSA_PSS_SHAKE128`. +#[allow(non_camel_case_types)] +pub struct RSASSA_PSS_SHAKE< + X, + const H_LEN: usize, + const S_LEN: usize, + const M_PRIME_LEN: usize, + const DB_LEN: usize, + const L: usize, + const L2: usize, + const L21: usize, + const HALF: usize, + const HALF2: usize, + const HALF21: usize, + const K_LEN: usize, + const SK_LEN: usize, + const PK_LEN: usize, +> { + hash: X, + sk: Option>, + pk: Option>, + /// See `RSASSA_PSS`'s field of the same name. + salt: Option<[u8; S_LEN]>, +} + +impl< + X: XOF + Default, + const H_LEN: usize, + const S_LEN: usize, + const M_PRIME_LEN: usize, + const DB_LEN: usize, + const L: usize, + const L2: usize, + const L21: usize, + const HALF: usize, + const HALF2: usize, + const HALF21: usize, + const K_LEN: usize, + const SK_LEN: usize, + const PK_LEN: usize, +> + RSASSA_PSS_SHAKE< + X, + H_LEN, + S_LEN, + M_PRIME_LEN, + DB_LEN, + L, + L2, + L21, + HALF, + HALF2, + HALF21, + K_LEN, + SK_LEN, + PK_LEN, + > +where + RsaPrivateKey: SignaturePrivateKey, +{ + /// As [`crate::rsassa_pss::RSASSA_PSS::sign_randomized`]: the salt from the caller's `rng`. + pub fn sign_randomized( + sk: &RsaPrivateKey, + msg: &[u8], + rng: &mut dyn RNG, + ) -> Result<[u8; K_LEN], SignatureError> { + let mut salt = [0u8; S_LEN]; + rng.next_bytes_out(&mut salt).map_err(SignatureError::RNGError)?; + let mut signer = Self::sign_init(sk, None)?; + signer.set_signer_salt(salt); + signer.sign_update(msg); + signer.sign_final() + } + + /// As [`crate::rsassa_pss::RSASSA_PSS::set_signer_salt`]: fixes the salt `sign_final` uses. + pub fn set_signer_salt(&mut self, salt: [u8; S_LEN]) { + self.salt = Some(salt); + } +} + +impl< + X: XOF + Default, + const H_LEN: usize, + const S_LEN: usize, + const M_PRIME_LEN: usize, + const DB_LEN: usize, + const L: usize, + const L2: usize, + const L21: usize, + const HALF: usize, + const HALF2: usize, + const HALF21: usize, + const K_LEN: usize, + const SK_LEN: usize, + const PK_LEN: usize, +> Signer, SK_LEN, K_LEN> + for RSASSA_PSS_SHAKE< + X, + H_LEN, + S_LEN, + M_PRIME_LEN, + DB_LEN, + L, + L2, + L21, + HALF, + HALF2, + HALF21, + K_LEN, + SK_LEN, + PK_LEN, + > +where + // See `RSASSA_PKCS1_v1_5`'s `Signer` impl: no `SignaturePrivateKey`, no `Signer`. + RsaPrivateKey: SignaturePrivateKey, +{ + fn sign( + sk: &RsaPrivateKey, + msg: &[u8], + ctx: Option<&[u8]>, + ) -> Result<[u8; K_LEN], SignatureError> { + let mut s = Self::sign_init(sk, ctx)?; + s.sign_update(msg); + s.sign_final() + } + + fn sign_out( + sk: &RsaPrivateKey, + msg: &[u8], + ctx: Option<&[u8]>, + output: &mut [u8; K_LEN], + ) -> Result { + output.fill(0); + *output = Self::sign(sk, msg, ctx)?; + Ok(K_LEN) + } + + fn sign_init(sk: &RsaPrivateKey, _ctx: Option<&[u8]>) -> Result { + // ctx ignored -- see `RSASSA_PKCS1_v1_5`'s docs. + Ok(Self { hash: X::default(), sk: Some(sk.clone()), pk: None, salt: None }) + } + + fn sign_update(&mut self, msg_chunk: &[u8]) { + self.hash.do_update(msg_chunk); + } + + fn sign_final(self) -> Result<[u8; K_LEN], SignatureError> { + let sk = self.sk.ok_or(SignatureError::GenericError( + "sign_final called on a verify-initialized RSASSA_PSS_SHAKE; call verify_final instead", + ))?; + // EMSA-PSS step 2, `mHash = Hash(M)`, completed here over the streamed chunks. + let mut m_hash = [0u8; H_LEN]; + self.hash.do_final_out(&mut m_hash); + // EMSA-PSS-ENCODE step 4's salt: fixed by `set_signer_salt`, else fresh from the default + // RNG (see `RSASSA_PSS`). + let salt = match self.salt { + Some(salt) => salt, + None => { + let mut salt = [0u8; S_LEN]; + DefaultRNG::default() + .next_bytes_out(&mut salt) + .map_err(SignatureError::RNGError)?; + salt + } + }; + sign_from_hash_with_salt::< + X, + H_LEN, + S_LEN, + M_PRIME_LEN, + DB_LEN, + L, + L2, + L21, + HALF, + HALF2, + HALF21, + K_LEN, + >(&sk, &m_hash, &salt) + } + + fn sign_final_out(self, output: &mut [u8; K_LEN]) -> Result { + output.fill(0); + *output = self.sign_final()?; + Ok(K_LEN) + } +} + +impl< + X: XOF + Default, + const H_LEN: usize, + const S_LEN: usize, + const M_PRIME_LEN: usize, + const DB_LEN: usize, + const L: usize, + const L2: usize, + const L21: usize, + const HALF: usize, + const HALF2: usize, + const HALF21: usize, + const K_LEN: usize, + const SK_LEN: usize, + const PK_LEN: usize, +> SignatureVerifier, PK_LEN, K_LEN> + for RSASSA_PSS_SHAKE< + X, + H_LEN, + S_LEN, + M_PRIME_LEN, + DB_LEN, + L, + L2, + L21, + HALF, + HALF2, + HALF21, + K_LEN, + SK_LEN, + PK_LEN, + > +where + RsaPublicKey: SignaturePublicKey, +{ + fn verify( + pk: &RsaPublicKey, + msg: &[u8], + ctx: Option<&[u8]>, + sig: &[u8], + ) -> Result<(), SignatureError> { + let mut v = Self::verify_init(pk, ctx)?; + v.verify_update(msg); + v.verify_final(sig) + } + + fn verify_init(pk: &RsaPublicKey, _ctx: Option<&[u8]>) -> Result { + Ok(Self { hash: X::default(), sk: None, pk: Some(pk.clone()), salt: None }) + } + + fn verify_update(&mut self, msg_chunk: &[u8]) { + self.hash.do_update(msg_chunk); + } + + fn verify_final(self, sig: &[u8]) -> Result<(), SignatureError> { + let pk = self.pk.ok_or(SignatureError::GenericError( + "verify_final called on a sign-initialized RSASSA_PSS_SHAKE; call sign_final instead", + ))?; + // RFC 8017 §8.1.2 step 1: "Length checking: If the length of the signature S is not k + // octets, output "invalid signature" and stop." (See `RSASSA_PKCS1_v1_5::verify_final`.) + let sig: &[u8; K_LEN] = + sig.try_into().map_err(|_| SignatureError::SignatureVerificationFailed)?; + let mut m_hash = [0u8; H_LEN]; + self.hash.do_final_out(&mut m_hash); + // Step 2.b: RSAVP1's "signature representative out of range" is "invalid signature" here + // (see `RSASSA_PKCS1_v1_5::verify_final`). + verify_from_hash::( + &pk, &m_hash, sig, + ) + .map_err(|_| SignatureError::SignatureVerificationFailed) + } +} /// RSASSA-PSS-SIGN (RFC 8017 §8.1.1) with the salt supplied directly rather than drawn from an /// RNG, mirroring [`crate::rsassa_pss::sign_with_salt`]: EMSA-PSS is randomized only in its choice diff --git a/crypto/rsa/tests/keys_tests.rs b/crypto/rsa/tests/keys_tests.rs index a9a71ea0..6fbd8ef4 100644 --- a/crypto/rsa/tests/keys_tests.rs +++ b/crypto/rsa/tests/keys_tests.rs @@ -1,6 +1,11 @@ -//! Validation tests for [`bouncycastle_rsa::keys`]'s public API. +//! Validation tests for [`bouncycastle_rsa::keys`]'s public API, including the +//! `SignaturePrivateKey`/`SignaturePublicKey` impls `rsa_2048` gives its aliases of these types +//! (`RsaPrivateKey<32, 16>` *is* `Rsa2048PrivateKey`, 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::SignatureError; +use bouncycastle_core::traits::{SignaturePrivateKey, SignaturePublicKey}; use bouncycastle_rsa::keys::{RsaPrivateKey, RsaPublicKey}; const P: [u64; 16] = [ @@ -131,39 +136,112 @@ fn public_key_rejects_even_modulus() { #[test] fn public_key_encode_round_trips() { let pk = RsaPublicKey::<32>::new(&N, 0x10001).unwrap(); - let bytes: [u8; 260] = pk.encode::<256, 260>(); - let decoded = RsaPublicKey::<32>::from_bytes::<256, 260>(&bytes).expect("must decode"); + let bytes: [u8; 260] = pk.encode(); + let decoded = RsaPublicKey::<32>::from_bytes(&bytes).expect("must decode"); assert_eq!(decoded, pk); } +/// `SignaturePublicKey`'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 = RsaPublicKey::<32>::new(&N, 0x10001).unwrap(); + 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 = RsaPublicKey::<32>::new(&N, 0x10001).unwrap(); - let mut bytes: [u8; 260] = pk.encode::<256, 260>(); + let mut bytes: [u8; 260] = pk.encode(); bytes[255] &= !1; // clear n's low bit (last byte, big-endian) assert!(matches!( - RsaPublicKey::<32>::from_bytes::<256, 260>(&bytes), + RsaPublicKey::<32>::from_bytes(&bytes), + Err(SignatureError::DecodingError(_)) + )); +} + +#[test] +fn public_key_from_bytes_rejects_wrong_lengths() { + let pk = RsaPublicKey::<32>::new(&N, 0x10001).unwrap(); + let bytes = pk.encode(); + assert!(matches!( + RsaPublicKey::<32>::from_bytes(&bytes[..259]), + Err(SignatureError::DecodingError(_)) + )); + let mut too_long = bytes.to_vec(); + too_long.push(0); + assert!(matches!( + RsaPublicKey::<32>::from_bytes(&too_long), Err(SignatureError::DecodingError(_)) )); } +/// `Display` (a `SignaturePublicKey` 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 = RsaPublicKey::<32>::new(&N, 0x10001).unwrap(); + let shown = format!("{pk}"); + let n_hex: String = pk.encode()[..256].iter().map(|b| format!("{b:02x}")).collect(); + assert_eq!(shown, format!("RsaPublicKey<32> {{ n: {n_hex}, e: 10001 }}")); +} + #[test] fn private_key_encode_round_trips() { let sk = RsaPrivateKey::<32, 16>::from_crt_components(&P, &Q, &D_P, &D_Q, &Q_INV).unwrap(); - let bytes: [u8; 640] = sk.encode::<128, 640>(); - let decoded = RsaPrivateKey::<32, 16>::from_bytes::<128, 640>(&bytes).expect("must decode"); + let bytes: [u8; 640] = sk.encode(); + let decoded = RsaPrivateKey::<32, 16>::from_bytes(&bytes).expect("must decode"); assert_eq!(decoded, sk); } +/// `SignaturePrivateKey`'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 = RsaPrivateKey::<32, 16>::from_crt_components(&P, &Q, &D_P, &D_Q, &Q_INV).unwrap(); + 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 = RsaPrivateKey::<32, 16>::from_crt_components(&P, &Q, &D_P, &D_Q, &Q_INV).unwrap(); - let mut bytes: [u8; 640] = sk.encode::<128, 640>(); + 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::<32, 16>::from_bytes::<128, 640>(&bytes), + RsaPrivateKey::<32, 16>::from_bytes(&bytes), + Err(SignatureError::DecodingError(_)) + )); +} + +#[test] +fn private_key_from_bytes_rejects_wrong_lengths() { + let sk = RsaPrivateKey::<32, 16>::from_crt_components(&P, &Q, &D_P, &D_Q, &Q_INV).unwrap(); + let bytes = sk.encode(); + assert!(matches!( + RsaPrivateKey::<32, 16>::from_bytes(&bytes[..639]), + Err(SignatureError::DecodingError(_)) + )); + let mut too_long = bytes.to_vec(); + too_long.push(0); + assert!(matches!( + RsaPrivateKey::<32, 16>::from_bytes(&too_long), Err(SignatureError::DecodingError(_)) )); } diff --git a/crypto/rsa/tests/rsa_1024_tests.rs b/crypto/rsa/tests/rsa_1024_tests.rs index 518dacd5..95203fc2 100644 --- a/crypto/rsa/tests/rsa_1024_tests.rs +++ b/crypto/rsa/tests/rsa_1024_tests.rs @@ -6,9 +6,12 @@ //! 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::SignatureError; +use bouncycastle_core::traits::{SignaturePublicKey, SignatureVerifier}; use bouncycastle_hex::decode as hex_decode; use bouncycastle_rsa::rsa_1024::{ - Rsa1024PublicKey, pkcs1_v1_5_verify_sha256, pkcs1_v1_5_verify_sha384, + PK_LEN, RSASSA_PKCS1_v1_5_SHA256, RSASSA_PKCS1_v1_5_SHA384, Rsa1024PublicKey, + pkcs1_v1_5_verify_sha256, pkcs1_v1_5_verify_sha384, }; use serde_json::Value; use std::fs; @@ -127,3 +130,67 @@ fn pkcs1_v1_5_sha384_rejects_wrong_message() { pkcs1_v1_5_verify_sha384(pk, msg, sig).is_ok() }); } + +// ---- bouncycastle_core trait conformance ------------------------------------------------------ +// +// No `Signer` 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 +// `SignatureVerifier` and `SignaturePublicKey` impls are checked directly against the same +// genuine Wycheproof material as the free functions. + +#[test] +fn trait_verify_accepts_genuine_sig_gen_signatures() { + run_sig_gen_group_as_verify_vectors("SHA-256", |pk, msg, sig| { + RSASSA_PKCS1_v1_5_SHA256::verify(pk, msg, None, sig).is_ok() + }); + run_sig_gen_group_as_verify_vectors("SHA-384", |pk, msg, sig| { + RSASSA_PKCS1_v1_5_SHA384::verify(pk, msg, None, sig).is_ok() + }); +} + +#[test] +fn trait_verify_rejects_wrong_message() { + run_sig_gen_group_rejects_wrong_message("SHA-256", |pk, msg, sig| { + RSASSA_PKCS1_v1_5_SHA256::verify(pk, msg, None, sig).is_ok() + }); + run_sig_gen_group_rejects_wrong_message("SHA-384", |pk, msg, sig| { + RSASSA_PKCS1_v1_5_SHA384::verify(pk, msg, None, sig).is_ok() + }); +} + +/// RFC 8017 §8.2.2 step 1 through the trait's `&[u8]` signature: a truncated genuine signature +/// is "invalid signature", never accepted. +#[test] +fn trait_verify_rejects_truncated_signature() { + run_sig_gen_group_as_verify_vectors("SHA-256", |pk, msg, sig| { + matches!( + RSASSA_PKCS1_v1_5_SHA256::verify(pk, msg, None, &sig[..127]), + Err(SignatureError::SignatureVerificationFailed) + ) + }); +} + +#[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 = Rsa1024PublicKey::new(&n, e).unwrap(); + + let bytes = pk.encode(); + assert_eq!(bytes.len(), PK_LEN); + assert_eq!(Rsa1024PublicKey::from_bytes(&bytes).unwrap(), pk); + assert!(matches!( + Rsa1024PublicKey::from_bytes(&bytes[..PK_LEN - 1]), + Err(SignatureError::DecodingError(_)) + )); + let mut too_long = bytes.to_vec(); + too_long.push(0); + assert!(matches!( + Rsa1024PublicKey::from_bytes(&too_long), + Err(SignatureError::DecodingError(_)) + )); +} diff --git a/crypto/rsa/tests/rsa_1536_tests.rs b/crypto/rsa/tests/rsa_1536_tests.rs index a025cd68..c93d5229 100644 --- a/crypto/rsa/tests/rsa_1536_tests.rs +++ b/crypto/rsa/tests/rsa_1536_tests.rs @@ -4,8 +4,11 @@ //! 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::SignatureError; +use bouncycastle_core::traits::{SignaturePublicKey, SignatureVerifier}; use bouncycastle_hex::decode as hex_decode; use bouncycastle_rsa::rsa_1536::{ + PK_LEN, RSASSA_PKCS1_v1_5_SHA256, RSASSA_PKCS1_v1_5_SHA384, RSASSA_PKCS1_v1_5_SHA512, Rsa1536PublicKey, pkcs1_v1_5_verify_sha256, pkcs1_v1_5_verify_sha384, pkcs1_v1_5_verify_sha512, }; use serde_json::Value; @@ -134,3 +137,69 @@ fn pkcs1_v1_5_sha512_rejects_wrong_message() { pkcs1_v1_5_verify_sha512(pk, msg, 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_accepts_genuine_sig_gen_signatures() { + run_sig_gen_group_as_verify_vectors("SHA-256", |pk, msg, sig| { + RSASSA_PKCS1_v1_5_SHA256::verify(pk, msg, None, sig).is_ok() + }); + run_sig_gen_group_as_verify_vectors("SHA-384", |pk, msg, sig| { + RSASSA_PKCS1_v1_5_SHA384::verify(pk, msg, None, sig).is_ok() + }); + run_sig_gen_group_as_verify_vectors("SHA-512", |pk, msg, sig| { + RSASSA_PKCS1_v1_5_SHA512::verify(pk, msg, None, sig).is_ok() + }); +} + +#[test] +fn trait_verify_rejects_wrong_message() { + run_sig_gen_group_rejects_wrong_message("SHA-256", |pk, msg, sig| { + RSASSA_PKCS1_v1_5_SHA256::verify(pk, msg, None, sig).is_ok() + }); + run_sig_gen_group_rejects_wrong_message("SHA-384", |pk, msg, sig| { + RSASSA_PKCS1_v1_5_SHA384::verify(pk, msg, None, sig).is_ok() + }); + run_sig_gen_group_rejects_wrong_message("SHA-512", |pk, msg, sig| { + RSASSA_PKCS1_v1_5_SHA512::verify(pk, msg, None, sig).is_ok() + }); +} + +#[test] +fn trait_verify_rejects_truncated_signature() { + run_sig_gen_group_as_verify_vectors("SHA-256", |pk, msg, sig| { + matches!( + RSASSA_PKCS1_v1_5_SHA256::verify(pk, msg, None, &sig[..191]), + Err(SignatureError::SignatureVerificationFailed) + ) + }); +} + +#[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 = Rsa1536PublicKey::new(&n, e).unwrap(); + + let bytes = pk.encode(); + assert_eq!(bytes.len(), PK_LEN); + assert_eq!(Rsa1536PublicKey::from_bytes(&bytes).unwrap(), pk); + assert!(matches!( + Rsa1536PublicKey::from_bytes(&bytes[..PK_LEN - 1]), + Err(SignatureError::DecodingError(_)) + )); + let mut too_long = bytes.to_vec(); + too_long.push(0); + assert!(matches!( + Rsa1536PublicKey::from_bytes(&too_long), + Err(SignatureError::DecodingError(_)) + )); +} 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 index 3c76685b..0f3ed66c 100644 --- 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 @@ -13,9 +13,13 @@ //! 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::traits::Signer; +use bouncycastle_core_test_framework::signature::TestFrameworkSignature; use bouncycastle_hex::decode as hex_decode; use bouncycastle_rsa::rsa_2048::{ - Rsa2048PrivateKey, Rsa2048PublicKey, pkcs1_v1_5_sign_sha384, pkcs1_v1_5_sign_sha512, + PK_LEN, RSASSA_PKCS1_v1_5_SHA384, RSASSA_PKCS1_v1_5_SHA512, Rsa2048PrivateKey, + Rsa2048PublicKey, SIG_LEN, SK_LEN, pkcs1_v1_5_sign_sha384, pkcs1_v1_5_sign_sha512, pkcs1_v1_5_verify_sha384, pkcs1_v1_5_verify_sha512, }; use serde_json::Value; @@ -198,3 +202,51 @@ fn rsa_signature_sha512_wycheproof_vectors() { 250, ); } + +// ---- bouncycastle_core trait conformance ------------------------------------------------------ + +fn fixed_keypair() -> Result<(Rsa2048PublicKey, Rsa2048PrivateKey), SignatureError> { + let sk = genuine_key(); + let pk = Rsa2048PublicKey::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(true, false); + framework.test_signature::< + Rsa2048PublicKey, + Rsa2048PrivateKey, + RSASSA_PKCS1_v1_5_SHA384, + RSASSA_PKCS1_v1_5_SHA384, + PK_LEN, + SK_LEN, + SIG_LEN, + >(fixed_keypair, false); + framework.test_signature::< + Rsa2048PublicKey, + Rsa2048PrivateKey, + RSASSA_PKCS1_v1_5_SHA512, + RSASSA_PKCS1_v1_5_SHA512, + PK_LEN, + SK_LEN, + SIG_LEN, + >(fixed_keypair, false); +} + +#[test] +fn pkcs1_v1_5_sha384_sha512_trait_matches_free_functions() { + let (_, sk) = fixed_keypair().unwrap(); + let msg = b"same message, both APIs"; + assert_eq!( + RSASSA_PKCS1_v1_5_SHA384::sign(&sk, msg, None).unwrap(), + pkcs1_v1_5_sign_sha384(&sk, msg).unwrap() + ); + assert_eq!( + RSASSA_PKCS1_v1_5_SHA512::sign(&sk, msg, None).unwrap(), + pkcs1_v1_5_sign_sha512(&sk, msg).unwrap() + ); +} diff --git a/crypto/rsa/tests/rsa_2048_pkcs1_v1_5_tests.rs b/crypto/rsa/tests/rsa_2048_pkcs1_v1_5_tests.rs index 7b8f3334..8d5fac46 100644 --- a/crypto/rsa/tests/rsa_2048_pkcs1_v1_5_tests.rs +++ b/crypto/rsa/tests/rsa_2048_pkcs1_v1_5_tests.rs @@ -31,9 +31,15 @@ //! 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::traits::{SignatureVerifier, Signer}; +use bouncycastle_core_test_framework::signature::{ + TestFrameworkSignature, TestFrameworkSignatureKeys, +}; use bouncycastle_hex::decode as hex_decode; use bouncycastle_rsa::rsa_2048::{ - Rsa2048PrivateKey, Rsa2048PublicKey, pkcs1_v1_5_sign_sha256, pkcs1_v1_5_verify_sha256, + PK_LEN, RSASSA_PKCS1_v1_5_SHA256, Rsa2048PrivateKey, Rsa2048PublicKey, SIG_LEN, SK_LEN, + pkcs1_v1_5_sign_sha256, pkcs1_v1_5_verify_sha256, }; use serde_json::Value; use std::fs; @@ -215,3 +221,165 @@ fn rsa_signature_sha256_all_groups() { assert_eq!(num_valid, 9); assert_eq!(num_invalid, 249); } + +// ---- bouncycastle_core trait conformance ------------------------------------------------------ + +/// The same genuine key pair as the free-function tests 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<(Rsa2048PublicKey, Rsa2048PrivateKey), SignatureError> { + let sk = wycheproof_key(); + let pk = Rsa2048PublicKey::new(sk.n(), 0x10001)?; + Ok((pk, sk)) +} + +/// The shared `Signer`/`SignatureVerifier` 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(true, false).test_signature::< + Rsa2048PublicKey, + Rsa2048PrivateKey, + RSASSA_PKCS1_v1_5_SHA256, + RSASSA_PKCS1_v1_5_SHA256, + PK_LEN, + SK_LEN, + SIG_LEN, + >(fixed_keypair, true); +} + +#[test] +fn key_trait_boundary_conditions() { + TestFrameworkSignatureKeys::new() + .test_keys::(fixed_keypair); +} + +/// The trait path and the free-function path are one computation: byte-identical signatures +/// (PKCS#1 v1.5 is deterministic) whether streamed or one-shot, and each side verifies the +/// other's output. +#[test] +fn pkcs1_v1_5_sha256_trait_matches_free_functions() { + let (pk, sk) = fixed_keypair().unwrap(); + let msg = b"the same message, three ways"; + let free = pkcs1_v1_5_sign_sha256(&sk, msg).unwrap(); + let one_shot = RSASSA_PKCS1_v1_5_SHA256::sign(&sk, msg, None).unwrap(); + let mut signer = RSASSA_PKCS1_v1_5_SHA256::sign_init(&sk, None).unwrap(); + signer.sign_update(&msg[..10]); + signer.sign_update(&msg[10..]); + let streamed = signer.sign_final().unwrap(); + assert_eq!(one_shot, free); + assert_eq!(streamed, free); + pkcs1_v1_5_verify_sha256(&pk, msg, &one_shot).unwrap(); + RSASSA_PKCS1_v1_5_SHA256::verify(&pk, msg, None, &free).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. `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 = RSASSA_PKCS1_v1_5_SHA256::sign(&sk, b"msg", None).unwrap(); + assert!(matches!( + RSASSA_PKCS1_v1_5_SHA256::verify(&pk, b"msg", None, &sig[..SIG_LEN - 1]), + Err(SignatureError::SignatureVerificationFailed) + )); + assert!(matches!( + RSASSA_PKCS1_v1_5_SHA256::verify(&pk, b"msg", None, &[]), + Err(SignatureError::SignatureVerificationFailed) + )); +} + +/// 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 trait_final_in_the_wrong_role_is_an_error() { + let (pk, sk) = fixed_keypair().unwrap(); + let mut out = [0u8; SIG_LEN]; + + let verifier = RSASSA_PKCS1_v1_5_SHA256::verify_init(&pk, None).unwrap(); + assert!(matches!(verifier.sign_final(), Err(SignatureError::GenericError(_)))); + let verifier = RSASSA_PKCS1_v1_5_SHA256::verify_init(&pk, None).unwrap(); + assert!(matches!(verifier.sign_final_out(&mut out), Err(SignatureError::GenericError(_)))); + + let signer = RSASSA_PKCS1_v1_5_SHA256::sign_init(&sk, None).unwrap(); + assert!(matches!(signer.verify_final(&out), Err(SignatureError::GenericError(_)))); +} + +/// `rsa_signature_2048_sha256_test.json` again, this time through `SignatureVerifier::verify`'s +/// `&[u8]` signature: unlike [`rsa_signature_sha256_all_groups`], the wrong-length vectors reach +/// the verifier here and must come back as `SignatureVerificationFailed` (RFC 8017 §8.2.2 step +/// 1) rather than being rejected by the test's own `try_into`. +#[test] +fn rsa_signature_sha256_all_groups_via_trait() { + 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 = Rsa2048PublicKey::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 = RSASSA_PKCS1_v1_5_SHA256::verify(&pk, &msg, None, &sig); + match test["result"].as_str().unwrap() { + // "acceptable" is only ever MissingNull in this file, accepted by policy -- see + // rsa_signature_sha256_all_groups. + "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::SignatureVerificationFailed)), + "tcId {tc_id}: a {}-byte signature must fail step 1's length check \ + as 'invalid signature', 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 free function deliberately surfaces RSAVP1's own +/// `DecodingError` so vector-driven callers can tell malformed from wrong -- see +/// `rsassa_pkcs1_v1_5::verify`'s 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]; + assert!(matches!( + pkcs1_v1_5_verify_sha256(&pk, b"msg", &too_big), + Err(SignatureError::DecodingError(_)) + )); + assert!(matches!( + RSASSA_PKCS1_v1_5_SHA256::verify(&pk, b"msg", None, &too_big), + Err(SignatureError::SignatureVerificationFailed) + )); +} diff --git a/crypto/rsa/tests/rsa_2048_pss_sha384_sha512_tests.rs b/crypto/rsa/tests/rsa_2048_pss_sha384_sha512_tests.rs index 44794170..c023968e 100644 --- a/crypto/rsa/tests/rsa_2048_pss_sha384_sha512_tests.rs +++ b/crypto/rsa/tests/rsa_2048_pss_sha384_sha512_tests.rs @@ -6,11 +6,15 @@ //! 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::traits::{SignatureVerifier, Signer}; +use bouncycastle_core_test_framework::signature::TestFrameworkSignature; use bouncycastle_hex::decode as hex_decode; use bouncycastle_rng::DefaultRNG; use bouncycastle_rsa::rsa_2048::{ - Rsa2048PrivateKey, Rsa2048PublicKey, pss_sign_sha384, pss_sign_sha384_with_salt, - pss_sign_sha512, pss_sign_sha512_with_salt, pss_verify_sha384, pss_verify_sha512, + PK_LEN, RSASSA_PSS_SHA384, RSASSA_PSS_SHA512, Rsa2048PrivateKey, Rsa2048PublicKey, SIG_LEN, + SK_LEN, pss_sign_sha384, pss_sign_sha384_with_salt, pss_sign_sha512, pss_sign_sha512_with_salt, + pss_verify_sha384, pss_verify_sha512, }; use serde_json::Value; use std::fs; @@ -177,3 +181,52 @@ fn rsa_pss_sha384_mgf1_48_wycheproof_vectors() { assert_eq!(num_valid, 95); assert_eq!(num_invalid, 46); } + +// ---- bouncycastle_core trait conformance ------------------------------------------------------ + +fn fixed_keypair() -> Result<(Rsa2048PublicKey, Rsa2048PrivateKey), SignatureError> { + let sk = genuine_key(); + let pk = Rsa2048PublicKey::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, false); + framework.test_signature::< + Rsa2048PublicKey, + Rsa2048PrivateKey, + RSASSA_PSS_SHA384, + RSASSA_PSS_SHA384, + PK_LEN, + SK_LEN, + SIG_LEN, + >(fixed_keypair, false); + framework.test_signature::< + Rsa2048PublicKey, + Rsa2048PrivateKey, + RSASSA_PSS_SHA512, + RSASSA_PSS_SHA512, + PK_LEN, + SK_LEN, + SIG_LEN, + >(fixed_keypair, false); +} + +#[test] +fn pss_sha384_sha512_trait_and_free_functions_cross_verify() { + let (pk, sk) = fixed_keypair().unwrap(); + let msg = b"PSS across both APIs"; + pss_verify_sha384(&pk, msg, &RSASSA_PSS_SHA384::sign(&sk, msg, None).unwrap()).unwrap(); + pss_verify_sha512(&pk, msg, &RSASSA_PSS_SHA512::sign(&sk, msg, None).unwrap()).unwrap(); + let mut rng = DefaultRNG::default(); + let free_384 = pss_sign_sha384(&sk, msg, &mut rng).unwrap(); + let free_512 = pss_sign_sha512(&sk, msg, &mut rng).unwrap(); + RSASSA_PSS_SHA384::verify(&pk, msg, None, &free_384).unwrap(); + RSASSA_PSS_SHA512::verify(&pk, msg, None, &free_512).unwrap(); + // The two hash pairings are distinct encodings: neither accepts the other's signature. + assert!(RSASSA_PSS_SHA384::verify(&pk, msg, None, &free_512).is_err()); + assert!(RSASSA_PSS_SHA512::verify(&pk, 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 index c492bd51..0dc0d724 100644 --- a/crypto/rsa/tests/rsa_2048_pss_shake128_tests.rs +++ b/crypto/rsa/tests/rsa_2048_pss_shake128_tests.rs @@ -5,11 +5,14 @@ //! 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::traits::{RNG, SignatureVerifier, Signer}; +use bouncycastle_core_test_framework::signature::TestFrameworkSignature; use bouncycastle_hex::decode as hex_decode; use bouncycastle_rng::DefaultRNG; use bouncycastle_rsa::rsa_2048::{ - Rsa2048PrivateKey, Rsa2048PublicKey, pss_shake128_sign, pss_shake128_sign_with_salt, - pss_shake128_verify, + PK_LEN, RSASSA_PSS_SHAKE128, Rsa2048PrivateKey, Rsa2048PublicKey, SIG_LEN, SK_LEN, + pss_shake128_sign, pss_shake128_sign_with_salt, pss_shake128_verify, }; use serde_json::Value; use std::fs; @@ -163,3 +166,119 @@ fn rsa_pss_2048_shake128_wycheproof_vectors() { assert_eq!(num_valid, 69); assert_eq!(num_invalid, 45); } + +// ---- bouncycastle_core trait conformance ------------------------------------------------------ + +fn fixed_keypair() -> Result<(Rsa2048PublicKey, Rsa2048PrivateKey), SignatureError> { + let sk = genuine_key(); + let pk = Rsa2048PublicKey::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, false).test_signature::< + Rsa2048PublicKey, + Rsa2048PrivateKey, + RSASSA_PSS_SHAKE128, + RSASSA_PSS_SHAKE128, + PK_LEN, + SK_LEN, + SIG_LEN, + >(fixed_keypair, true); +} + +#[test] +fn pss_shake128_trait_and_free_functions_cross_verify() { + let (pk, sk) = fixed_keypair().unwrap(); + let msg = b"PSS-SHAKE128 across both APIs"; + pss_shake128_verify(&pk, msg, &RSASSA_PSS_SHAKE128::sign(&sk, msg, None).unwrap()).unwrap(); + let from_free = pss_shake128_sign(&sk, msg, &mut DefaultRNG::default()).unwrap(); + RSASSA_PSS_SHAKE128::verify(&pk, msg, None, &from_free).unwrap(); + assert!(RSASSA_PSS_SHAKE128::verify(&pk, b"other", None, &from_free).is_err()); +} + +/// A fixed-output RNG (all-`0x42` bytes), as `bouncycastle-ecdsa`'s tests use: pins that +/// `sign_randomized` 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_signer_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 fixed-salt free +/// function over the same salt, while an unfixed streamed signature is fresh. +#[test] +fn set_signer_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 mut signer = RSASSA_PSS_SHAKE128::sign_init(&sk, None).unwrap(); + signer.set_signer_salt(salt); + signer.sign_update(&msg[..11]); + signer.sign_update(&msg[11..]); + let sig = signer.sign_final().unwrap(); + assert_eq!(sig, pss_shake128_sign_with_salt(&sk, msg, &salt).unwrap()); + RSASSA_PSS_SHAKE128::verify(&pk, msg, None, &sig).unwrap(); + + let mut fresh = RSASSA_PSS_SHAKE128::sign_init(&sk, None).unwrap(); + fresh.sign_update(msg); + assert_ne!(fresh.sign_final().unwrap(), sig, "without set_signer_salt the salt is fresh"); + + // On a verify-initialised state it has no effect. + let mut verifier = RSASSA_PSS_SHAKE128::verify_init(&pk, None).unwrap(); + verifier.set_signer_salt([0xffu8; 32]); + verifier.verify_update(msg); + verifier.verify_final(&sig).unwrap(); +} + +/// `sign_randomized` 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 through both the trait and the free-function verifier. +#[test] +fn sign_randomized_takes_the_salt_from_the_callers_rng() { + let (pk, sk) = fixed_keypair().unwrap(); + let msg = b"caller-supplied RNG"; + let from_fixed_rng = RSASSA_PSS_SHAKE128::sign_randomized(&sk, msg, &mut FixedRng).unwrap(); + assert_eq!(from_fixed_rng, pss_shake128_sign_with_salt(&sk, msg, &[0x42u8; 32]).unwrap()); + + let mut rng = DefaultRNG::default(); + let a = RSASSA_PSS_SHAKE128::sign_randomized(&sk, msg, &mut rng).unwrap(); + let b = RSASSA_PSS_SHAKE128::sign_randomized(&sk, msg, &mut rng).unwrap(); + assert_ne!(a, b); + RSASSA_PSS_SHAKE128::verify(&pk, msg, None, &a).unwrap(); + pss_shake128_verify(&pk, msg, &b).unwrap(); + assert!(RSASSA_PSS_SHAKE128::verify(&pk, b"other", None, &a).is_err()); + let _ = pss_shake128_sign; // the free functions stay the explicit-RNG one-shot path +} diff --git a/crypto/rsa/tests/rsa_2048_pss_tests.rs b/crypto/rsa/tests/rsa_2048_pss_tests.rs index 9f626e90..df08a905 100644 --- a/crypto/rsa/tests/rsa_2048_pss_tests.rs +++ b/crypto/rsa/tests/rsa_2048_pss_tests.rs @@ -10,11 +10,14 @@ //! `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::traits::{RNG, SignatureVerifier, Signer}; +use bouncycastle_core_test_framework::signature::TestFrameworkSignature; use bouncycastle_hex::decode as hex_decode; use bouncycastle_rng::DefaultRNG; use bouncycastle_rsa::rsa_2048::{ - Rsa2048PrivateKey, Rsa2048PublicKey, pss_sign_sha256, pss_sign_sha256_with_salt, - pss_verify_sha256, + PK_LEN, RSASSA_PSS_SHA256, Rsa2048PrivateKey, Rsa2048PublicKey, SIG_LEN, SK_LEN, + pss_sign_sha256, pss_sign_sha256_with_salt, pss_verify_sha256, }; use serde_json::Value; use std::fs; @@ -168,3 +171,122 @@ fn rsa_pss_sha256_mgf1_32_wycheproof_vectors() { assert_eq!(num_valid, 63); assert_eq!(num_invalid, 45); } + +// ---- bouncycastle_core trait conformance ------------------------------------------------------ + +fn fixed_keypair() -> Result<(Rsa2048PublicKey, Rsa2048PrivateKey), SignatureError> { + let sk = wycheproof_key(); + let pk = Rsa2048PublicKey::new(sk.n(), 0x10001)?; + Ok((pk, sk)) +} + +/// `core-test-framework`'s conformance suite: randomized (`Signer::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, false).test_signature::< + Rsa2048PublicKey, + Rsa2048PrivateKey, + RSASSA_PSS_SHA256, + RSASSA_PSS_SHA256, + PK_LEN, + SK_LEN, + SIG_LEN, + >(fixed_keypair, true); +} + +/// The trait's default-RNG salt and the free functions' caller-supplied RNG produce signatures +/// each side's verifier accepts: one encoding, two ways in. +#[test] +fn pss_sha256_trait_and_free_functions_cross_verify() { + let (pk, sk) = fixed_keypair().unwrap(); + let msg = b"PSS across both APIs"; + let from_trait = RSASSA_PSS_SHA256::sign(&sk, msg, None).unwrap(); + pss_verify_sha256(&pk, msg, &from_trait).unwrap(); + let from_free = pss_sign_sha256(&sk, msg, &mut DefaultRNG::default()).unwrap(); + RSASSA_PSS_SHA256::verify(&pk, msg, None, &from_free).unwrap(); + assert!(RSASSA_PSS_SHA256::verify(&pk, b"other", None, &from_free).is_err()); +} + +/// A fixed-output RNG (all-`0x42` bytes), as `bouncycastle-ecdsa`'s tests use: pins that +/// `sign_randomized` 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_signer_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 fixed-salt free +/// function over the same salt, while an unfixed streamed signature is fresh. +#[test] +fn set_signer_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 mut signer = RSASSA_PSS_SHA256::sign_init(&sk, None).unwrap(); + signer.set_signer_salt(salt); + signer.sign_update(&msg[..11]); + signer.sign_update(&msg[11..]); + let sig = signer.sign_final().unwrap(); + assert_eq!(sig, pss_sign_sha256_with_salt(&sk, msg, &salt).unwrap()); + RSASSA_PSS_SHA256::verify(&pk, msg, None, &sig).unwrap(); + + let mut fresh = RSASSA_PSS_SHA256::sign_init(&sk, None).unwrap(); + fresh.sign_update(msg); + assert_ne!(fresh.sign_final().unwrap(), sig, "without set_signer_salt the salt is fresh"); + + // On a verify-initialised state it has no effect. + let mut verifier = RSASSA_PSS_SHA256::verify_init(&pk, None).unwrap(); + verifier.set_signer_salt([0xffu8; 32]); + verifier.verify_update(msg); + verifier.verify_final(&sig).unwrap(); +} + +/// `sign_randomized` 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 through both the trait and the free-function verifier. +#[test] +fn sign_randomized_takes_the_salt_from_the_callers_rng() { + let (pk, sk) = fixed_keypair().unwrap(); + let msg = b"caller-supplied RNG"; + let from_fixed_rng = RSASSA_PSS_SHA256::sign_randomized(&sk, msg, &mut FixedRng).unwrap(); + assert_eq!(from_fixed_rng, pss_sign_sha256_with_salt(&sk, msg, &[0x42u8; 32]).unwrap()); + + let mut rng = DefaultRNG::default(); + let a = RSASSA_PSS_SHA256::sign_randomized(&sk, msg, &mut rng).unwrap(); + let b = RSASSA_PSS_SHA256::sign_randomized(&sk, msg, &mut rng).unwrap(); + assert_ne!(a, b); + RSASSA_PSS_SHA256::verify(&pk, msg, None, &a).unwrap(); + pss_verify_sha256(&pk, msg, &b).unwrap(); + assert!(RSASSA_PSS_SHA256::verify(&pk, b"other", None, &a).is_err()); + let _ = pss_sign_sha256; // the free functions stay the explicit-RNG one-shot path +} diff --git a/crypto/rsa/tests/rsa_3072_pss_shake128_tests.rs b/crypto/rsa/tests/rsa_3072_pss_shake128_tests.rs index ff652558..424c465b 100644 --- a/crypto/rsa/tests/rsa_3072_pss_shake128_tests.rs +++ b/crypto/rsa/tests/rsa_3072_pss_shake128_tests.rs @@ -3,11 +3,14 @@ //! 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::traits::{SignatureVerifier, Signer}; +use bouncycastle_core_test_framework::signature::TestFrameworkSignature; use bouncycastle_hex::decode as hex_decode; use bouncycastle_rng::DefaultRNG; use bouncycastle_rsa::rsa_3072::{ - Rsa3072PrivateKey, Rsa3072PublicKey, pss_shake128_sign, pss_shake128_sign_with_salt, - pss_shake128_verify, + PK_LEN, RSASSA_PSS_SHAKE128, Rsa3072PrivateKey, Rsa3072PublicKey, SIG_LEN, SK_LEN, + pss_shake128_sign, pss_shake128_sign_with_salt, pss_shake128_verify, }; use serde_json::Value; use std::fs; @@ -170,3 +173,33 @@ fn rsa_pss_3072_shake128_wycheproof_vectors() { assert_eq!(num_valid, 69); assert_eq!(num_invalid, 45); } + +// ---- bouncycastle_core trait conformance ------------------------------------------------------ + +fn fixed_keypair() -> Result<(Rsa3072PublicKey, Rsa3072PrivateKey), SignatureError> { + let sk = genuine_key(); + let pk = Rsa3072PublicKey::new(sk.n(), 0x10001)?; + Ok((pk, sk)) +} + +#[test] +fn pss_shake128_trait_conformance_suite() { + TestFrameworkSignature::new(false, false).test_signature::< + Rsa3072PublicKey, + Rsa3072PrivateKey, + RSASSA_PSS_SHAKE128, + RSASSA_PSS_SHAKE128, + PK_LEN, + SK_LEN, + SIG_LEN, + >(fixed_keypair, false); +} + +#[test] +fn pss_shake128_trait_and_free_functions_cross_verify() { + let (pk, sk) = fixed_keypair().unwrap(); + let msg = b"PSS-SHAKE128 at RSA-3072, both APIs"; + pss_shake128_verify(&pk, msg, &RSASSA_PSS_SHAKE128::sign(&sk, msg, None).unwrap()).unwrap(); + let from_free = pss_shake128_sign(&sk, msg, &mut DefaultRNG::default()).unwrap(); + RSASSA_PSS_SHAKE128::verify(&pk, msg, None, &from_free).unwrap(); +} diff --git a/crypto/rsa/tests/rsa_3072_tests.rs b/crypto/rsa/tests/rsa_3072_tests.rs index cdee2641..bf395bb2 100644 --- a/crypto/rsa/tests/rsa_3072_tests.rs +++ b/crypto/rsa/tests/rsa_3072_tests.rs @@ -10,14 +10,20 @@ //! `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::traits::{SignatureVerifier, Signer}; +use bouncycastle_core_test_framework::signature::{ + TestFrameworkSignature, TestFrameworkSignatureKeys, +}; use bouncycastle_hex::decode as hex_decode; use bouncycastle_rng::DefaultRNG; use bouncycastle_rsa::rsa_3072::{ - Rsa3072PrivateKey, Rsa3072PublicKey, pkcs1_v1_5_sign_sha256, pkcs1_v1_5_sign_sha384, - pkcs1_v1_5_sign_sha512, pkcs1_v1_5_verify_sha256, pkcs1_v1_5_verify_sha384, - pkcs1_v1_5_verify_sha512, pss_sign_sha256, pss_sign_sha256_with_salt, pss_sign_sha384, - pss_sign_sha384_with_salt, pss_sign_sha512, pss_sign_sha512_with_salt, pss_verify_sha256, - pss_verify_sha384, pss_verify_sha512, + 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, Rsa3072PrivateKey, Rsa3072PublicKey, + SIG_LEN, SK_LEN, pkcs1_v1_5_sign_sha256, pkcs1_v1_5_sign_sha384, pkcs1_v1_5_sign_sha512, + pkcs1_v1_5_verify_sha256, pkcs1_v1_5_verify_sha384, pkcs1_v1_5_verify_sha512, pss_sign_sha256, + pss_sign_sha256_with_salt, pss_sign_sha384, pss_sign_sha384_with_salt, pss_sign_sha512, + pss_sign_sha512_with_salt, pss_verify_sha256, pss_verify_sha384, pss_verify_sha512, }; use serde_json::Value; use std::fs; @@ -346,3 +352,98 @@ fn rsa_pss_3072_sha256_mgf1_32_wycheproof_vectors() { assert_eq!(num_valid, 63); assert_eq!(num_invalid, 45); } + +// ---- bouncycastle_core trait conformance ------------------------------------------------------ + +fn fixed_keypair() -> Result<(Rsa3072PublicKey, Rsa3072PrivateKey), SignatureError> { + let sk = genuine_key(); + let pk = Rsa3072PublicKey::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(true, false); + framework.test_signature::< + Rsa3072PublicKey, + Rsa3072PrivateKey, + RSASSA_PKCS1_v1_5_SHA256, + RSASSA_PKCS1_v1_5_SHA256, + PK_LEN, + SK_LEN, + SIG_LEN, + >(fixed_keypair, false); + framework.test_signature::< + Rsa3072PublicKey, + Rsa3072PrivateKey, + RSASSA_PKCS1_v1_5_SHA384, + RSASSA_PKCS1_v1_5_SHA384, + PK_LEN, + SK_LEN, + SIG_LEN, + >(fixed_keypair, false); + framework.test_signature::< + Rsa3072PublicKey, + Rsa3072PrivateKey, + RSASSA_PKCS1_v1_5_SHA512, + RSASSA_PKCS1_v1_5_SHA512, + PK_LEN, + SK_LEN, + SIG_LEN, + >(fixed_keypair, false); +} + +#[test] +fn pss_trait_conformance_suites() { + let framework = TestFrameworkSignature::new(false, false); + framework.test_signature::< + Rsa3072PublicKey, + Rsa3072PrivateKey, + RSASSA_PSS_SHA256, + RSASSA_PSS_SHA256, + PK_LEN, + SK_LEN, + SIG_LEN, + >(fixed_keypair, false); + framework.test_signature::< + Rsa3072PublicKey, + Rsa3072PrivateKey, + RSASSA_PSS_SHA384, + RSASSA_PSS_SHA384, + PK_LEN, + SK_LEN, + SIG_LEN, + >(fixed_keypair, false); + framework.test_signature::< + Rsa3072PublicKey, + Rsa3072PrivateKey, + RSASSA_PSS_SHA512, + RSASSA_PSS_SHA512, + PK_LEN, + SK_LEN, + SIG_LEN, + >(fixed_keypair, false); +} + +#[test] +fn key_trait_boundary_conditions() { + TestFrameworkSignatureKeys::new() + .test_keys::(fixed_keypair); +} + +/// Trait and free-function paths agree at this width: identical PKCS#1 v1.5 signatures, and +/// PSS signatures each side's verifier accepts. +#[test] +fn trait_matches_free_functions() { + let (pk, sk) = fixed_keypair().unwrap(); + let msg = b"RSA-3072, both APIs"; + assert_eq!( + RSASSA_PKCS1_v1_5_SHA256::sign(&sk, msg, None).unwrap(), + pkcs1_v1_5_sign_sha256(&sk, msg).unwrap() + ); + pss_verify_sha256(&pk, msg, &RSASSA_PSS_SHA256::sign(&sk, msg, None).unwrap()).unwrap(); + let from_free = pss_sign_sha256(&sk, msg, &mut DefaultRNG::default()).unwrap(); + RSASSA_PSS_SHA256::verify(&pk, msg, None, &from_free).unwrap(); +} diff --git a/crypto/rsa/tests/rsa_4096_pss_shake256_tests.rs b/crypto/rsa/tests/rsa_4096_pss_shake256_tests.rs index 87f80f87..038dea36 100644 --- a/crypto/rsa/tests/rsa_4096_pss_shake256_tests.rs +++ b/crypto/rsa/tests/rsa_4096_pss_shake256_tests.rs @@ -3,11 +3,12 @@ //! 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::traits::{SignatureVerifier, Signer}; use bouncycastle_hex::decode as hex_decode; use bouncycastle_rng::DefaultRNG; use bouncycastle_rsa::rsa_4096::{ - Rsa4096PrivateKey, Rsa4096PublicKey, pss_shake256_sign, pss_shake256_sign_with_salt, - pss_shake256_verify, + RSASSA_PSS_SHAKE256, Rsa4096PrivateKey, Rsa4096PublicKey, pss_shake256_sign, + pss_shake256_sign_with_salt, pss_shake256_verify, }; use serde_json::Value; use std::fs; @@ -180,3 +181,21 @@ fn rsa_pss_4096_shake256_wycheproof_vectors() { 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 +/// trip and cross-verification against the free functions. +#[test] +fn pss_shake256_trait_round_trip_and_cross_verify() { + let sk = genuine_key(); + let pk = Rsa4096PublicKey::new(sk.n(), 0x10001).unwrap(); + let msg = b"PSS-SHAKE256 at RSA-4096, both APIs"; + let from_trait = RSASSA_PSS_SHAKE256::sign(&sk, msg, None).unwrap(); + RSASSA_PSS_SHAKE256::verify(&pk, msg, None, &from_trait).unwrap(); + pss_shake256_verify(&pk, msg, &from_trait).unwrap(); + let from_free = pss_shake256_sign(&sk, msg, &mut DefaultRNG::default()).unwrap(); + RSASSA_PSS_SHAKE256::verify(&pk, msg, None, &from_free).unwrap(); + assert!(RSASSA_PSS_SHAKE256::verify(&pk, 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 index 4e9d7ac4..92bfe739 100644 --- a/crypto/rsa/tests/rsa_4096_tests.rs +++ b/crypto/rsa/tests/rsa_4096_tests.rs @@ -11,14 +11,20 @@ //! 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::traits::{SignatureVerifier, Signer}; +use bouncycastle_core_test_framework::signature::{ + TestFrameworkSignature, TestFrameworkSignatureKeys, +}; use bouncycastle_hex::decode as hex_decode; use bouncycastle_rng::DefaultRNG; use bouncycastle_rsa::rsa_4096::{ - Rsa4096PrivateKey, Rsa4096PublicKey, pkcs1_v1_5_sign_sha256, pkcs1_v1_5_sign_sha384, - pkcs1_v1_5_sign_sha512, pkcs1_v1_5_verify_sha256, pkcs1_v1_5_verify_sha384, - pkcs1_v1_5_verify_sha512, pss_sign_sha256, pss_sign_sha256_with_salt, pss_sign_sha384, - pss_sign_sha384_with_salt, pss_sign_sha512, pss_sign_sha512_with_salt, pss_verify_sha256, - pss_verify_sha384, pss_verify_sha512, + 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, Rsa4096PrivateKey, Rsa4096PublicKey, + SIG_LEN, SK_LEN, pkcs1_v1_5_sign_sha256, pkcs1_v1_5_sign_sha384, pkcs1_v1_5_sign_sha512, + pkcs1_v1_5_verify_sha256, pkcs1_v1_5_verify_sha384, pkcs1_v1_5_verify_sha512, pss_sign_sha256, + pss_sign_sha256_with_salt, pss_sign_sha384, pss_sign_sha384_with_salt, pss_sign_sha512, + pss_sign_sha512_with_salt, pss_verify_sha256, pss_verify_sha384, pss_verify_sha512, }; use serde_json::Value; use std::fs; @@ -393,3 +399,78 @@ fn pss_sha512_rng_produces_fresh_salts_that_both_verify() { pss_verify_sha512(&pk, b"hello", &sig_a).expect("sig_a must verify"); pss_verify_sha512(&pk, b"hello", &sig_b).expect("sig_b must verify"); } + +// ---- bouncycastle_core trait conformance ------------------------------------------------------ + +fn fixed_keypair() -> Result<(Rsa4096PublicKey, Rsa4096PrivateKey), SignatureError> { + let sk = genuine_key(); + let pk = Rsa4096PublicKey::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(true, false).test_signature::< + Rsa4096PublicKey, + Rsa4096PrivateKey, + RSASSA_PKCS1_v1_5_SHA256, + RSASSA_PKCS1_v1_5_SHA256, + PK_LEN, + SK_LEN, + SIG_LEN, + >(fixed_keypair, false); + TestFrameworkSignature::new(false, false).test_signature::< + Rsa4096PublicKey, + Rsa4096PrivateKey, + RSASSA_PSS_SHA256, + RSASSA_PSS_SHA256, + PK_LEN, + SK_LEN, + SIG_LEN, + >(fixed_keypair, false); +} + +#[test] +fn key_trait_boundary_conditions() { + TestFrameworkSignatureKeys::new() + .test_keys::(fixed_keypair); +} + +/// Sign then verify through the traits, verify the free functions' signature over the same +/// message through the trait, and reject a different message -- what a wrong width constant in +/// this size's aliases would break. +fn trait_round_trip(pk: &Rsa4096PublicKey, sk: &Rsa4096PrivateKey, free_sig: &[u8; SIG_LEN]) +where + S: Signer + + SignatureVerifier, +{ + let msg = b"RSA-4096 trait round trip"; + let sig = S::sign(sk, msg, None).unwrap(); + S::verify(pk, msg, None, &sig).unwrap(); + S::verify(pk, msg, None, free_sig).unwrap(); + assert!(S::verify(pk, b"a different message", None, &sig).is_err()); +} + +#[test] +fn remaining_pairings_trait_round_trips() { + let (pk, sk) = fixed_keypair().unwrap(); + let msg = b"RSA-4096 trait round trip"; + let mut rng = DefaultRNG::default(); + trait_round_trip::( + &pk, + &sk, + &pkcs1_v1_5_sign_sha384(&sk, msg).unwrap(), + ); + trait_round_trip::( + &pk, + &sk, + &pkcs1_v1_5_sign_sha512(&sk, msg).unwrap(), + ); + trait_round_trip::(&pk, &sk, &pss_sign_sha384(&sk, msg, &mut rng).unwrap()); + trait_round_trip::(&pk, &sk, &pss_sign_sha512(&sk, msg, &mut rng).unwrap()); +} diff --git a/crypto/rsa/tests/rsa_8192_tests.rs b/crypto/rsa/tests/rsa_8192_tests.rs index aee4dc0e..e60d637f 100644 --- a/crypto/rsa/tests/rsa_8192_tests.rs +++ b/crypto/rsa/tests/rsa_8192_tests.rs @@ -20,14 +20,20 @@ //! 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::traits::{SignatureVerifier, Signer}; +use bouncycastle_core_test_framework::signature::{ + TestFrameworkSignature, TestFrameworkSignatureKeys, +}; use bouncycastle_hex::decode as hex_decode; use bouncycastle_rng::DefaultRNG; use bouncycastle_rsa::rsa_8192::{ - Rsa8192PrivateKey, Rsa8192PublicKey, pkcs1_v1_5_sign_sha256, pkcs1_v1_5_sign_sha384, - pkcs1_v1_5_sign_sha512, pkcs1_v1_5_verify_sha256, pkcs1_v1_5_verify_sha384, - pkcs1_v1_5_verify_sha512, pss_sign_sha256, pss_sign_sha256_with_salt, pss_sign_sha384, - pss_sign_sha384_with_salt, pss_sign_sha512, pss_sign_sha512_with_salt, pss_verify_sha256, - pss_verify_sha384, pss_verify_sha512, + 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, Rsa8192PrivateKey, Rsa8192PublicKey, + SIG_LEN, SK_LEN, pkcs1_v1_5_sign_sha256, pkcs1_v1_5_sign_sha384, pkcs1_v1_5_sign_sha512, + pkcs1_v1_5_verify_sha256, pkcs1_v1_5_verify_sha384, pkcs1_v1_5_verify_sha512, pss_sign_sha256, + pss_sign_sha256_with_salt, pss_sign_sha384, pss_sign_sha384_with_salt, pss_sign_sha512, + pss_sign_sha512_with_salt, pss_verify_sha256, pss_verify_sha384, pss_verify_sha512, }; use serde_json::Value; use std::collections::HashSet; @@ -357,3 +363,77 @@ fn rsa_signature_8192_sha512_wycheproof_vectors_sampled() { "SHA-512", ); } + +// ---- bouncycastle_core trait conformance ------------------------------------------------------ + +fn fixed_keypair() -> Result<(Rsa8192PublicKey, Rsa8192PrivateKey), SignatureError> { + let sk = genuine_key(); + let pk = Rsa8192PublicKey::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(true, false).test_signature::< + Rsa8192PublicKey, + Rsa8192PrivateKey, + RSASSA_PKCS1_v1_5_SHA256, + RSASSA_PKCS1_v1_5_SHA256, + PK_LEN, + SK_LEN, + SIG_LEN, + >(fixed_keypair, false); +} + +#[test] +fn key_trait_boundary_conditions() { + TestFrameworkSignatureKeys::new() + .test_keys::(fixed_keypair); +} + +fn trait_round_trip(pk: &Rsa8192PublicKey, sk: &Rsa8192PrivateKey, free_sig: &[u8; SIG_LEN]) +where + S: Signer + + SignatureVerifier, +{ + let msg = b"RSA-8192 trait round trip"; + let sig = S::sign(sk, msg, None).unwrap(); + S::verify(pk, msg, None, &sig).unwrap(); + S::verify(pk, msg, None, free_sig).unwrap(); + assert!(S::verify(pk, b"a different message", None, &sig).is_err()); +} + +#[test] +fn remaining_pairings_trait_round_trips() { + let (pk, sk) = fixed_keypair().unwrap(); + let msg = b"RSA-8192 trait round trip"; + let mut rng = DefaultRNG::default(); + trait_round_trip::( + &pk, + &sk, + &pkcs1_v1_5_sign_sha384(&sk, msg).unwrap(), + ); + trait_round_trip::( + &pk, + &sk, + &pkcs1_v1_5_sign_sha512(&sk, msg).unwrap(), + ); + trait_round_trip::(&pk, &sk, &pss_sign_sha256(&sk, msg, &mut rng).unwrap()); + trait_round_trip::(&pk, &sk, &pss_sign_sha384(&sk, msg, &mut rng).unwrap()); + trait_round_trip::(&pk, &sk, &pss_sign_sha512(&sk, msg, &mut rng).unwrap()); +} + +/// 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 free-function +/// tests above, through `Signer`/`SignatureVerifier`. +#[test] +fn trait_matches_bc_java() { + let (pk, sk) = fixed_keypair().unwrap(); + let sig = RSASSA_PKCS1_v1_5_SHA256::sign(&sk, 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(); + RSASSA_PSS_SHA256::verify(&pk, b"hello", None, &pss).unwrap(); +} From 7a5407ef48d6cd30469baf1410673d0a9bca01db Mon Sep 17 00:00:00 2001 From: David Hook Date: Mon, 21 Sep 2026 09:57:34 +1000 Subject: [PATCH 15/55] cli: rsa-* subcommands stream stdin through Signer/SignatureVerifier instead of buffering the whole message This CLI's convention is stdin -> stdout in ~1 KB chunks so commands compose in pipelines; rsa_cmd.rs was the one exception, reading all of stdin into memory (read_all_stdin) because bouncycastle_rsa's sign/verify functions took the whole message as one slice and there was no incremental hash state to feed. Now that every (size, scheme, hash) pairing is a Signer/SignatureVerifier type, the RSA commands stream the message through sign_update/verify_update exactly as ecdsa_cmd.rs does for its curves, and one generic rsa_sign_verify_cmd bound over those traits replaces the per-scheme rsa_pkcs1_cmd/rsa_pss_cmd pair and the three function-pointer type aliases that selected a free function per scheme; do_verify needs only a SignatureVerifier, which is what the verify-only 1024/1536 types implement. PSS's salt now comes from the trait's own DefaultRNG rather than one this file constructed -- the same OS-backed source. The signature file's length check moves into verify_final (RFC 8017 SS8.1.2/SS8.2.2 step 1), so a wrong-length file is reported as an invalid signature rather than a separate error. Adds cli/tests/rsa_cli_tests.rs, driving the binary as aes_cbc_cli_tests.rs does: RSA-1024 verification of a genuine Wycheproof signature and rejection of a different message; an RSA-2048 PKCS#1 v1.5 signature over a 5000-byte payload (several stream buffers) compared byte for byte with the library's own Signer::sign, then verified through the CLI, in binary and hex output; PSS/SHA-256 and PSS-SHAKE128 signatures shown fresh per call and verified through both the CLI and the library's SignatureVerifier; a tampered and a truncated signature rejected; a wrong-length key file rejected with the expected size in the message; and unsupported pairings refused up front. Key material is the crate docs' own documented RSA-2048 CRT key and RSA-1024 Wycheproof key. Co-Authored-By: Claude Fable 5.1 --- cli/src/rsa_cmd.rs | 569 +++++++++++++++---------------------- cli/tests/rsa_cli_tests.rs | 311 ++++++++++++++++++++ 2 files changed, 537 insertions(+), 343 deletions(-) create mode 100644 cli/tests/rsa_cli_tests.rs diff --git a/cli/src/rsa_cmd.rs b/cli/src/rsa_cmd.rs index bd77f8a5..53e0cfc3 100644 --- a/cli/src/rsa_cmd.rs +++ b/cli/src/rsa_cmd.rs @@ -8,6 +8,14 @@ //! (`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 `Signer`/`SignatureVerifier` +//! types (`rsa_2048::RSASSA_PKCS1_v1_5_SHA256` and siblings), so, as `ecdsa_cmd.rs` does for its +//! curves, a single generic [`rsa_sign_verify_cmd`] bound over those traits is monomorphised once +//! per pairing below, and the message streams from stdin through the traits' `_update` methods in +//! this CLI's usual ~1 KB chunks rather than being read whole. `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`. +//! //! `bouncycastle_rsa` does not generate keys (see that crate's `keys` module docs), so there is no //! `Keygen` action here, and no `PkFromSk` either -- a private key's CRT components alone do not //! determine the public exponent `e`, so there is nothing to derive a public key from. Private and @@ -17,18 +25,15 @@ //! 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. -//! -//! Reads the whole message into memory (`read_all_stdin`) rather than this CLI's usual ~1 KB -//! streaming buffer: RSASSA-PKCS1-v1_5 and RSASSA-PSS both hash the entire message before any -//! signing/verification step can begin, and `bouncycastle_rsa`'s sign/verify functions take the -//! whole message as one slice -- there is no incremental hash state to feed a chunk at a time. +//! Scope`), so `rsa_1024_cmd`/`rsa_1536_cmd` take no `action`/`skfile` at all: they only verify, +//! through [`do_verify`], which needs only a `SignatureVerifier` -- exactly the trait those sizes' +//! types implement. use crate::helpers::{read_from_file, write_bytes_or_hex}; -use bouncycastle::core::errors::SignatureError; -use bouncycastle::core::traits::{RNG, SignaturePrivateKey, SignaturePublicKey}; -use bouncycastle::rng::DefaultRNG; -use bouncycastle::rsa::keys::{RsaPrivateKey, RsaPublicKey}; +use bouncycastle::core::traits::{ + SignaturePrivateKey, SignaturePublicKey, SignatureVerifier, Signer, +}; +use bouncycastle::rsa::{rsa_1024, rsa_1536, rsa_2048, rsa_3072, rsa_4096, rsa_8192}; use clap::ValueEnum; use std::io; use std::io::Read; @@ -76,11 +81,15 @@ fn require_file(file: &Option, flag_name: &str) -> Vec { } /// The message is read raw, never hex-decoded: unlike a key or signature file, arbitrary message -/// bytes that happen to look like hex must still be signed/verified byte-for-byte. -fn read_all_stdin() -> Vec { - let mut buf = Vec::new(); - io::stdin().read_to_end(&mut buf).expect("Failed to read from stdin"); - buf +/// bytes that happen to look like hex must still be signed/verified byte-for-byte. Streams stdin +/// through `update` in ~1 KB chunks (the same loop as `ecdsa_cmd.rs`). +fn stream_stdin_into(mut update: impl FnMut(&[u8])) { + let mut buf = [0u8; 1024]; + let mut bytes_read = io::stdin().read(&mut buf).expect("Failed to read from stdin"); + while bytes_read > 0 { + update(&buf[..bytes_read]); + bytes_read = io::stdin().read(&mut buf).expect("Failed to read from stdin"); + } } fn unsupported(scheme: &RSAScheme, hash: &RSAHash, alg_name: &str) -> ! { @@ -88,27 +97,13 @@ fn unsupported(scheme: &RSAScheme, hash: &RSAHash, alg_name: &str) -> ! { exit(-1); } -/// A `bouncycastle_rsa::rsa_*::pkcs1_v1_5_sign_*` function. -type PkcsSignFn = - fn(&RsaPrivateKey, &[u8]) -> Result<[u8; SIG_LEN], SignatureError>; -/// A `bouncycastle_rsa::rsa_*::pss_sign_*`/`pss_shake*_sign` function. -type PssSignFn = - fn(&RsaPrivateKey, &[u8], &mut dyn RNG) -> Result<[u8; SIG_LEN], SignatureError>; -/// A `bouncycastle_rsa::rsa_*::{pkcs1_v1_5,pss,pss_shake*}_verify_*` function -- the same shape -/// for every scheme, since verification never needs an RNG. -type VerifyFn = - fn(&RsaPublicKey, &[u8], &[u8; SIG_LEN]) -> Result<(), SignatureError>; - -/// See [`RsaPrivateKey`]'s `# Encoding` docs for the expected layout; a wrong-length file is one -/// of the `DecodingError`s `SignaturePrivateKey::from_bytes` reports. -fn parse_sk( +/// See `RsaPrivateKey`'s `# Encoding` docs for the expected layout; a wrong-length file is one of +/// the `DecodingError`s `SignaturePrivateKey::from_bytes` reports. +fn parse_sk, const SK_LEN: usize>( bytes: &[u8], alg_name: &str, -) -> RsaPrivateKey -where - RsaPrivateKey: SignaturePrivateKey, -{ - match as SignaturePrivateKey>::from_bytes(bytes) { +) -> SK { + match SK::from_bytes(bytes) { Ok(sk) => sk, Err(_) => { eprintln!( @@ -120,16 +115,13 @@ where } } -/// See [`RsaPublicKey`]'s `# Encoding` docs for the expected layout; a wrong-length file is one of +/// See `RsaPublicKey`'s `# Encoding` docs for the expected layout; a wrong-length file is one of /// the `DecodingError`s `SignaturePublicKey::from_bytes` reports. -fn parse_pk( +fn parse_pk, const PK_LEN: usize>( bytes: &[u8], alg_name: &str, -) -> RsaPublicKey -where - RsaPublicKey: SignaturePublicKey, -{ - match as SignaturePublicKey>::from_bytes(bytes) { +) -> PK { + match PK::from_bytes(bytes) { Ok(pk) => pk, Err(_) => { eprintln!( @@ -141,25 +133,29 @@ where } } -/// Shared by [`rsa_pkcs1_cmd`] and [`rsa_pss_cmd`]'s `Verify` arm, and called directly by the -/// verify-only sizes (`rsa_1024_cmd`, `rsa_1536_cmd`). -fn do_verify( - verify: VerifyFn, +/// Verifies stdin against `--pkfile`/`--sigfile` through `V`'s streaming `SignatureVerifier` +/// impl. Shared by [`rsa_sign_verify_cmd`]'s `Verify` arm, 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 `verify_final` reports it. +fn do_verify< + PK: SignaturePublicKey, + V: SignatureVerifier, + const PK_LEN: usize, + const SIG_LEN: usize, +>( pkfile: &Option, sigfile: &Option, alg_name: &str, -) where - RsaPublicKey: SignaturePublicKey, -{ - let pk_bytes = require_file(pkfile, "pkfile"); - let pk = parse_pk::(&pk_bytes, alg_name); - let sig_bytes = require_file(sigfile, "sigfile"); - let Ok(sig): Result<[u8; SIG_LEN], _> = sig_bytes.try_into() else { - eprintln!("Error: signature file must be exactly {SIG_LEN} bytes for {alg_name}."); - exit(-1); - }; - let msg = read_all_stdin(); - if verify(&pk, &msg, &sig).is_ok() { +) { + let pk = parse_pk::(&require_file(pkfile, "pkfile"), alg_name); + let sig = require_file(sigfile, "sigfile"); + + // `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 = V::verify_init(&pk, None).unwrap(); + stream_stdin_into(|chunk| verifier.verify_update(chunk)); + + if verifier.verify_final(&sig).is_ok() { println!("Signature is valid."); } else { eprintln!("Signature is invalid."); @@ -167,155 +163,110 @@ fn do_verify, + SK: SignaturePrivateKey, + S: Signer + SignatureVerifier, const PK_LEN: usize, - const SIG_LEN: usize, ->( - action: &RSAAction, - sign: PkcsSignFn, - verify: VerifyFn, - skfile: &Option, - pkfile: &Option, - sigfile: &Option, - output_hex: bool, - alg_name: &str, -) where - RsaPrivateKey: SignaturePrivateKey, - RsaPublicKey: SignaturePublicKey, -{ - match action { - RSAAction::Sign => { - let sk_bytes = require_file(skfile, "skfile"); - let sk = parse_sk::(&sk_bytes, alg_name); - let msg = read_all_stdin(); - let sig = sign(&sk, &msg).unwrap_or_else(|_| { - eprintln!("Error: signing failed."); - exit(-1); - }); - write_bytes_or_hex(&sig, output_hex); - } - RSAAction::Verify => { - do_verify::(verify, pkfile, sigfile, alg_name) - } - } -} - -/// RSASSA-PSS (randomized: `sign` draws a fresh salt from a [`DefaultRNG`] each call), covering -/// both the MGF1-based scheme (RFC 8017 §8.1) and the SHAKE-native one (RFC 8702 §3.2.1) -- their -/// `sign`/`verify` function shapes are identical, only the concrete function passed in differs. -#[allow(clippy::too_many_arguments)] -fn rsa_pss_cmd< - const HALF: usize, - const L: usize, - const HALF_BYTES: usize, const SK_LEN: usize, - const N_BYTES: usize, - const PK_LEN: usize, const SIG_LEN: usize, >( action: &RSAAction, - sign: PssSignFn, - verify: VerifyFn, skfile: &Option, pkfile: &Option, sigfile: &Option, output_hex: bool, alg_name: &str, -) where - RsaPrivateKey: SignaturePrivateKey, - RsaPublicKey: SignaturePublicKey, -{ +) { match action { RSAAction::Sign => { - let sk_bytes = require_file(skfile, "skfile"); - let sk = parse_sk::(&sk_bytes, alg_name); - let msg = read_all_stdin(); - let mut rng = DefaultRNG::default(); - let sig = sign(&sk, &msg, &mut rng).unwrap_or_else(|_| { + let sk = parse_sk::(&require_file(skfile, "skfile"), alg_name); + + // `sign_init` is infallible for every `bouncycastle_rsa` signer (see `do_verify`). + let mut signer = S::sign_init(&sk, None).unwrap(); + stream_stdin_into(|chunk| signer.sign_update(chunk)); + let sig = signer.sign_final().unwrap_or_else(|_| { eprintln!("Error: signing failed."); exit(-1); }); + write_bytes_or_hex(&sig, output_hex); } - RSAAction::Verify => { - do_verify::(verify, pkfile, sigfile, alg_name) - } + RSAAction::Verify => do_verify::(pkfile, sigfile, alg_name), } } -/// RSA-1024: verification only (see module docs). `L = 16`, `N_BYTES = 128`, `PK_LEN = 132`, -/// `SIG_LEN = 128`. No SHA-512 or PSS group exists in Wycheproof at this size (see -/// `bouncycastle_rsa::rsa_1024`'s own docs), so neither is wired up here either. +/// RSA-1024: verification only (see module docs). No SHA-512 or PSS group exists in Wycheproof at +/// this size (see `bouncycastle_rsa::rsa_1024`'s own docs), so neither is wired up here either. pub(crate) fn rsa_1024_cmd( scheme: &RSAScheme, hash: &RSAHash, pkfile: &Option, sigfile: &Option, ) { - use bouncycastle::rsa::rsa_1024::{pkcs1_v1_5_verify_sha256, pkcs1_v1_5_verify_sha384}; + use rsa_1024::{ + PK_LEN, RSASSA_PKCS1_v1_5_SHA256, RSASSA_PKCS1_v1_5_SHA384, Rsa1024PublicKey, SIG_LEN, + }; match (scheme, hash) { - (RSAScheme::Pkcs1v15, RSAHash::Sha256) => do_verify::<16, 128, 132, 128>( - pkcs1_v1_5_verify_sha256, - pkfile, - sigfile, - "RSA-1024/PKCS#1v1.5/SHA-256", - ), - (RSAScheme::Pkcs1v15, RSAHash::Sha384) => do_verify::<16, 128, 132, 128>( - pkcs1_v1_5_verify_sha384, - pkfile, - sigfile, - "RSA-1024/PKCS#1v1.5/SHA-384", - ), + (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"), } } -/// RSA-1536: verification only (see module docs). `L = 24`, `N_BYTES = 192`, `PK_LEN = 196`, -/// `SIG_LEN = 192`. No PSS group exists in Wycheproof at this size. +/// RSA-1536: verification only (see module docs). No PSS group exists in Wycheproof at this size. pub(crate) fn rsa_1536_cmd( scheme: &RSAScheme, hash: &RSAHash, pkfile: &Option, sigfile: &Option, ) { - use bouncycastle::rsa::rsa_1536::{ - pkcs1_v1_5_verify_sha256, pkcs1_v1_5_verify_sha384, pkcs1_v1_5_verify_sha512, + use rsa_1536::{ + PK_LEN, RSASSA_PKCS1_v1_5_SHA256, RSASSA_PKCS1_v1_5_SHA384, RSASSA_PKCS1_v1_5_SHA512, + Rsa1536PublicKey, SIG_LEN, }; match (scheme, hash) { - (RSAScheme::Pkcs1v15, RSAHash::Sha256) => do_verify::<24, 192, 196, 192>( - pkcs1_v1_5_verify_sha256, - pkfile, - sigfile, - "RSA-1536/PKCS#1v1.5/SHA-256", - ), - (RSAScheme::Pkcs1v15, RSAHash::Sha384) => do_verify::<24, 192, 196, 192>( - pkcs1_v1_5_verify_sha384, - pkfile, - sigfile, - "RSA-1536/PKCS#1v1.5/SHA-384", - ), - (RSAScheme::Pkcs1v15, RSAHash::Sha512) => do_verify::<24, 192, 196, 192>( - pkcs1_v1_5_verify_sha512, - pkfile, - sigfile, - "RSA-1536/PKCS#1v1.5/SHA-512", - ), + (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: sign and verify. `HALF = 16`, `L = 32`, `HALF_BYTES = 128`, `SK_LEN = 640`, `N_BYTES -/// = 256`, `PK_LEN = 260`, `SIG_LEN = 256`. `--hash shake128` is the only SHAKE choice wired up at -/// this size (RFC 8702 §5 pairs SHAKE128 with 2048/3072-bit RSA, SHAKE256 with 4096-bit or -/// larger). +/// RSA-2048: sign and verify. `--hash shake128` is the only SHAKE choice wired up at this size +/// (RFC 8702 §5 pairs SHAKE128 with 2048/3072-bit RSA, SHAKE256 with 4096-bit or larger). #[allow(clippy::too_many_arguments)] pub(crate) fn rsa_2048_cmd( action: &RSAAction, @@ -326,66 +277,51 @@ pub(crate) fn rsa_2048_cmd( sigfile: &Option, output_hex: bool, ) { - use bouncycastle::rsa::rsa_2048::{ - pkcs1_v1_5_sign_sha256, pkcs1_v1_5_sign_sha384, pkcs1_v1_5_sign_sha512, - pkcs1_v1_5_verify_sha256, pkcs1_v1_5_verify_sha384, pkcs1_v1_5_verify_sha512, - pss_shake128_sign, pss_shake128_verify, pss_sign_sha256, pss_sign_sha384, pss_sign_sha512, - pss_verify_sha256, pss_verify_sha384, pss_verify_sha512, + 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, + Rsa2048PrivateKey as SK, Rsa2048PublicKey as PK, SIG_LEN, SK_LEN, }; + let args = (skfile, pkfile, sigfile, output_hex); + let run = + |name: &str, + f: fn(&RSAAction, &Option, &Option, &Option, bool, &str)| { + f(action, args.0, args.1, args.2, args.3, name) + }; match (scheme, hash) { - (RSAScheme::Pkcs1v15, RSAHash::Sha256) => rsa_pkcs1_cmd::<16, 32, 128, 640, 256, 260, 256>( - action, - pkcs1_v1_5_sign_sha256, - pkcs1_v1_5_verify_sha256, - skfile, - pkfile, - sigfile, - output_hex, + (RSAScheme::Pkcs1v15, RSAHash::Sha256) => run( "RSA-2048/PKCS#1v1.5/SHA-256", + rsa_sign_verify_cmd::, ), - (RSAScheme::Pkcs1v15, RSAHash::Sha384) => rsa_pkcs1_cmd::<16, 32, 128, 640, 256, 260, 256>( - action, - pkcs1_v1_5_sign_sha384, - pkcs1_v1_5_verify_sha384, - skfile, - pkfile, - sigfile, - output_hex, + (RSAScheme::Pkcs1v15, RSAHash::Sha384) => run( "RSA-2048/PKCS#1v1.5/SHA-384", + rsa_sign_verify_cmd::, ), - (RSAScheme::Pkcs1v15, RSAHash::Sha512) => rsa_pkcs1_cmd::<16, 32, 128, 640, 256, 260, 256>( - action, - pkcs1_v1_5_sign_sha512, - pkcs1_v1_5_verify_sha512, - skfile, - pkfile, - sigfile, - output_hex, + (RSAScheme::Pkcs1v15, RSAHash::Sha512) => run( "RSA-2048/PKCS#1v1.5/SHA-512", + rsa_sign_verify_cmd::, ), - (RSAScheme::Pss, RSAHash::Sha256) => rsa_pss_cmd::<16, 32, 128, 640, 256, 260, 256>( - action, pss_sign_sha256, pss_verify_sha256, skfile, pkfile, sigfile, output_hex, + (RSAScheme::Pss, RSAHash::Sha256) => run( "RSA-2048/PSS/SHA-256", + rsa_sign_verify_cmd::, ), - (RSAScheme::Pss, RSAHash::Sha384) => rsa_pss_cmd::<16, 32, 128, 640, 256, 260, 256>( - action, pss_sign_sha384, pss_verify_sha384, skfile, pkfile, sigfile, output_hex, + (RSAScheme::Pss, RSAHash::Sha384) => run( "RSA-2048/PSS/SHA-384", + rsa_sign_verify_cmd::, ), - (RSAScheme::Pss, RSAHash::Sha512) => rsa_pss_cmd::<16, 32, 128, 640, 256, 260, 256>( - action, pss_sign_sha512, pss_verify_sha512, skfile, pkfile, sigfile, output_hex, + (RSAScheme::Pss, RSAHash::Sha512) => run( "RSA-2048/PSS/SHA-512", + rsa_sign_verify_cmd::, ), - (RSAScheme::Pss, RSAHash::Shake128) => rsa_pss_cmd::<16, 32, 128, 640, 256, 260, 256>( - action, pss_shake128_sign, pss_shake128_verify, skfile, pkfile, sigfile, output_hex, + (RSAScheme::Pss, RSAHash::Shake128) => run( "RSA-2048/PSS-SHAKE128", + rsa_sign_verify_cmd::, ), (scheme, hash) => unsupported(scheme, hash, "RSA-2048"), } } -/// RSA-3072: sign and verify. `HALF = 24`, `L = 48`, `HALF_BYTES = 192`, `SK_LEN = 960`, `N_BYTES -/// = 384`, `PK_LEN = 388`, `SIG_LEN = 384`. See [`rsa_2048_cmd`] for the SHAKE128 pairing -/// rationale. +/// RSA-3072: sign and verify. See [`rsa_2048_cmd`] for the SHAKE128 pairing rationale. #[allow(clippy::too_many_arguments)] pub(crate) fn rsa_3072_cmd( action: &RSAAction, @@ -396,66 +332,52 @@ pub(crate) fn rsa_3072_cmd( sigfile: &Option, output_hex: bool, ) { - use bouncycastle::rsa::rsa_3072::{ - pkcs1_v1_5_sign_sha256, pkcs1_v1_5_sign_sha384, pkcs1_v1_5_sign_sha512, - pkcs1_v1_5_verify_sha256, pkcs1_v1_5_verify_sha384, pkcs1_v1_5_verify_sha512, - pss_shake128_sign, pss_shake128_verify, pss_sign_sha256, pss_sign_sha384, pss_sign_sha512, - pss_verify_sha256, pss_verify_sha384, pss_verify_sha512, + 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, + Rsa3072PrivateKey as SK, Rsa3072PublicKey as PK, SIG_LEN, SK_LEN, }; + let args = (skfile, pkfile, sigfile, output_hex); + let run = + |name: &str, + f: fn(&RSAAction, &Option, &Option, &Option, bool, &str)| { + f(action, args.0, args.1, args.2, args.3, name) + }; match (scheme, hash) { - (RSAScheme::Pkcs1v15, RSAHash::Sha256) => rsa_pkcs1_cmd::<24, 48, 192, 960, 384, 388, 384>( - action, - pkcs1_v1_5_sign_sha256, - pkcs1_v1_5_verify_sha256, - skfile, - pkfile, - sigfile, - output_hex, + (RSAScheme::Pkcs1v15, RSAHash::Sha256) => run( "RSA-3072/PKCS#1v1.5/SHA-256", + rsa_sign_verify_cmd::, ), - (RSAScheme::Pkcs1v15, RSAHash::Sha384) => rsa_pkcs1_cmd::<24, 48, 192, 960, 384, 388, 384>( - action, - pkcs1_v1_5_sign_sha384, - pkcs1_v1_5_verify_sha384, - skfile, - pkfile, - sigfile, - output_hex, + (RSAScheme::Pkcs1v15, RSAHash::Sha384) => run( "RSA-3072/PKCS#1v1.5/SHA-384", + rsa_sign_verify_cmd::, ), - (RSAScheme::Pkcs1v15, RSAHash::Sha512) => rsa_pkcs1_cmd::<24, 48, 192, 960, 384, 388, 384>( - action, - pkcs1_v1_5_sign_sha512, - pkcs1_v1_5_verify_sha512, - skfile, - pkfile, - sigfile, - output_hex, + (RSAScheme::Pkcs1v15, RSAHash::Sha512) => run( "RSA-3072/PKCS#1v1.5/SHA-512", + rsa_sign_verify_cmd::, ), - (RSAScheme::Pss, RSAHash::Sha256) => rsa_pss_cmd::<24, 48, 192, 960, 384, 388, 384>( - action, pss_sign_sha256, pss_verify_sha256, skfile, pkfile, sigfile, output_hex, + (RSAScheme::Pss, RSAHash::Sha256) => run( "RSA-3072/PSS/SHA-256", + rsa_sign_verify_cmd::, ), - (RSAScheme::Pss, RSAHash::Sha384) => rsa_pss_cmd::<24, 48, 192, 960, 384, 388, 384>( - action, pss_sign_sha384, pss_verify_sha384, skfile, pkfile, sigfile, output_hex, + (RSAScheme::Pss, RSAHash::Sha384) => run( "RSA-3072/PSS/SHA-384", + rsa_sign_verify_cmd::, ), - (RSAScheme::Pss, RSAHash::Sha512) => rsa_pss_cmd::<24, 48, 192, 960, 384, 388, 384>( - action, pss_sign_sha512, pss_verify_sha512, skfile, pkfile, sigfile, output_hex, + (RSAScheme::Pss, RSAHash::Sha512) => run( "RSA-3072/PSS/SHA-512", + rsa_sign_verify_cmd::, ), - (RSAScheme::Pss, RSAHash::Shake128) => rsa_pss_cmd::<24, 48, 192, 960, 384, 388, 384>( - action, pss_shake128_sign, pss_shake128_verify, skfile, pkfile, sigfile, output_hex, + (RSAScheme::Pss, RSAHash::Shake128) => run( "RSA-3072/PSS-SHAKE128", + rsa_sign_verify_cmd::, ), (scheme, hash) => unsupported(scheme, hash, "RSA-3072"), } } -/// RSA-4096: sign and verify. `HALF = 32`, `L = 64`, `HALF_BYTES = 256`, `SK_LEN = 1280`, `N_BYTES -/// = 512`, `PK_LEN = 516`, `SIG_LEN = 512`. `--hash shake256` (not shake128) is wired up at this -/// size -- see [`rsa_2048_cmd`] for the pairing rationale. +/// RSA-4096: sign and verify. `--hash shake256` (not shake128) is wired up at this size -- see +/// [`rsa_2048_cmd`] for the pairing rationale. #[allow(clippy::too_many_arguments)] pub(crate) fn rsa_4096_cmd( action: &RSAAction, @@ -466,73 +388,53 @@ pub(crate) fn rsa_4096_cmd( sigfile: &Option, output_hex: bool, ) { - use bouncycastle::rsa::rsa_4096::{ - pkcs1_v1_5_sign_sha256, pkcs1_v1_5_sign_sha384, pkcs1_v1_5_sign_sha512, - pkcs1_v1_5_verify_sha256, pkcs1_v1_5_verify_sha384, pkcs1_v1_5_verify_sha512, - pss_shake256_sign, pss_shake256_verify, pss_sign_sha256, pss_sign_sha384, pss_sign_sha512, - pss_verify_sha256, pss_verify_sha384, pss_verify_sha512, + 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, + Rsa4096PrivateKey as SK, Rsa4096PublicKey as PK, SIG_LEN, SK_LEN, }; + let args = (skfile, pkfile, sigfile, output_hex); + let run = + |name: &str, + f: fn(&RSAAction, &Option, &Option, &Option, bool, &str)| { + f(action, args.0, args.1, args.2, args.3, name) + }; match (scheme, hash) { - (RSAScheme::Pkcs1v15, RSAHash::Sha256) => { - rsa_pkcs1_cmd::<32, 64, 256, 1280, 512, 516, 512>( - action, - pkcs1_v1_5_sign_sha256, - pkcs1_v1_5_verify_sha256, - skfile, - pkfile, - sigfile, - output_hex, - "RSA-4096/PKCS#1v1.5/SHA-256", - ) - } - (RSAScheme::Pkcs1v15, RSAHash::Sha384) => { - rsa_pkcs1_cmd::<32, 64, 256, 1280, 512, 516, 512>( - action, - pkcs1_v1_5_sign_sha384, - pkcs1_v1_5_verify_sha384, - skfile, - pkfile, - sigfile, - output_hex, - "RSA-4096/PKCS#1v1.5/SHA-384", - ) - } - (RSAScheme::Pkcs1v15, RSAHash::Sha512) => { - rsa_pkcs1_cmd::<32, 64, 256, 1280, 512, 516, 512>( - action, - pkcs1_v1_5_sign_sha512, - pkcs1_v1_5_verify_sha512, - skfile, - pkfile, - sigfile, - output_hex, - "RSA-4096/PKCS#1v1.5/SHA-512", - ) - } - (RSAScheme::Pss, RSAHash::Sha256) => rsa_pss_cmd::<32, 64, 256, 1280, 512, 516, 512>( - action, pss_sign_sha256, pss_verify_sha256, skfile, pkfile, sigfile, output_hex, + (RSAScheme::Pkcs1v15, RSAHash::Sha256) => run( + "RSA-4096/PKCS#1v1.5/SHA-256", + rsa_sign_verify_cmd::, + ), + (RSAScheme::Pkcs1v15, RSAHash::Sha384) => run( + "RSA-4096/PKCS#1v1.5/SHA-384", + rsa_sign_verify_cmd::, + ), + (RSAScheme::Pkcs1v15, RSAHash::Sha512) => run( + "RSA-4096/PKCS#1v1.5/SHA-512", + rsa_sign_verify_cmd::, + ), + (RSAScheme::Pss, RSAHash::Sha256) => run( "RSA-4096/PSS/SHA-256", + rsa_sign_verify_cmd::, ), - (RSAScheme::Pss, RSAHash::Sha384) => rsa_pss_cmd::<32, 64, 256, 1280, 512, 516, 512>( - action, pss_sign_sha384, pss_verify_sha384, skfile, pkfile, sigfile, output_hex, + (RSAScheme::Pss, RSAHash::Sha384) => run( "RSA-4096/PSS/SHA-384", + rsa_sign_verify_cmd::, ), - (RSAScheme::Pss, RSAHash::Sha512) => rsa_pss_cmd::<32, 64, 256, 1280, 512, 516, 512>( - action, pss_sign_sha512, pss_verify_sha512, skfile, pkfile, sigfile, output_hex, + (RSAScheme::Pss, RSAHash::Sha512) => run( "RSA-4096/PSS/SHA-512", + rsa_sign_verify_cmd::, ), - (RSAScheme::Pss, RSAHash::Shake256) => rsa_pss_cmd::<32, 64, 256, 1280, 512, 516, 512>( - action, pss_shake256_sign, pss_shake256_verify, skfile, pkfile, sigfile, output_hex, + (RSAScheme::Pss, RSAHash::Shake256) => run( "RSA-4096/PSS-SHAKE256", + rsa_sign_verify_cmd::, ), (scheme, hash) => unsupported(scheme, hash, "RSA-4096"), } } -/// RSA-8192: sign and verify. `HALF = 64`, `L = 128`, `HALF_BYTES = 512`, `SK_LEN = 2560`, -/// `N_BYTES = 1024`, `PK_LEN = 1028`, `SIG_LEN = 1024`. No PSS-SHAKE variant is wired up at this -/// size: no Wycheproof vectors exist for it, and RFC 8702 §5 does not name a pairing beyond -/// "4096-bit or larger" for SHAKE256 -- 4096 already covers that recommendation. +/// RSA-8192: sign and verify. No PSS-SHAKE variant is wired up at this size: no Wycheproof +/// vectors exist for it, and RFC 8702 §5 does not name a pairing beyond "4096-bit or larger" for +/// SHAKE256 -- 4096 already covers that recommendation. #[allow(clippy::too_many_arguments)] pub(crate) fn rsa_8192_cmd( action: &RSAAction, @@ -543,60 +445,41 @@ pub(crate) fn rsa_8192_cmd( sigfile: &Option, output_hex: bool, ) { - use bouncycastle::rsa::rsa_8192::{ - pkcs1_v1_5_sign_sha256, pkcs1_v1_5_sign_sha384, pkcs1_v1_5_sign_sha512, - pkcs1_v1_5_verify_sha256, pkcs1_v1_5_verify_sha384, pkcs1_v1_5_verify_sha512, - pss_sign_sha256, pss_sign_sha384, pss_sign_sha512, pss_verify_sha256, pss_verify_sha384, - pss_verify_sha512, + 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, Rsa8192PrivateKey as SK, + Rsa8192PublicKey as PK, SIG_LEN, SK_LEN, }; + let args = (skfile, pkfile, sigfile, output_hex); + let run = + |name: &str, + f: fn(&RSAAction, &Option, &Option, &Option, bool, &str)| { + f(action, args.0, args.1, args.2, args.3, name) + }; match (scheme, hash) { - (RSAScheme::Pkcs1v15, RSAHash::Sha256) => { - rsa_pkcs1_cmd::<64, 128, 512, 2560, 1024, 1028, 1024>( - action, - pkcs1_v1_5_sign_sha256, - pkcs1_v1_5_verify_sha256, - skfile, - pkfile, - sigfile, - output_hex, - "RSA-8192/PKCS#1v1.5/SHA-256", - ) - } - (RSAScheme::Pkcs1v15, RSAHash::Sha384) => { - rsa_pkcs1_cmd::<64, 128, 512, 2560, 1024, 1028, 1024>( - action, - pkcs1_v1_5_sign_sha384, - pkcs1_v1_5_verify_sha384, - skfile, - pkfile, - sigfile, - output_hex, - "RSA-8192/PKCS#1v1.5/SHA-384", - ) - } - (RSAScheme::Pkcs1v15, RSAHash::Sha512) => { - rsa_pkcs1_cmd::<64, 128, 512, 2560, 1024, 1028, 1024>( - action, - pkcs1_v1_5_sign_sha512, - pkcs1_v1_5_verify_sha512, - skfile, - pkfile, - sigfile, - output_hex, - "RSA-8192/PKCS#1v1.5/SHA-512", - ) - } - (RSAScheme::Pss, RSAHash::Sha256) => rsa_pss_cmd::<64, 128, 512, 2560, 1024, 1028, 1024>( - action, pss_sign_sha256, pss_verify_sha256, skfile, pkfile, sigfile, output_hex, + (RSAScheme::Pkcs1v15, RSAHash::Sha256) => run( + "RSA-8192/PKCS#1v1.5/SHA-256", + rsa_sign_verify_cmd::, + ), + (RSAScheme::Pkcs1v15, RSAHash::Sha384) => run( + "RSA-8192/PKCS#1v1.5/SHA-384", + rsa_sign_verify_cmd::, + ), + (RSAScheme::Pkcs1v15, RSAHash::Sha512) => run( + "RSA-8192/PKCS#1v1.5/SHA-512", + rsa_sign_verify_cmd::, + ), + (RSAScheme::Pss, RSAHash::Sha256) => run( "RSA-8192/PSS/SHA-256", + rsa_sign_verify_cmd::, ), - (RSAScheme::Pss, RSAHash::Sha384) => rsa_pss_cmd::<64, 128, 512, 2560, 1024, 1028, 1024>( - action, pss_sign_sha384, pss_verify_sha384, skfile, pkfile, sigfile, output_hex, + (RSAScheme::Pss, RSAHash::Sha384) => run( "RSA-8192/PSS/SHA-384", + rsa_sign_verify_cmd::, ), - (RSAScheme::Pss, RSAHash::Sha512) => rsa_pss_cmd::<64, 128, 512, 2560, 1024, 1028, 1024>( - action, pss_sign_sha512, pss_verify_sha512, skfile, pkfile, sigfile, output_hex, + (RSAScheme::Pss, RSAHash::Sha512) => run( "RSA-8192/PSS/SHA-512", + rsa_sign_verify_cmd::, ), (scheme, hash) => unsupported(scheme, hash, "RSA-8192"), } diff --git a/cli/tests/rsa_cli_tests.rs b/cli/tests/rsa_cli_tests.rs new file mode 100644 index 00000000..a7b7bad1 --- /dev/null +++ b/cli/tests/rsa_cli_tests.rs @@ -0,0 +1,311 @@ +//! 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 +//! `SignatureVerifier` 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::traits::{ + SignaturePrivateKey, SignaturePublicKey, SignatureVerifier, Signer, +}; +use bouncycastle::rsa::rsa_2048::{ + PK_LEN, RSASSA_PKCS1_v1_5_SHA256, RSASSA_PSS_SHA256, RSASSA_PSS_SHAKE128, Rsa2048PrivateKey, + Rsa2048PublicKey, SIG_LEN, +}; +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() +} + +fn sk_2048() -> Rsa2048PrivateKey { + Rsa2048PrivateKey::from_bytes(&unhex(SK_2048_HEX)).expect("the documented key decodes") +} + +fn pk_2048() -> Rsa2048PublicKey { + Rsa2048PublicKey::from_bytes(&unhex(PK_2048_HEX)).expect("the documented key decodes") +} + +/// The CLI accepts key and signature files as hex (as written here) or binary. +fn rsa_2048_sign(scheme: &str, hash: &str, msg: &[u8]) -> Vec { + let skfile = temp_file("sk", SK_2048_HEX.as_bytes()); + 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", PK_2048_HEX.as_bytes()); + 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", PK_1024_HEX.as_bytes()); + let sigfile = temp_file("sig1024", SIG_1024_HEX.as_bytes()); + 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 = RSASSA_PKCS1_v1_5_SHA256::sign(&sk_2048(), &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", SK_2048_HEX.as_bytes()); + 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 `SignatureVerifier` `V` and through the CLI. +fn pss_case>(hash: &str, msg: &[u8]) { + let pk = pk_2048(); + 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] { + V::verify(&pk, 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", PK_1024_HEX.as_bytes()); + let sigfile = temp_file("sig1024", SIG_1024_HEX.as_bytes()); + 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", SK_2048_HEX.as_bytes()); + let err = run_err( + &["rsa-2048", "sign", "--scheme", "pss", "--hash", "shake256", "--skfile", &skfile], + b"msg", + ); + assert!(err.contains("not supported"), "stderr: {err}"); +} From c84e7a6046d57c5125e51235b9d7ee4bd6ee359c Mon Sep 17 00:00:00 2001 From: David Hook Date: Mon, 21 Sep 2026 10:33:46 +1000 Subject: [PATCH 16/55] rsa: drop the per-size free-function API now that every pairing is a Signer/SignatureVerifier type, and add sign_randomized/set_signer_salt for the randomness control the free functions used to carry With the trait wiring in place, rsa_2048::pkcs1_v1_5_sign_sha256 and its 70-odd siblings across the six size modules (pkcs1_v1_5_sign_*/ _verify_*, pss_sign_*/_with_salt/_verify_*, pss_shake*_sign/ _with_salt/_verify) were exact duplicates of Signer::sign/ SignatureVerifier::verify on the RSASSA_* types -- two public spellings of one computation, which is not how this workspace's other signature crates (ECDSA, SM2, ML-DSA) present themselves. This removes them, and with them the message-taking generic sign/sign_with_salt/verify in the rsassa_* modules that only they called; the *_from_hash functions those modules keep are the one encoding path the trait impls use, and the pre-hash entry point for a caller that already holds the digest. The two things the free functions offered that the traits did not -- signing PSS with a caller's RNG, and with a fixed salt -- move onto the algorithm types in the shape the other crates use: RSASSA_PSS::sign_randomized(sk, msg, rng) as ECDSA/SM2's sign_randomized RSASSA_PSS::set_signer_salt(salt) on a streaming state, as ML-DSA's set_signer_rnd (and likewise on RSASSA_PSS_SHAKE). set_signer_salt makes the streaming path deterministic, which the free functions never offered: the fixed salt was one-shot only. sign_final uses the fixed salt if one was set and otherwise draws from DefaultRNG as before; a verify-initialised state ignores it. Callers migrated: every test (fixed-salt cases through a small sign_with_salt! test macro over sign_init/set_signer_salt/sign_final; the trait-versus-free-function cross-checks that became tautologies are removed, and the RSAVP1 range-error and fixed-salt checks now compare against the generic *_from_hash functions instead), the six criterion bench files (bench names unchanged), mem_usage_benches' RSA harness, and the crate docs (the trait example gains the two new methods; the RSA-1024 example goes through SignatureVerifier). The CLI already went through the traits (previous commit). New tests: set_signer_salt against sign_from_hash_with_salt and against an unfixed fresh signature, and sign_randomized against a fixed-output RNG (must equal the fixed-salt path over that RNG's bytes) and against DefaultRNG. ./dev_scripts/quality_stats.sh ./crypto/rsa: core code 3033 -> 2393 lines; fallibility unchanged in runtime code (the one "unwrap in core code" that disappears, 2 -> 1, was in the removed crate-docs example; 20 Err() as before). Co-Authored-By: Claude Fable 5.1 --- crypto/rsa/benches/rsa_1024_benches.rs | 9 +- crypto/rsa/benches/rsa_1536_benches.rs | 30 ++- crypto/rsa/benches/rsa_2048_benches.rs | 111 ++++++--- crypto/rsa/benches/rsa_3072_benches.rs | 111 ++++++--- crypto/rsa/benches/rsa_4096_benches.rs | 111 ++++++--- crypto/rsa/benches/rsa_8192_benches.rs | 91 +++++--- crypto/rsa/src/lib.rs | 91 +++----- crypto/rsa/src/rsa_1024.rs | 23 +- crypto/rsa/src/rsa_1536.rs | 31 --- crypto/rsa/src/rsa_2048.rs | 216 +----------------- crypto/rsa/src/rsa_3072.rs | 190 +-------------- crypto/rsa/src/rsa_4096.rs | 196 +--------------- crypto/rsa/src/rsa_8192.rs | 160 +------------ crypto/rsa/src/rsassa_pkcs1_v1_5.rs | 103 +++------ crypto/rsa/src/rsassa_pss.rs | 141 ++---------- crypto/rsa/src/rsassa_pss_shake.rs | 120 ++-------- crypto/rsa/tests/rsa_1024_tests.rs | 33 +-- crypto/rsa/tests/rsa_1536_tests.rs | 42 +--- ...rsa_2048_pkcs1_v1_5_sha384_sha512_tests.rs | 35 +-- crypto/rsa/tests/rsa_2048_pkcs1_v1_5_tests.rs | 122 +++------- .../tests/rsa_2048_pss_sha384_sha512_tests.rs | 62 +++-- .../rsa/tests/rsa_2048_pss_shake128_tests.rs | 80 ++++--- crypto/rsa/tests/rsa_2048_pss_tests.rs | 81 ++++--- .../rsa/tests/rsa_3072_pss_shake128_tests.rs | 41 ++-- crypto/rsa/tests/rsa_3072_tests.rs | 110 ++++----- .../rsa/tests/rsa_4096_pss_shake256_tests.rs | 45 ++-- crypto/rsa/tests/rsa_4096_tests.rs | 127 +++++----- crypto/rsa/tests/rsa_8192_tests.rs | 127 +++++----- mem_usage_benches/src/bench_rsa_mem_usage.rs | 15 +- 29 files changed, 887 insertions(+), 1767 deletions(-) diff --git a/crypto/rsa/benches/rsa_1024_benches.rs b/crypto/rsa/benches/rsa_1024_benches.rs index e0af7879..bf844d54 100644 --- a/crypto/rsa/benches/rsa_1024_benches.rs +++ b/crypto/rsa/benches/rsa_1024_benches.rs @@ -3,12 +3,13 @@ //! `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::traits::SignatureVerifier; use criterion::{Criterion, criterion_group, criterion_main}; use std::hint::black_box; use bouncycastle_hex::decode as hex_decode; use bouncycastle_rsa::rsa_1024::{ - Rsa1024PublicKey, pkcs1_v1_5_verify_sha256, pkcs1_v1_5_verify_sha384, + RSASSA_PKCS1_v1_5_SHA256, RSASSA_PKCS1_v1_5_SHA384, Rsa1024PublicKey, }; fn bench_rsa_1024(c: &mut Criterion) { @@ -45,9 +46,10 @@ fn bench_rsa_1024(c: &mut Criterion) { let mut group = c.benchmark_group("rsa_1024"); group.bench_function("pkcs1v15_verify_sha256", |b| { b.iter(|| { - pkcs1_v1_5_verify_sha256( + RSASSA_PKCS1_v1_5_SHA256::verify( black_box(&pk_sha256), black_box(&msg_sha256), + None, black_box(&sig_sha256), ) .unwrap() @@ -55,9 +57,10 @@ fn bench_rsa_1024(c: &mut Criterion) { }); group.bench_function("pkcs1v15_verify_sha384", |b| { b.iter(|| { - pkcs1_v1_5_verify_sha384( + RSASSA_PKCS1_v1_5_SHA384::verify( black_box(&pk_sha384), black_box(&msg_sha384), + None, black_box(&sig_sha384), ) .unwrap() diff --git a/crypto/rsa/benches/rsa_1536_benches.rs b/crypto/rsa/benches/rsa_1536_benches.rs index 314054ec..84734678 100644 --- a/crypto/rsa/benches/rsa_1536_benches.rs +++ b/crypto/rsa/benches/rsa_1536_benches.rs @@ -3,12 +3,13 @@ //! `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::traits::SignatureVerifier; use criterion::{Criterion, criterion_group, criterion_main}; use std::hint::black_box; use bouncycastle_hex::decode as hex_decode; use bouncycastle_rsa::rsa_1536::{ - Rsa1536PublicKey, pkcs1_v1_5_verify_sha256, pkcs1_v1_5_verify_sha384, pkcs1_v1_5_verify_sha512, + RSASSA_PKCS1_v1_5_SHA256, RSASSA_PKCS1_v1_5_SHA384, RSASSA_PKCS1_v1_5_SHA512, Rsa1536PublicKey, }; fn bench_rsa_1536(c: &mut Criterion) { @@ -64,20 +65,35 @@ fn bench_rsa_1536(c: &mut Criterion) { let mut group = c.benchmark_group("rsa_1536"); group.bench_function("pkcs1v15_verify_sha256", |b| { b.iter(|| { - pkcs1_v1_5_verify_sha256(black_box(&pk_sha256), black_box(&msg), black_box(&sig_sha256)) - .unwrap() + RSASSA_PKCS1_v1_5_SHA256::verify( + black_box(&pk_sha256), + black_box(&msg), + None, + black_box(&sig_sha256), + ) + .unwrap() }) }); group.bench_function("pkcs1v15_verify_sha384", |b| { b.iter(|| { - pkcs1_v1_5_verify_sha384(black_box(&pk_sha384), black_box(&msg), black_box(&sig_sha384)) - .unwrap() + RSASSA_PKCS1_v1_5_SHA384::verify( + black_box(&pk_sha384), + black_box(&msg), + None, + black_box(&sig_sha384), + ) + .unwrap() }) }); group.bench_function("pkcs1v15_verify_sha512", |b| { b.iter(|| { - pkcs1_v1_5_verify_sha512(black_box(&pk_sha512), black_box(&msg), black_box(&sig_sha512)) - .unwrap() + RSASSA_PKCS1_v1_5_SHA512::verify( + black_box(&pk_sha512), + black_box(&msg), + None, + black_box(&sig_sha512), + ) + .unwrap() }) }); group.finish(); diff --git a/crypto/rsa/benches/rsa_2048_benches.rs b/crypto/rsa/benches/rsa_2048_benches.rs index 169a097b..f979d920 100644 --- a/crypto/rsa/benches/rsa_2048_benches.rs +++ b/crypto/rsa/benches/rsa_2048_benches.rs @@ -4,15 +4,15 @@ //! 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::traits::{SignatureVerifier, Signer}; use criterion::{Criterion, criterion_group, criterion_main}; use std::hint::black_box; use bouncycastle_rng::DefaultRNG; use bouncycastle_rsa::rsa_2048::{ - Rsa2048PrivateKey, Rsa2048PublicKey, pkcs1_v1_5_sign_sha256, pkcs1_v1_5_sign_sha384, - pkcs1_v1_5_sign_sha512, pkcs1_v1_5_verify_sha256, pkcs1_v1_5_verify_sha384, - pkcs1_v1_5_verify_sha512, pss_shake128_sign, pss_shake128_verify, pss_sign_sha256, - pss_sign_sha384, pss_sign_sha512, pss_verify_sha256, pss_verify_sha384, pss_verify_sha512, + 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, + Rsa2048PrivateKey, Rsa2048PublicKey, }; const MSG: &[u8] = b"a representative message for benchmarking RSA-2048"; @@ -57,94 +57,139 @@ fn bench_rsa_2048(c: &mut Criterion) { let pk = Rsa2048PublicKey::new(sk.n(), 0x10001).unwrap(); let mut rng = DefaultRNG::default(); - let sig_pkcs1_256 = pkcs1_v1_5_sign_sha256(&sk, MSG).unwrap(); - let sig_pkcs1_384 = pkcs1_v1_5_sign_sha384(&sk, MSG).unwrap(); - let sig_pkcs1_512 = pkcs1_v1_5_sign_sha512(&sk, MSG).unwrap(); - let sig_pss_256 = pss_sign_sha256(&sk, MSG, &mut rng).unwrap(); - let sig_pss_384 = pss_sign_sha384(&sk, MSG, &mut rng).unwrap(); - let sig_pss_512 = pss_sign_sha512(&sk, MSG, &mut rng).unwrap(); - let sig_pss_shake128 = pss_shake128_sign(&sk, MSG, &mut rng).unwrap(); + let sig_pkcs1_256 = RSASSA_PKCS1_v1_5_SHA256::sign(&sk, MSG, None).unwrap(); + let sig_pkcs1_384 = RSASSA_PKCS1_v1_5_SHA384::sign(&sk, MSG, None).unwrap(); + let sig_pkcs1_512 = RSASSA_PKCS1_v1_5_SHA512::sign(&sk, MSG, None).unwrap(); + let sig_pss_256 = RSASSA_PSS_SHA256::sign_randomized(&sk, MSG, &mut rng).unwrap(); + let sig_pss_384 = RSASSA_PSS_SHA384::sign_randomized(&sk, MSG, &mut rng).unwrap(); + let sig_pss_512 = RSASSA_PSS_SHA512::sign_randomized(&sk, MSG, &mut rng).unwrap(); + let sig_pss_shake128 = RSASSA_PSS_SHAKE128::sign_randomized(&sk, MSG, &mut rng).unwrap(); let mut group = c.benchmark_group("rsa_2048"); group.bench_function("pkcs1v15_sign_sha256", |b| { - b.iter(|| black_box(pkcs1_v1_5_sign_sha256(black_box(&sk), black_box(MSG)).unwrap())) + b.iter(|| { + black_box(RSASSA_PKCS1_v1_5_SHA256::sign(black_box(&sk), black_box(MSG), None).unwrap()) + }) }); group.bench_function("pkcs1v15_verify_sha256", |b| { b.iter(|| { - pkcs1_v1_5_verify_sha256(black_box(&pk), black_box(MSG), black_box(&sig_pkcs1_256)) - .unwrap() + RSASSA_PKCS1_v1_5_SHA256::verify( + black_box(&pk), + black_box(MSG), + None, + black_box(&sig_pkcs1_256), + ) + .unwrap() }) }); group.bench_function("pkcs1v15_sign_sha384", |b| { - b.iter(|| black_box(pkcs1_v1_5_sign_sha384(black_box(&sk), black_box(MSG)).unwrap())) + b.iter(|| { + black_box(RSASSA_PKCS1_v1_5_SHA384::sign(black_box(&sk), black_box(MSG), None).unwrap()) + }) }); group.bench_function("pkcs1v15_verify_sha384", |b| { b.iter(|| { - pkcs1_v1_5_verify_sha384(black_box(&pk), black_box(MSG), black_box(&sig_pkcs1_384)) - .unwrap() + RSASSA_PKCS1_v1_5_SHA384::verify( + black_box(&pk), + black_box(MSG), + None, + black_box(&sig_pkcs1_384), + ) + .unwrap() }) }); group.bench_function("pkcs1v15_sign_sha512", |b| { - b.iter(|| black_box(pkcs1_v1_5_sign_sha512(black_box(&sk), black_box(MSG)).unwrap())) + b.iter(|| { + black_box(RSASSA_PKCS1_v1_5_SHA512::sign(black_box(&sk), black_box(MSG), None).unwrap()) + }) }); group.bench_function("pkcs1v15_verify_sha512", |b| { b.iter(|| { - pkcs1_v1_5_verify_sha512(black_box(&pk), black_box(MSG), black_box(&sig_pkcs1_512)) - .unwrap() + RSASSA_PKCS1_v1_5_SHA512::verify( + black_box(&pk), + black_box(MSG), + None, + black_box(&sig_pkcs1_512), + ) + .unwrap() }) }); group.bench_function("pss_sign_sha256", |b| { b.iter(|| { black_box( - pss_sign_sha256(black_box(&sk), black_box(MSG), &mut DefaultRNG::default()) - .unwrap(), + RSASSA_PSS_SHA256::sign_randomized( + black_box(&sk), + black_box(MSG), + &mut DefaultRNG::default(), + ) + .unwrap(), ) }) }); group.bench_function("pss_verify_sha256", |b| { b.iter(|| { - pss_verify_sha256(black_box(&pk), black_box(MSG), black_box(&sig_pss_256)).unwrap() + RSASSA_PSS_SHA256::verify(black_box(&pk), black_box(MSG), None, black_box(&sig_pss_256)) + .unwrap() }) }); group.bench_function("pss_sign_sha384", |b| { b.iter(|| { black_box( - pss_sign_sha384(black_box(&sk), black_box(MSG), &mut DefaultRNG::default()) - .unwrap(), + RSASSA_PSS_SHA384::sign_randomized( + black_box(&sk), + black_box(MSG), + &mut DefaultRNG::default(), + ) + .unwrap(), ) }) }); group.bench_function("pss_verify_sha384", |b| { b.iter(|| { - pss_verify_sha384(black_box(&pk), black_box(MSG), black_box(&sig_pss_384)).unwrap() + RSASSA_PSS_SHA384::verify(black_box(&pk), black_box(MSG), None, black_box(&sig_pss_384)) + .unwrap() }) }); group.bench_function("pss_sign_sha512", |b| { b.iter(|| { black_box( - pss_sign_sha512(black_box(&sk), black_box(MSG), &mut DefaultRNG::default()) - .unwrap(), + RSASSA_PSS_SHA512::sign_randomized( + black_box(&sk), + black_box(MSG), + &mut DefaultRNG::default(), + ) + .unwrap(), ) }) }); group.bench_function("pss_verify_sha512", |b| { b.iter(|| { - pss_verify_sha512(black_box(&pk), black_box(MSG), black_box(&sig_pss_512)).unwrap() + RSASSA_PSS_SHA512::verify(black_box(&pk), black_box(MSG), None, black_box(&sig_pss_512)) + .unwrap() }) }); group.bench_function("pss_sign_shake128", |b| { b.iter(|| { black_box( - pss_shake128_sign(black_box(&sk), black_box(MSG), &mut DefaultRNG::default()) - .unwrap(), + RSASSA_PSS_SHAKE128::sign_randomized( + black_box(&sk), + black_box(MSG), + &mut DefaultRNG::default(), + ) + .unwrap(), ) }) }); group.bench_function("pss_verify_shake128", |b| { b.iter(|| { - pss_shake128_verify(black_box(&pk), black_box(MSG), black_box(&sig_pss_shake128)) - .unwrap() + RSASSA_PSS_SHAKE128::verify( + black_box(&pk), + black_box(MSG), + None, + black_box(&sig_pss_shake128), + ) + .unwrap() }) }); diff --git a/crypto/rsa/benches/rsa_3072_benches.rs b/crypto/rsa/benches/rsa_3072_benches.rs index c4a877dd..fa873308 100644 --- a/crypto/rsa/benches/rsa_3072_benches.rs +++ b/crypto/rsa/benches/rsa_3072_benches.rs @@ -2,15 +2,15 @@ //! key is the same one `tests/rsa_3072_tests.rs` recovers from Wycheproof's //! `rsa_pkcs1_3072_sig_gen_test.json`. +use bouncycastle_core::traits::{SignatureVerifier, Signer}; use criterion::{Criterion, criterion_group, criterion_main}; use std::hint::black_box; use bouncycastle_rng::DefaultRNG; use bouncycastle_rsa::rsa_3072::{ - Rsa3072PrivateKey, Rsa3072PublicKey, pkcs1_v1_5_sign_sha256, pkcs1_v1_5_sign_sha384, - pkcs1_v1_5_sign_sha512, pkcs1_v1_5_verify_sha256, pkcs1_v1_5_verify_sha384, - pkcs1_v1_5_verify_sha512, pss_shake128_sign, pss_shake128_verify, pss_sign_sha256, - pss_sign_sha384, pss_sign_sha512, pss_verify_sha256, pss_verify_sha384, pss_verify_sha512, + 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, + Rsa3072PrivateKey, Rsa3072PublicKey, }; const MSG: &[u8] = b"a representative message for benchmarking RSA-3072"; @@ -65,94 +65,139 @@ fn bench_rsa_3072(c: &mut Criterion) { let pk = Rsa3072PublicKey::new(sk.n(), 0x10001).unwrap(); let mut rng = DefaultRNG::default(); - let sig_pkcs1_256 = pkcs1_v1_5_sign_sha256(&sk, MSG).unwrap(); - let sig_pkcs1_384 = pkcs1_v1_5_sign_sha384(&sk, MSG).unwrap(); - let sig_pkcs1_512 = pkcs1_v1_5_sign_sha512(&sk, MSG).unwrap(); - let sig_pss_256 = pss_sign_sha256(&sk, MSG, &mut rng).unwrap(); - let sig_pss_384 = pss_sign_sha384(&sk, MSG, &mut rng).unwrap(); - let sig_pss_512 = pss_sign_sha512(&sk, MSG, &mut rng).unwrap(); - let sig_pss_shake128 = pss_shake128_sign(&sk, MSG, &mut rng).unwrap(); + let sig_pkcs1_256 = RSASSA_PKCS1_v1_5_SHA256::sign(&sk, MSG, None).unwrap(); + let sig_pkcs1_384 = RSASSA_PKCS1_v1_5_SHA384::sign(&sk, MSG, None).unwrap(); + let sig_pkcs1_512 = RSASSA_PKCS1_v1_5_SHA512::sign(&sk, MSG, None).unwrap(); + let sig_pss_256 = RSASSA_PSS_SHA256::sign_randomized(&sk, MSG, &mut rng).unwrap(); + let sig_pss_384 = RSASSA_PSS_SHA384::sign_randomized(&sk, MSG, &mut rng).unwrap(); + let sig_pss_512 = RSASSA_PSS_SHA512::sign_randomized(&sk, MSG, &mut rng).unwrap(); + let sig_pss_shake128 = RSASSA_PSS_SHAKE128::sign_randomized(&sk, MSG, &mut rng).unwrap(); let mut group = c.benchmark_group("rsa_3072"); group.bench_function("pkcs1v15_sign_sha256", |b| { - b.iter(|| black_box(pkcs1_v1_5_sign_sha256(black_box(&sk), black_box(MSG)).unwrap())) + b.iter(|| { + black_box(RSASSA_PKCS1_v1_5_SHA256::sign(black_box(&sk), black_box(MSG), None).unwrap()) + }) }); group.bench_function("pkcs1v15_verify_sha256", |b| { b.iter(|| { - pkcs1_v1_5_verify_sha256(black_box(&pk), black_box(MSG), black_box(&sig_pkcs1_256)) - .unwrap() + RSASSA_PKCS1_v1_5_SHA256::verify( + black_box(&pk), + black_box(MSG), + None, + black_box(&sig_pkcs1_256), + ) + .unwrap() }) }); group.bench_function("pkcs1v15_sign_sha384", |b| { - b.iter(|| black_box(pkcs1_v1_5_sign_sha384(black_box(&sk), black_box(MSG)).unwrap())) + b.iter(|| { + black_box(RSASSA_PKCS1_v1_5_SHA384::sign(black_box(&sk), black_box(MSG), None).unwrap()) + }) }); group.bench_function("pkcs1v15_verify_sha384", |b| { b.iter(|| { - pkcs1_v1_5_verify_sha384(black_box(&pk), black_box(MSG), black_box(&sig_pkcs1_384)) - .unwrap() + RSASSA_PKCS1_v1_5_SHA384::verify( + black_box(&pk), + black_box(MSG), + None, + black_box(&sig_pkcs1_384), + ) + .unwrap() }) }); group.bench_function("pkcs1v15_sign_sha512", |b| { - b.iter(|| black_box(pkcs1_v1_5_sign_sha512(black_box(&sk), black_box(MSG)).unwrap())) + b.iter(|| { + black_box(RSASSA_PKCS1_v1_5_SHA512::sign(black_box(&sk), black_box(MSG), None).unwrap()) + }) }); group.bench_function("pkcs1v15_verify_sha512", |b| { b.iter(|| { - pkcs1_v1_5_verify_sha512(black_box(&pk), black_box(MSG), black_box(&sig_pkcs1_512)) - .unwrap() + RSASSA_PKCS1_v1_5_SHA512::verify( + black_box(&pk), + black_box(MSG), + None, + black_box(&sig_pkcs1_512), + ) + .unwrap() }) }); group.bench_function("pss_sign_sha256", |b| { b.iter(|| { black_box( - pss_sign_sha256(black_box(&sk), black_box(MSG), &mut DefaultRNG::default()) - .unwrap(), + RSASSA_PSS_SHA256::sign_randomized( + black_box(&sk), + black_box(MSG), + &mut DefaultRNG::default(), + ) + .unwrap(), ) }) }); group.bench_function("pss_verify_sha256", |b| { b.iter(|| { - pss_verify_sha256(black_box(&pk), black_box(MSG), black_box(&sig_pss_256)).unwrap() + RSASSA_PSS_SHA256::verify(black_box(&pk), black_box(MSG), None, black_box(&sig_pss_256)) + .unwrap() }) }); group.bench_function("pss_sign_sha384", |b| { b.iter(|| { black_box( - pss_sign_sha384(black_box(&sk), black_box(MSG), &mut DefaultRNG::default()) - .unwrap(), + RSASSA_PSS_SHA384::sign_randomized( + black_box(&sk), + black_box(MSG), + &mut DefaultRNG::default(), + ) + .unwrap(), ) }) }); group.bench_function("pss_verify_sha384", |b| { b.iter(|| { - pss_verify_sha384(black_box(&pk), black_box(MSG), black_box(&sig_pss_384)).unwrap() + RSASSA_PSS_SHA384::verify(black_box(&pk), black_box(MSG), None, black_box(&sig_pss_384)) + .unwrap() }) }); group.bench_function("pss_sign_sha512", |b| { b.iter(|| { black_box( - pss_sign_sha512(black_box(&sk), black_box(MSG), &mut DefaultRNG::default()) - .unwrap(), + RSASSA_PSS_SHA512::sign_randomized( + black_box(&sk), + black_box(MSG), + &mut DefaultRNG::default(), + ) + .unwrap(), ) }) }); group.bench_function("pss_verify_sha512", |b| { b.iter(|| { - pss_verify_sha512(black_box(&pk), black_box(MSG), black_box(&sig_pss_512)).unwrap() + RSASSA_PSS_SHA512::verify(black_box(&pk), black_box(MSG), None, black_box(&sig_pss_512)) + .unwrap() }) }); group.bench_function("pss_sign_shake128", |b| { b.iter(|| { black_box( - pss_shake128_sign(black_box(&sk), black_box(MSG), &mut DefaultRNG::default()) - .unwrap(), + RSASSA_PSS_SHAKE128::sign_randomized( + black_box(&sk), + black_box(MSG), + &mut DefaultRNG::default(), + ) + .unwrap(), ) }) }); group.bench_function("pss_verify_shake128", |b| { b.iter(|| { - pss_shake128_verify(black_box(&pk), black_box(MSG), black_box(&sig_pss_shake128)) - .unwrap() + RSASSA_PSS_SHAKE128::verify( + black_box(&pk), + black_box(MSG), + None, + black_box(&sig_pss_shake128), + ) + .unwrap() }) }); diff --git a/crypto/rsa/benches/rsa_4096_benches.rs b/crypto/rsa/benches/rsa_4096_benches.rs index 3fe206de..23738191 100644 --- a/crypto/rsa/benches/rsa_4096_benches.rs +++ b/crypto/rsa/benches/rsa_4096_benches.rs @@ -3,15 +3,15 @@ //! `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::traits::{SignatureVerifier, Signer}; use criterion::{Criterion, criterion_group, criterion_main}; use std::hint::black_box; use bouncycastle_rng::DefaultRNG; use bouncycastle_rsa::rsa_4096::{ - Rsa4096PrivateKey, Rsa4096PublicKey, pkcs1_v1_5_sign_sha256, pkcs1_v1_5_sign_sha384, - pkcs1_v1_5_sign_sha512, pkcs1_v1_5_verify_sha256, pkcs1_v1_5_verify_sha384, - pkcs1_v1_5_verify_sha512, pss_shake256_sign, pss_shake256_verify, pss_sign_sha256, - pss_sign_sha384, pss_sign_sha512, pss_verify_sha256, pss_verify_sha384, pss_verify_sha512, + 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, + Rsa4096PrivateKey, Rsa4096PublicKey, }; const MSG: &[u8] = b"a representative message for benchmarking RSA-4096"; @@ -76,94 +76,139 @@ fn bench_rsa_4096(c: &mut Criterion) { let pk = Rsa4096PublicKey::new(sk.n(), 0x10001).unwrap(); let mut rng = DefaultRNG::default(); - let sig_pkcs1_256 = pkcs1_v1_5_sign_sha256(&sk, MSG).unwrap(); - let sig_pkcs1_384 = pkcs1_v1_5_sign_sha384(&sk, MSG).unwrap(); - let sig_pkcs1_512 = pkcs1_v1_5_sign_sha512(&sk, MSG).unwrap(); - let sig_pss_256 = pss_sign_sha256(&sk, MSG, &mut rng).unwrap(); - let sig_pss_384 = pss_sign_sha384(&sk, MSG, &mut rng).unwrap(); - let sig_pss_512 = pss_sign_sha512(&sk, MSG, &mut rng).unwrap(); - let sig_pss_shake256 = pss_shake256_sign(&sk, MSG, &mut rng).unwrap(); + let sig_pkcs1_256 = RSASSA_PKCS1_v1_5_SHA256::sign(&sk, MSG, None).unwrap(); + let sig_pkcs1_384 = RSASSA_PKCS1_v1_5_SHA384::sign(&sk, MSG, None).unwrap(); + let sig_pkcs1_512 = RSASSA_PKCS1_v1_5_SHA512::sign(&sk, MSG, None).unwrap(); + let sig_pss_256 = RSASSA_PSS_SHA256::sign_randomized(&sk, MSG, &mut rng).unwrap(); + let sig_pss_384 = RSASSA_PSS_SHA384::sign_randomized(&sk, MSG, &mut rng).unwrap(); + let sig_pss_512 = RSASSA_PSS_SHA512::sign_randomized(&sk, MSG, &mut rng).unwrap(); + let sig_pss_shake256 = RSASSA_PSS_SHAKE256::sign_randomized(&sk, MSG, &mut rng).unwrap(); let mut group = c.benchmark_group("rsa_4096"); group.bench_function("pkcs1v15_sign_sha256", |b| { - b.iter(|| black_box(pkcs1_v1_5_sign_sha256(black_box(&sk), black_box(MSG)).unwrap())) + b.iter(|| { + black_box(RSASSA_PKCS1_v1_5_SHA256::sign(black_box(&sk), black_box(MSG), None).unwrap()) + }) }); group.bench_function("pkcs1v15_verify_sha256", |b| { b.iter(|| { - pkcs1_v1_5_verify_sha256(black_box(&pk), black_box(MSG), black_box(&sig_pkcs1_256)) - .unwrap() + RSASSA_PKCS1_v1_5_SHA256::verify( + black_box(&pk), + black_box(MSG), + None, + black_box(&sig_pkcs1_256), + ) + .unwrap() }) }); group.bench_function("pkcs1v15_sign_sha384", |b| { - b.iter(|| black_box(pkcs1_v1_5_sign_sha384(black_box(&sk), black_box(MSG)).unwrap())) + b.iter(|| { + black_box(RSASSA_PKCS1_v1_5_SHA384::sign(black_box(&sk), black_box(MSG), None).unwrap()) + }) }); group.bench_function("pkcs1v15_verify_sha384", |b| { b.iter(|| { - pkcs1_v1_5_verify_sha384(black_box(&pk), black_box(MSG), black_box(&sig_pkcs1_384)) - .unwrap() + RSASSA_PKCS1_v1_5_SHA384::verify( + black_box(&pk), + black_box(MSG), + None, + black_box(&sig_pkcs1_384), + ) + .unwrap() }) }); group.bench_function("pkcs1v15_sign_sha512", |b| { - b.iter(|| black_box(pkcs1_v1_5_sign_sha512(black_box(&sk), black_box(MSG)).unwrap())) + b.iter(|| { + black_box(RSASSA_PKCS1_v1_5_SHA512::sign(black_box(&sk), black_box(MSG), None).unwrap()) + }) }); group.bench_function("pkcs1v15_verify_sha512", |b| { b.iter(|| { - pkcs1_v1_5_verify_sha512(black_box(&pk), black_box(MSG), black_box(&sig_pkcs1_512)) - .unwrap() + RSASSA_PKCS1_v1_5_SHA512::verify( + black_box(&pk), + black_box(MSG), + None, + black_box(&sig_pkcs1_512), + ) + .unwrap() }) }); group.bench_function("pss_sign_sha256", |b| { b.iter(|| { black_box( - pss_sign_sha256(black_box(&sk), black_box(MSG), &mut DefaultRNG::default()) - .unwrap(), + RSASSA_PSS_SHA256::sign_randomized( + black_box(&sk), + black_box(MSG), + &mut DefaultRNG::default(), + ) + .unwrap(), ) }) }); group.bench_function("pss_verify_sha256", |b| { b.iter(|| { - pss_verify_sha256(black_box(&pk), black_box(MSG), black_box(&sig_pss_256)).unwrap() + RSASSA_PSS_SHA256::verify(black_box(&pk), black_box(MSG), None, black_box(&sig_pss_256)) + .unwrap() }) }); group.bench_function("pss_sign_sha384", |b| { b.iter(|| { black_box( - pss_sign_sha384(black_box(&sk), black_box(MSG), &mut DefaultRNG::default()) - .unwrap(), + RSASSA_PSS_SHA384::sign_randomized( + black_box(&sk), + black_box(MSG), + &mut DefaultRNG::default(), + ) + .unwrap(), ) }) }); group.bench_function("pss_verify_sha384", |b| { b.iter(|| { - pss_verify_sha384(black_box(&pk), black_box(MSG), black_box(&sig_pss_384)).unwrap() + RSASSA_PSS_SHA384::verify(black_box(&pk), black_box(MSG), None, black_box(&sig_pss_384)) + .unwrap() }) }); group.bench_function("pss_sign_sha512", |b| { b.iter(|| { black_box( - pss_sign_sha512(black_box(&sk), black_box(MSG), &mut DefaultRNG::default()) - .unwrap(), + RSASSA_PSS_SHA512::sign_randomized( + black_box(&sk), + black_box(MSG), + &mut DefaultRNG::default(), + ) + .unwrap(), ) }) }); group.bench_function("pss_verify_sha512", |b| { b.iter(|| { - pss_verify_sha512(black_box(&pk), black_box(MSG), black_box(&sig_pss_512)).unwrap() + RSASSA_PSS_SHA512::verify(black_box(&pk), black_box(MSG), None, black_box(&sig_pss_512)) + .unwrap() }) }); group.bench_function("pss_sign_shake256", |b| { b.iter(|| { black_box( - pss_shake256_sign(black_box(&sk), black_box(MSG), &mut DefaultRNG::default()) - .unwrap(), + RSASSA_PSS_SHAKE256::sign_randomized( + black_box(&sk), + black_box(MSG), + &mut DefaultRNG::default(), + ) + .unwrap(), ) }) }); group.bench_function("pss_verify_shake256", |b| { b.iter(|| { - pss_shake256_verify(black_box(&pk), black_box(MSG), black_box(&sig_pss_shake256)) - .unwrap() + RSASSA_PSS_SHAKE256::verify( + black_box(&pk), + black_box(MSG), + None, + black_box(&sig_pss_shake256), + ) + .unwrap() }) }); diff --git a/crypto/rsa/benches/rsa_8192_benches.rs b/crypto/rsa/benches/rsa_8192_benches.rs index 8abaa342..b5742afd 100644 --- a/crypto/rsa/benches/rsa_8192_benches.rs +++ b/crypto/rsa/benches/rsa_8192_benches.rs @@ -3,15 +3,14 @@ //! 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::traits::{SignatureVerifier, Signer}; use criterion::{Criterion, criterion_group, criterion_main}; use std::hint::black_box; use bouncycastle_rng::DefaultRNG; use bouncycastle_rsa::rsa_8192::{ - Rsa8192PrivateKey, Rsa8192PublicKey, pkcs1_v1_5_sign_sha256, pkcs1_v1_5_sign_sha384, - pkcs1_v1_5_sign_sha512, pkcs1_v1_5_verify_sha256, pkcs1_v1_5_verify_sha384, - pkcs1_v1_5_verify_sha512, pss_sign_sha256, pss_sign_sha384, pss_sign_sha512, pss_verify_sha256, - pss_verify_sha384, pss_verify_sha512, + RSASSA_PKCS1_v1_5_SHA256, RSASSA_PKCS1_v1_5_SHA384, RSASSA_PKCS1_v1_5_SHA512, + RSASSA_PSS_SHA256, RSASSA_PSS_SHA384, RSASSA_PSS_SHA512, Rsa8192PrivateKey, Rsa8192PublicKey, }; const MSG: &[u8] = b"a representative message for benchmarking RSA-8192"; @@ -116,79 +115,115 @@ fn bench_rsa_8192(c: &mut Criterion) { let pk = Rsa8192PublicKey::new(sk.n(), 0x10001).unwrap(); let mut rng = DefaultRNG::default(); - let sig_pkcs1_256 = pkcs1_v1_5_sign_sha256(&sk, MSG).unwrap(); - let sig_pkcs1_384 = pkcs1_v1_5_sign_sha384(&sk, MSG).unwrap(); - let sig_pkcs1_512 = pkcs1_v1_5_sign_sha512(&sk, MSG).unwrap(); - let sig_pss_256 = pss_sign_sha256(&sk, MSG, &mut rng).unwrap(); - let sig_pss_384 = pss_sign_sha384(&sk, MSG, &mut rng).unwrap(); - let sig_pss_512 = pss_sign_sha512(&sk, MSG, &mut rng).unwrap(); + let sig_pkcs1_256 = RSASSA_PKCS1_v1_5_SHA256::sign(&sk, MSG, None).unwrap(); + let sig_pkcs1_384 = RSASSA_PKCS1_v1_5_SHA384::sign(&sk, MSG, None).unwrap(); + let sig_pkcs1_512 = RSASSA_PKCS1_v1_5_SHA512::sign(&sk, MSG, None).unwrap(); + let sig_pss_256 = RSASSA_PSS_SHA256::sign_randomized(&sk, MSG, &mut rng).unwrap(); + let sig_pss_384 = RSASSA_PSS_SHA384::sign_randomized(&sk, MSG, &mut rng).unwrap(); + let sig_pss_512 = RSASSA_PSS_SHA512::sign_randomized(&sk, MSG, &mut rng).unwrap(); let mut group = c.benchmark_group("rsa_8192"); group.bench_function("pkcs1v15_sign_sha256", |b| { - b.iter(|| black_box(pkcs1_v1_5_sign_sha256(black_box(&sk), black_box(MSG)).unwrap())) + b.iter(|| { + black_box(RSASSA_PKCS1_v1_5_SHA256::sign(black_box(&sk), black_box(MSG), None).unwrap()) + }) }); group.bench_function("pkcs1v15_verify_sha256", |b| { b.iter(|| { - pkcs1_v1_5_verify_sha256(black_box(&pk), black_box(MSG), black_box(&sig_pkcs1_256)) - .unwrap() + RSASSA_PKCS1_v1_5_SHA256::verify( + black_box(&pk), + black_box(MSG), + None, + black_box(&sig_pkcs1_256), + ) + .unwrap() }) }); group.bench_function("pkcs1v15_sign_sha384", |b| { - b.iter(|| black_box(pkcs1_v1_5_sign_sha384(black_box(&sk), black_box(MSG)).unwrap())) + b.iter(|| { + black_box(RSASSA_PKCS1_v1_5_SHA384::sign(black_box(&sk), black_box(MSG), None).unwrap()) + }) }); group.bench_function("pkcs1v15_verify_sha384", |b| { b.iter(|| { - pkcs1_v1_5_verify_sha384(black_box(&pk), black_box(MSG), black_box(&sig_pkcs1_384)) - .unwrap() + RSASSA_PKCS1_v1_5_SHA384::verify( + black_box(&pk), + black_box(MSG), + None, + black_box(&sig_pkcs1_384), + ) + .unwrap() }) }); group.bench_function("pkcs1v15_sign_sha512", |b| { - b.iter(|| black_box(pkcs1_v1_5_sign_sha512(black_box(&sk), black_box(MSG)).unwrap())) + b.iter(|| { + black_box(RSASSA_PKCS1_v1_5_SHA512::sign(black_box(&sk), black_box(MSG), None).unwrap()) + }) }); group.bench_function("pkcs1v15_verify_sha512", |b| { b.iter(|| { - pkcs1_v1_5_verify_sha512(black_box(&pk), black_box(MSG), black_box(&sig_pkcs1_512)) - .unwrap() + RSASSA_PKCS1_v1_5_SHA512::verify( + black_box(&pk), + black_box(MSG), + None, + black_box(&sig_pkcs1_512), + ) + .unwrap() }) }); group.bench_function("pss_sign_sha256", |b| { b.iter(|| { black_box( - pss_sign_sha256(black_box(&sk), black_box(MSG), &mut DefaultRNG::default()) - .unwrap(), + RSASSA_PSS_SHA256::sign_randomized( + black_box(&sk), + black_box(MSG), + &mut DefaultRNG::default(), + ) + .unwrap(), ) }) }); group.bench_function("pss_verify_sha256", |b| { b.iter(|| { - pss_verify_sha256(black_box(&pk), black_box(MSG), black_box(&sig_pss_256)).unwrap() + RSASSA_PSS_SHA256::verify(black_box(&pk), black_box(MSG), None, black_box(&sig_pss_256)) + .unwrap() }) }); group.bench_function("pss_sign_sha384", |b| { b.iter(|| { black_box( - pss_sign_sha384(black_box(&sk), black_box(MSG), &mut DefaultRNG::default()) - .unwrap(), + RSASSA_PSS_SHA384::sign_randomized( + black_box(&sk), + black_box(MSG), + &mut DefaultRNG::default(), + ) + .unwrap(), ) }) }); group.bench_function("pss_verify_sha384", |b| { b.iter(|| { - pss_verify_sha384(black_box(&pk), black_box(MSG), black_box(&sig_pss_384)).unwrap() + RSASSA_PSS_SHA384::verify(black_box(&pk), black_box(MSG), None, black_box(&sig_pss_384)) + .unwrap() }) }); group.bench_function("pss_sign_sha512", |b| { b.iter(|| { black_box( - pss_sign_sha512(black_box(&sk), black_box(MSG), &mut DefaultRNG::default()) - .unwrap(), + RSASSA_PSS_SHA512::sign_randomized( + black_box(&sk), + black_box(MSG), + &mut DefaultRNG::default(), + ) + .unwrap(), ) }) }); group.bench_function("pss_verify_sha512", |b| { b.iter(|| { - pss_verify_sha512(black_box(&pk), black_box(MSG), black_box(&sig_pss_512)).unwrap() + RSASSA_PSS_SHA512::verify(black_box(&pk), black_box(MSG), None, black_box(&sig_pss_512)) + .unwrap() }) }); diff --git a/crypto/rsa/src/lib.rs b/crypto/rsa/src/lib.rs index 3a1e30ae..69e01cd8 100644 --- a/crypto/rsa/src/lib.rs +++ b/crypto/rsa/src/lib.rs @@ -13,14 +13,16 @@ //! only, enforced by the absence of a private-key type (and so of any `Signer` impl) for those //! sizes rather than a runtime check. //! -//! Every (scheme, hash, modulus size) pairing is available two ways over one implementation: -//! as a pair of free functions taking a whole message (`pkcs1_v1_5_sign_sha256`/`..._verify_...` -//! in each size module), and as a type implementing [`bouncycastle_core`]'s +//! Every (scheme, hash, modulus size) pairing is a type implementing [`bouncycastle_core`]'s //! [`Signer`](bouncycastle_core::traits::Signer)/[`SignatureVerifier`](bouncycastle_core::traits::SignatureVerifier) -//! traits (`RSASSA_PKCS1_v1_5_SHA256` and siblings in each size module), which adds the -//! streaming `_init`/`_update`/`_final` form. The key types implement +//! traits (`RSASSA_PKCS1_v1_5_SHA256` and siblings in each size module), one-shot or streaming +//! (`_init`/`_update`/`_final`), the same API shape as this workspace's ECDSA, SM2 and ML-DSA +//! crates. RSASSA-PSS's salt comes from the library's default RNG through `Signer::sign`, from +//! a caller-supplied RNG through `sign_randomized`, or is fixed through `set_signer_salt` on a +//! streaming state. The key types implement //! [`SignaturePrivateKey`](bouncycastle_core::traits::SignaturePrivateKey)/[`SignaturePublicKey`](bouncycastle_core::traits::SignaturePublicKey) -//! per size. +//! per size. The generic `rsassa_*` modules also expose `*_from_hash` entry points that take +//! the message hash rather than the message, for a caller that already holds the digest. //! //! # Usage Examples //! @@ -66,6 +68,23 @@ //! RSASSA_PSS_SHA256::verify(&pk, b"the message to sign", None, &sig_a)?; //! RSASSA_PSS_SHA256::verify(&pk, b"the message to sign", None, &sig_b)?; //! +//! // ... or from a caller-supplied RNG (as ECDSA's and SM2's `sign_randomized`), ... +//! use bouncycastle_rng::DefaultRNG; +//! let sig_c = RSASSA_PSS_SHA256::sign_randomized(&sk, b"the message to sign", &mut DefaultRNG::default())?; +//! RSASSA_PSS_SHA256::verify(&pk, b"the message to sign", None, &sig_c)?; +//! +//! // ... or fixed on a streaming state (as ML-DSA's `set_signer_rnd`), which makes PSS +//! // deterministic -- for a caller with its own randomness source, or a test against a known salt. +//! let mut signer = RSASSA_PSS_SHA256::sign_init(&sk, None)?; +//! signer.set_signer_salt([0x42u8; 32]); +//! signer.sign_update(b"the message to sign"); +//! let sig_d = signer.sign_final()?; +//! let mut signer = RSASSA_PSS_SHA256::sign_init(&sk, None)?; +//! signer.set_signer_salt([0x42u8; 32]); +//! signer.sign_update(b"the message to sign"); +//! assert_eq!(signer.sign_final()?, sig_d); +//! RSASSA_PSS_SHA256::verify(&pk, b"the message to sign", None, &sig_d)?; +//! //! // Keys round-trip through the traits' raw fixed-width encoding (see `keys`'s docs). //! let pk_again = Rsa2048PublicKey::from_bytes(&pk.encode())?; //! assert_eq!(pk_again, pk); @@ -74,61 +93,27 @@ //! # Ok::<(), bouncycastle_core::errors::SignatureError>(()) //! ``` //! -//! The same RSA-2048/SHA-256 pairing through the free functions, which take a whole message and -//! (for PSS) an explicit RNG or salt: -//! -//! ``` -//! use bouncycastle_rsa::rsa_2048::{Rsa2048PrivateKey, Rsa2048PublicKey, pkcs1_v1_5_sign_sha256, pkcs1_v1_5_verify_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). -//! # 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 = Rsa2048PrivateKey::from_crt_components(&P, &Q, &D_P, &D_Q, &Q_INV)?; -//! let pk = Rsa2048PublicKey::new(sk.n(), 0x10001)?; -//! -//! let signature = pkcs1_v1_5_sign_sha256(&sk, b"the message to sign")?; -//! pkcs1_v1_5_verify_sha256(&pk, b"the message to sign", &signature)?; -//! -//! // A signature does not verify against a different message. -//! assert!(pkcs1_v1_5_verify_sha256(&pk, b"a different message", &signature).is_err()); -//! -//! // RSASSA-PSS is randomized (a fresh salt each time), so two signatures of the same message -//! // differ, but both verify. -//! use bouncycastle_rsa::rsa_2048::{pss_sign_sha256, pss_verify_sha256}; -//! use bouncycastle_rng::DefaultRNG; -//! -//! let mut rng = DefaultRNG::default(); -//! let sig_a = pss_sign_sha256(&sk, b"the message to sign", &mut rng)?; -//! let sig_b = pss_sign_sha256(&sk, b"the message to sign", &mut rng)?; -//! assert_ne!(sig_a, sig_b); -//! pss_verify_sha256(&pk, b"the message to sign", &sig_a)?; -//! pss_verify_sha256(&pk, b"the message to sign", &sig_b)?; -//! # Ok::<(), bouncycastle_core::errors::SignatureError>(()) -//! ``` -//! -//! RSA-1024 verification, the other major usage pattern: no private key or signer exists for this -//! size at all (see `# Scope` above), only verification against a signature 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): +//! RSA-1024 verification, the other major usage pattern: no private key or `Signer` exists for +//! this size at all (see `# Scope` above), only a `SignatureVerifier` 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_rsa::rsa_1024::{Rsa1024PublicKey, pkcs1_v1_5_verify_sha256}; +//! use bouncycastle_core::traits::SignatureVerifier; +//! use bouncycastle_rsa::rsa_1024::{RSASSA_PKCS1_v1_5_SHA256, Rsa1024PublicKey}; //! # const N: [u64; 16] = [0xd00343468eaacfbf, 0xb7c7044cc202dcca, 0x9686f30f478db649, 0x5179b54951fff6aa, 0xbabb14f550d5d0dd, 0x5405db7c5c8f4cf6, 0x9816e2eda41fd7b9, 0xb31b6abd805bace9, 0xb909dd0f4c6014f2, 0x9c8a5810b6d05990, 0x40760d1f23fe9250, 0x90adb011a919575a, 0x45e48572113cab28, 0xcb9ca9ec12000fc8, 0x91b4fcaf62a14595, 0xac9048a7a4f560af]; -//! let sig: [u8; 128] = bouncycastle_hex::decode("41339884a9b3940e8488d666bb158063c6a2a2717cae7f564834a876fcbf7098ecf3acbfabf37d38a8e6127b1e313744f1f896e165efdaea0b2e7673867842b9e94db0868ed9a92bcdcb370a4e20ff275c82595e4400a8b9e9f12482f014846b48216f321266ae6ae6338dbcdc41b711e483e6e3e728772e7f9f5ef95c30196b").unwrap().try_into().unwrap(); +//! let sig = bouncycastle_hex::decode("41339884a9b3940e8488d666bb158063c6a2a2717cae7f564834a876fcbf7098ecf3acbfabf37d38a8e6127b1e313744f1f896e165efdaea0b2e7673867842b9e94db0868ed9a92bcdcb370a4e20ff275c82595e4400a8b9e9f12482f014846b48216f321266ae6ae6338dbcdc41b711e483e6e3e728772e7f9f5ef95c30196b").unwrap(); //! let msg = [0u8; 20]; // Wycheproof's own genuine message for this signature. //! let pk = Rsa1024PublicKey::new(&N, 0x10001)?; -//! pkcs1_v1_5_verify_sha256(&pk, &msg, &sig)?; +//! RSASSA_PKCS1_v1_5_SHA256::verify(&pk, &msg, None, &sig)?; //! # Ok::<(), bouncycastle_core::errors::SignatureError>(()) //! ``` //! -//! RSASSA-PSS-SHAKE128/256 (RFC 8702 §3.2.1, [`rsa_2048::pss_shake128_sign`]/`_verify` and -//! siblings at RSA-3072/4096) follow the exact same `sign`/`sign_with_salt`/`verify` shape as -//! `pss_sign_sha256`/`pss_verify_sha256` above, just with a different function name per §5's -//! recommended pairing (SHAKE128 at 2048/3072, SHAKE256 at 4096) -- see [`rsa_2048`]'s own docs -//! rather than a second, near-identical example here. +//! 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, `sign_randomized` and +//! `set_signer_salt` included -- see [`rsa_2048`]'s own docs rather than a second, near-identical +//! example here. //! //! # Status //! diff --git a/crypto/rsa/src/rsa_1024.rs b/crypto/rsa/src/rsa_1024.rs index 354b28e2..0bc22535 100644 --- a/crypto/rsa/src/rsa_1024.rs +++ b/crypto/rsa/src/rsa_1024.rs @@ -28,7 +28,6 @@ //! ``` use crate::keys::RsaPublicKey; -use crate::rsassa_pkcs1_v1_5; use crate::rsassa_pkcs1_v1_5::RSASSA_PKCS1_v1_5; use bouncycastle_core::errors::SignatureError; use bouncycastle_core::traits::SignaturePublicKey; @@ -62,7 +61,7 @@ impl SignaturePublicKey for Rsa1024PublicKey { } /// RSASSA-PKCS1-v1_5/SHA-256 over RSA-1024 as a `SignatureVerifier` only (see the module docs): -/// [`RSASSA_PKCS1_v1_5`] at the widths [`pkcs1_v1_5_verify_sha256`] passes. The signing-side +/// [`RSASSA_PKCS1_v1_5`] at this size's widths. The signing-side /// widths the generic type also needs (`HALF = 8`, `HALF2 = 16`, `HALF21 = 17`, `SK_LEN = 320`) /// are what an RSA-1024 CRT key would have if one existed; they name the type but nothing uses /// them, since the `Signer` impl they would feed does not exist for `RsaPrivateKey<16, 8>`. @@ -73,23 +72,3 @@ pub type RSASSA_PKCS1_v1_5_SHA256 = #[allow(non_camel_case_types)] pub type RSASSA_PKCS1_v1_5_SHA384 = RSASSA_PKCS1_v1_5; - -/// RSASSA-PKCS1-v1_5 (RFC 8017 §8.2) verification against a SHA-256 digest. See -/// [`rsassa_pkcs1_v1_5::verify`] for what each error means. -pub fn pkcs1_v1_5_verify_sha256( - pk: &Rsa1024PublicKey, - message: &[u8], - signature: &[u8; 128], -) -> Result<(), SignatureError> { - rsassa_pkcs1_v1_5::verify::(pk, message, signature) -} - -/// RSASSA-PKCS1-v1_5 (RFC 8017 §8.2) verification against a SHA-384 digest. See -/// [`rsassa_pkcs1_v1_5::verify`] for what each error means. -pub fn pkcs1_v1_5_verify_sha384( - pk: &Rsa1024PublicKey, - message: &[u8], - signature: &[u8; 128], -) -> Result<(), SignatureError> { - rsassa_pkcs1_v1_5::verify::(pk, message, signature) -} diff --git a/crypto/rsa/src/rsa_1536.rs b/crypto/rsa/src/rsa_1536.rs index 6f0c7be8..e8c4dff1 100644 --- a/crypto/rsa/src/rsa_1536.rs +++ b/crypto/rsa/src/rsa_1536.rs @@ -11,7 +11,6 @@ //! the same reason and in the same way as [`crate::rsa_1024`]'s -- see that module's docs. use crate::keys::RsaPublicKey; -use crate::rsassa_pkcs1_v1_5; use crate::rsassa_pkcs1_v1_5::RSASSA_PKCS1_v1_5; use bouncycastle_core::errors::SignatureError; use bouncycastle_core::traits::SignaturePublicKey; @@ -58,33 +57,3 @@ pub type RSASSA_PKCS1_v1_5_SHA384 = #[allow(non_camel_case_types)] pub type RSASSA_PKCS1_v1_5_SHA512 = RSASSA_PKCS1_v1_5; - -/// RSASSA-PKCS1-v1_5 (RFC 8017 §8.2) verification against a SHA-256 digest. See -/// [`rsassa_pkcs1_v1_5::verify`] for what each error means. -pub fn pkcs1_v1_5_verify_sha256( - pk: &Rsa1536PublicKey, - message: &[u8], - signature: &[u8; 192], -) -> Result<(), SignatureError> { - rsassa_pkcs1_v1_5::verify::(pk, message, signature) -} - -/// RSASSA-PKCS1-v1_5 (RFC 8017 §8.2) verification against a SHA-384 digest. See -/// [`rsassa_pkcs1_v1_5::verify`] for what each error means. -pub fn pkcs1_v1_5_verify_sha384( - pk: &Rsa1536PublicKey, - message: &[u8], - signature: &[u8; 192], -) -> Result<(), SignatureError> { - rsassa_pkcs1_v1_5::verify::(pk, message, signature) -} - -/// RSASSA-PKCS1-v1_5 (RFC 8017 §8.2) verification against a SHA-512 digest. See -/// [`rsassa_pkcs1_v1_5::verify`] for what each error means. -pub fn pkcs1_v1_5_verify_sha512( - pk: &Rsa1536PublicKey, - message: &[u8], - signature: &[u8; 192], -) -> Result<(), SignatureError> { - rsassa_pkcs1_v1_5::verify::(pk, message, signature) -} diff --git a/crypto/rsa/src/rsa_2048.rs b/crypto/rsa/src/rsa_2048.rs index 0264d7ea..d87e5fe7 100644 --- a/crypto/rsa/src/rsa_2048.rs +++ b/crypto/rsa/src/rsa_2048.rs @@ -7,22 +7,18 @@ //! matching RFC 8017 §9.1 note 4's "typical" choice and Wycheproof's own //! `rsa_pss_2048_sha256_mgf1_32_test.json`/`..._sha384_mgf1_48_test.json`. //! -//! Each (scheme, hash) pairing is offered two ways over the same code path: a pair of free -//! functions taking a whole message (`pkcs1_v1_5_sign_sha256`/`pkcs1_v1_5_verify_sha256`, ...), -//! and a type implementing `bouncycastle_core`'s `Signer`/`SignatureVerifier` traits -//! ([`RSASSA_PKCS1_v1_5_SHA256`], ...) for streaming use and for code written against those -//! traits. The key types implement `SignaturePrivateKey`/`SignaturePublicKey` here, at this -//! size's [`SK_LEN`]/[`PK_LEN`]. +//! Each (scheme, hash) pairing is a type implementing `bouncycastle_core`'s +//! `Signer`/`SignatureVerifier` traits ([`RSASSA_PKCS1_v1_5_SHA256`], [`RSASSA_PSS_SHA256`], +//! [`RSASSA_PSS_SHAKE128`], ...): one-shot or streaming, with PSS's salt from the default RNG or +//! under the caller's control via `sign_randomized`/`set_signer_salt`. The key types implement +//! `SignaturePrivateKey`/`SignaturePublicKey` here, at this size's [`SK_LEN`]/[`PK_LEN`]. use crate::keys::{RsaPrivateKey, RsaPublicKey}; -use crate::rsassa_pkcs1_v1_5; use crate::rsassa_pkcs1_v1_5::RSASSA_PKCS1_v1_5; -use crate::rsassa_pss; use crate::rsassa_pss::RSASSA_PSS; -use crate::rsassa_pss_shake; use crate::rsassa_pss_shake::RSASSA_PSS_SHAKE; use bouncycastle_core::errors::SignatureError; -use bouncycastle_core::traits::{RNG, SignaturePrivateKey, SignaturePublicKey}; +use bouncycastle_core::traits::{SignaturePrivateKey, SignaturePublicKey}; use bouncycastle_sha2::{SHA256, SHA384, SHA512}; use bouncycastle_sha3::SHAKE128; @@ -77,8 +73,8 @@ impl SignaturePublicKey for Rsa2048PublicKey { } /// RSASSA-PKCS1-v1_5/SHA-256 over RSA-2048 as a `Signer`/`SignatureVerifier`: [`RSASSA_PKCS1_v1_5`] -/// at the widths [`pkcs1_v1_5_sign_sha256`] passes. Deterministic, so `Signer::sign` reproduces -/// that function's output byte for byte. +/// at this size's widths. Deterministic: PKCS#1 v1.5 has no randomness, so `Signer::sign` +/// always reproduces the same signature. #[allow(non_camel_case_types)] pub type RSASSA_PKCS1_v1_5_SHA256 = RSASSA_PKCS1_v1_5; @@ -92,8 +88,8 @@ pub type RSASSA_PKCS1_v1_5_SHA512 = RSASSA_PKCS1_v1_5; /// RSASSA-PSS/SHA-256 (MGF1-SHA-256, 32-byte salt) over RSA-2048 as a `Signer`/`SignatureVerifier`: -/// [`RSASSA_PSS`] at the widths [`pss_sign_sha256`] passes, drawing its salt from the library's -/// default RNG (see that type's docs). +/// [`RSASSA_PSS`] at this size's widths, drawing its salt from the library's default RNG unless +/// `sign_randomized`/`set_signer_salt` supply it (see that type's docs). #[allow(non_camel_case_types)] pub type RSASSA_PSS_SHA256 = RSASSA_PSS; @@ -106,197 +102,7 @@ pub type RSASSA_PSS_SHA384 = pub type RSASSA_PSS_SHA512 = RSASSA_PSS; /// RSASSA-PSS-SHAKE128 (RFC 8702 §3.2.1) over RSA-2048 as a `Signer`/`SignatureVerifier`: -/// [`RSASSA_PSS_SHAKE`] at the widths [`pss_shake128_sign`] passes. +/// [`RSASSA_PSS_SHAKE`] at this size's widths. #[allow(non_camel_case_types)] pub type RSASSA_PSS_SHAKE128 = RSASSA_PSS_SHAKE; - -/// RSASSA-PKCS1-v1_5 (RFC 8017 §8.2) signing, `s = m^d mod n` over an EMSA-PKCS1-v1_5/SHA-256 -/// encoded message. See [`rsassa_pkcs1_v1_5::sign`] for what each error means. -pub fn pkcs1_v1_5_sign_sha256( - sk: &Rsa2048PrivateKey, - message: &[u8], -) -> Result<[u8; 256], SignatureError> { - rsassa_pkcs1_v1_5::sign::(sk, message) -} - -/// RSASSA-PKCS1-v1_5 (RFC 8017 §8.2) verification against a SHA-256 digest. See -/// [`rsassa_pkcs1_v1_5::verify`] for what each error means. -pub fn pkcs1_v1_5_verify_sha256( - pk: &Rsa2048PublicKey, - message: &[u8], - signature: &[u8; 256], -) -> Result<(), SignatureError> { - rsassa_pkcs1_v1_5::verify::(pk, message, signature) -} - -/// RSASSA-PSS (RFC 8017 §8.1) signing with SHA-256 (both as the message hash and, per §8.1's own -/// recommendation, as MGF1's hash) and a 32-byte salt drawn fresh from `rng` for each signature. -/// See [`rsassa_pss::sign`] for what each error means. -pub fn pss_sign_sha256( - sk: &Rsa2048PrivateKey, - message: &[u8], - rng: &mut dyn RNG, -) -> Result<[u8; 256], SignatureError> { - rsassa_pss::sign::(sk, message, rng) -} - -/// As [`pss_sign_sha256`], but with the salt supplied directly instead of drawn from an RNG -- -/// deterministic, for testing against a known salt. See [`rsassa_pss::sign_with_salt`]. -pub fn pss_sign_sha256_with_salt( - sk: &Rsa2048PrivateKey, - message: &[u8], - salt: &[u8; 32], -) -> Result<[u8; 256], SignatureError> { - rsassa_pss::sign_with_salt::( - sk, message, salt, - ) -} - -/// RSASSA-PSS (RFC 8017 §8.1) verification against a SHA-256/MGF1-SHA-256/32-byte-salt encoding. -/// See [`rsassa_pss::verify`] for what each error means. -pub fn pss_verify_sha256( - pk: &Rsa2048PublicKey, - message: &[u8], - signature: &[u8; 256], -) -> Result<(), SignatureError> { - rsassa_pss::verify::(pk, message, signature) -} - -/// RSASSA-PKCS1-v1_5 (RFC 8017 §8.2) signing with SHA-384. See [`rsassa_pkcs1_v1_5::sign`] for -/// what each error means. -pub fn pkcs1_v1_5_sign_sha384( - sk: &Rsa2048PrivateKey, - message: &[u8], -) -> Result<[u8; 256], SignatureError> { - rsassa_pkcs1_v1_5::sign::(sk, message) -} - -/// RSASSA-PKCS1-v1_5 (RFC 8017 §8.2) verification against a SHA-384 digest. See -/// [`rsassa_pkcs1_v1_5::verify`] for what each error means. -pub fn pkcs1_v1_5_verify_sha384( - pk: &Rsa2048PublicKey, - message: &[u8], - signature: &[u8; 256], -) -> Result<(), SignatureError> { - rsassa_pkcs1_v1_5::verify::(pk, message, signature) -} - -/// RSASSA-PKCS1-v1_5 (RFC 8017 §8.2) signing with SHA-512. See [`rsassa_pkcs1_v1_5::sign`] for -/// what each error means. -pub fn pkcs1_v1_5_sign_sha512( - sk: &Rsa2048PrivateKey, - message: &[u8], -) -> Result<[u8; 256], SignatureError> { - rsassa_pkcs1_v1_5::sign::(sk, message) -} - -/// RSASSA-PKCS1-v1_5 (RFC 8017 §8.2) verification against a SHA-512 digest. See -/// [`rsassa_pkcs1_v1_5::verify`] for what each error means. -pub fn pkcs1_v1_5_verify_sha512( - pk: &Rsa2048PublicKey, - message: &[u8], - signature: &[u8; 256], -) -> Result<(), SignatureError> { - rsassa_pkcs1_v1_5::verify::(pk, message, signature) -} - -/// RSASSA-PSS (RFC 8017 §8.1) signing with SHA-384 (as both the message hash and MGF1's hash) -/// and a 48-byte salt drawn fresh from `rng`. See [`rsassa_pss::sign`] for what each error means. -pub fn pss_sign_sha384( - sk: &Rsa2048PrivateKey, - message: &[u8], - rng: &mut dyn RNG, -) -> Result<[u8; 256], SignatureError> { - rsassa_pss::sign::(sk, message, rng) -} - -/// As [`pss_sign_sha384`], but with the salt supplied directly instead of drawn from an RNG -- -/// deterministic, for testing against a known salt. See [`rsassa_pss::sign_with_salt`]. -pub fn pss_sign_sha384_with_salt( - sk: &Rsa2048PrivateKey, - message: &[u8], - salt: &[u8; 48], -) -> Result<[u8; 256], SignatureError> { - rsassa_pss::sign_with_salt::( - sk, message, salt, - ) -} - -/// RSASSA-PSS (RFC 8017 §8.1) verification against a SHA-384/MGF1-SHA-384/48-byte-salt encoding. -/// See [`rsassa_pss::verify`] for what each error means. -pub fn pss_verify_sha384( - pk: &Rsa2048PublicKey, - message: &[u8], - signature: &[u8; 256], -) -> Result<(), SignatureError> { - rsassa_pss::verify::(pk, message, signature) -} - -/// RSASSA-PSS (RFC 8017 §8.1) signing with SHA-512 (as both the message hash and MGF1's hash) -/// and a 64-byte salt drawn fresh from `rng`. See [`rsassa_pss::sign`] for what each error means. -pub fn pss_sign_sha512( - sk: &Rsa2048PrivateKey, - message: &[u8], - rng: &mut dyn RNG, -) -> Result<[u8; 256], SignatureError> { - rsassa_pss::sign::(sk, message, rng) -} - -/// As [`pss_sign_sha512`], but with the salt supplied directly instead of drawn from an RNG -- -/// deterministic, for testing against a known salt. See [`rsassa_pss::sign_with_salt`]. -pub fn pss_sign_sha512_with_salt( - sk: &Rsa2048PrivateKey, - message: &[u8], - salt: &[u8; 64], -) -> Result<[u8; 256], SignatureError> { - rsassa_pss::sign_with_salt::( - sk, message, salt, - ) -} - -/// RSASSA-PSS (RFC 8017 §8.1) verification against a SHA-512/MGF1-SHA-512/64-byte-salt encoding. -/// See [`rsassa_pss::verify`] for what each error means. -pub fn pss_verify_sha512( - pk: &Rsa2048PublicKey, - message: &[u8], - signature: &[u8; 256], -) -> Result<(), SignatureError> { - rsassa_pss::verify::(pk, message, signature) -} - -/// RSASSA-PSS-SHAKE128 (`id-RSASSA-PSS-SHAKE128`, RFC 8702 §3.2.1) signing: SHAKE128 as both the -/// message hash and, natively rather than through MGF1, the mask generation function, with a -/// 32-byte salt drawn fresh from `rng` for each signature. RFC 8702 §5 recommends this pairing for -/// a 2048- or 3072-bit RSA modulus. See [`rsassa_pss_shake::sign`] for what each error means. -pub fn pss_shake128_sign( - sk: &Rsa2048PrivateKey, - message: &[u8], - rng: &mut dyn RNG, -) -> Result<[u8; 256], SignatureError> { - rsassa_pss_shake::sign::( - sk, message, rng, - ) -} - -/// As [`pss_shake128_sign`], but with the salt supplied directly instead of drawn from an RNG -- -/// deterministic, for testing against a known salt. See [`rsassa_pss_shake::sign_with_salt`]. -pub fn pss_shake128_sign_with_salt( - sk: &Rsa2048PrivateKey, - message: &[u8], - salt: &[u8; 32], -) -> Result<[u8; 256], SignatureError> { - rsassa_pss_shake::sign_with_salt::( - sk, message, salt, - ) -} - -/// RSASSA-PSS-SHAKE128 (RFC 8702 §3.2.1) verification. See [`rsassa_pss_shake::verify`] for what -/// each error means. -pub fn pss_shake128_verify( - pk: &Rsa2048PublicKey, - message: &[u8], - signature: &[u8; 256], -) -> Result<(), SignatureError> { - rsassa_pss_shake::verify::(pk, message, signature) -} diff --git a/crypto/rsa/src/rsa_3072.rs b/crypto/rsa/src/rsa_3072.rs index 04b3db14..d0399e78 100644 --- a/crypto/rsa/src/rsa_3072.rs +++ b/crypto/rsa/src/rsa_3072.rs @@ -2,14 +2,11 @@ //! docs for the pattern every concrete modulus size in this crate follows. use crate::keys::{RsaPrivateKey, RsaPublicKey}; -use crate::rsassa_pkcs1_v1_5; use crate::rsassa_pkcs1_v1_5::RSASSA_PKCS1_v1_5; -use crate::rsassa_pss; use crate::rsassa_pss::RSASSA_PSS; -use crate::rsassa_pss_shake; use crate::rsassa_pss_shake::RSASSA_PSS_SHAKE; use bouncycastle_core::errors::SignatureError; -use bouncycastle_core::traits::{RNG, SignaturePrivateKey, SignaturePublicKey}; +use bouncycastle_core::traits::{SignaturePrivateKey, SignaturePublicKey}; use bouncycastle_sha2::{SHA256, SHA384, SHA512}; use bouncycastle_sha3::SHAKE128; @@ -94,188 +91,3 @@ pub type RSASSA_PSS_SHA512 = #[allow(non_camel_case_types)] pub type RSASSA_PSS_SHAKE128 = RSASSA_PSS_SHAKE; - -/// RSASSA-PKCS1-v1_5 (RFC 8017 §8.2) signing with SHA-256. See [`rsassa_pkcs1_v1_5::sign`] for -/// what each error means. -pub fn pkcs1_v1_5_sign_sha256( - sk: &Rsa3072PrivateKey, - message: &[u8], -) -> Result<[u8; 384], SignatureError> { - rsassa_pkcs1_v1_5::sign::(sk, message) -} - -/// RSASSA-PKCS1-v1_5 (RFC 8017 §8.2) verification against a SHA-256 digest. See -/// [`rsassa_pkcs1_v1_5::verify`] for what each error means. -pub fn pkcs1_v1_5_verify_sha256( - pk: &Rsa3072PublicKey, - message: &[u8], - signature: &[u8; 384], -) -> Result<(), SignatureError> { - rsassa_pkcs1_v1_5::verify::(pk, message, signature) -} - -/// RSASSA-PKCS1-v1_5 (RFC 8017 §8.2) signing with SHA-384. See [`rsassa_pkcs1_v1_5::sign`] for -/// what each error means. -pub fn pkcs1_v1_5_sign_sha384( - sk: &Rsa3072PrivateKey, - message: &[u8], -) -> Result<[u8; 384], SignatureError> { - rsassa_pkcs1_v1_5::sign::(sk, message) -} - -/// RSASSA-PKCS1-v1_5 (RFC 8017 §8.2) verification against a SHA-384 digest. See -/// [`rsassa_pkcs1_v1_5::verify`] for what each error means. -pub fn pkcs1_v1_5_verify_sha384( - pk: &Rsa3072PublicKey, - message: &[u8], - signature: &[u8; 384], -) -> Result<(), SignatureError> { - rsassa_pkcs1_v1_5::verify::(pk, message, signature) -} - -/// RSASSA-PKCS1-v1_5 (RFC 8017 §8.2) signing with SHA-512. See [`rsassa_pkcs1_v1_5::sign`] for -/// what each error means. -pub fn pkcs1_v1_5_sign_sha512( - sk: &Rsa3072PrivateKey, - message: &[u8], -) -> Result<[u8; 384], SignatureError> { - rsassa_pkcs1_v1_5::sign::(sk, message) -} - -/// RSASSA-PKCS1-v1_5 (RFC 8017 §8.2) verification against a SHA-512 digest. See -/// [`rsassa_pkcs1_v1_5::verify`] for what each error means. -pub fn pkcs1_v1_5_verify_sha512( - pk: &Rsa3072PublicKey, - message: &[u8], - signature: &[u8; 384], -) -> Result<(), SignatureError> { - rsassa_pkcs1_v1_5::verify::(pk, message, signature) -} - -/// RSASSA-PSS (RFC 8017 §8.1) signing with SHA-256 and a 32-byte salt drawn fresh from `rng`. See -/// [`rsassa_pss::sign`] for what each error means. -pub fn pss_sign_sha256( - sk: &Rsa3072PrivateKey, - message: &[u8], - rng: &mut dyn RNG, -) -> Result<[u8; 384], SignatureError> { - rsassa_pss::sign::(sk, message, rng) -} - -/// As [`pss_sign_sha256`], but with the salt supplied directly instead of drawn from an RNG. -pub fn pss_sign_sha256_with_salt( - sk: &Rsa3072PrivateKey, - message: &[u8], - salt: &[u8; 32], -) -> Result<[u8; 384], SignatureError> { - rsassa_pss::sign_with_salt::( - sk, message, salt, - ) -} - -/// RSASSA-PSS (RFC 8017 §8.1) verification against a SHA-256/MGF1-SHA-256/32-byte-salt encoding. -/// See [`rsassa_pss::verify`] for what each error means. -pub fn pss_verify_sha256( - pk: &Rsa3072PublicKey, - message: &[u8], - signature: &[u8; 384], -) -> Result<(), SignatureError> { - rsassa_pss::verify::(pk, message, signature) -} - -/// RSASSA-PSS (RFC 8017 §8.1) signing with SHA-384 and a 48-byte salt drawn fresh from `rng`. See -/// [`rsassa_pss::sign`] for what each error means. -pub fn pss_sign_sha384( - sk: &Rsa3072PrivateKey, - message: &[u8], - rng: &mut dyn RNG, -) -> Result<[u8; 384], SignatureError> { - rsassa_pss::sign::(sk, message, rng) -} - -/// As [`pss_sign_sha384`], but with the salt supplied directly instead of drawn from an RNG. -pub fn pss_sign_sha384_with_salt( - sk: &Rsa3072PrivateKey, - message: &[u8], - salt: &[u8; 48], -) -> Result<[u8; 384], SignatureError> { - rsassa_pss::sign_with_salt::( - sk, message, salt, - ) -} - -/// RSASSA-PSS (RFC 8017 §8.1) verification against a SHA-384/MGF1-SHA-384/48-byte-salt encoding. -/// See [`rsassa_pss::verify`] for what each error means. -pub fn pss_verify_sha384( - pk: &Rsa3072PublicKey, - message: &[u8], - signature: &[u8; 384], -) -> Result<(), SignatureError> { - rsassa_pss::verify::(pk, message, signature) -} - -/// RSASSA-PSS (RFC 8017 §8.1) signing with SHA-512 and a 64-byte salt drawn fresh from `rng`. See -/// [`rsassa_pss::sign`] for what each error means. -pub fn pss_sign_sha512( - sk: &Rsa3072PrivateKey, - message: &[u8], - rng: &mut dyn RNG, -) -> Result<[u8; 384], SignatureError> { - rsassa_pss::sign::(sk, message, rng) -} - -/// As [`pss_sign_sha512`], but with the salt supplied directly instead of drawn from an RNG. -pub fn pss_sign_sha512_with_salt( - sk: &Rsa3072PrivateKey, - message: &[u8], - salt: &[u8; 64], -) -> Result<[u8; 384], SignatureError> { - rsassa_pss::sign_with_salt::( - sk, message, salt, - ) -} - -/// RSASSA-PSS (RFC 8017 §8.1) verification against a SHA-512/MGF1-SHA-512/64-byte-salt encoding. -/// See [`rsassa_pss::verify`] for what each error means. -pub fn pss_verify_sha512( - pk: &Rsa3072PublicKey, - message: &[u8], - signature: &[u8; 384], -) -> Result<(), SignatureError> { - rsassa_pss::verify::(pk, message, signature) -} - -/// RSASSA-PSS-SHAKE128 (`id-RSASSA-PSS-SHAKE128`, RFC 8702 §3.2.1) signing: SHAKE128 as both the -/// message hash and, natively rather than through MGF1, the mask generation function, with a -/// 32-byte salt drawn fresh from `rng`. RFC 8702 §5 recommends this pairing for a 2048- or -/// 3072-bit RSA modulus. See [`rsassa_pss_shake::sign`] for what each error means. -pub fn pss_shake128_sign( - sk: &Rsa3072PrivateKey, - message: &[u8], - rng: &mut dyn RNG, -) -> Result<[u8; 384], SignatureError> { - rsassa_pss_shake::sign::( - sk, message, rng, - ) -} - -/// As [`pss_shake128_sign`], but with the salt supplied directly instead of drawn from an RNG. -pub fn pss_shake128_sign_with_salt( - sk: &Rsa3072PrivateKey, - message: &[u8], - salt: &[u8; 32], -) -> Result<[u8; 384], SignatureError> { - rsassa_pss_shake::sign_with_salt::( - sk, message, salt, - ) -} - -/// RSASSA-PSS-SHAKE128 (RFC 8702 §3.2.1) verification. See [`rsassa_pss_shake::verify`] for what -/// each error means. -pub fn pss_shake128_verify( - pk: &Rsa3072PublicKey, - message: &[u8], - signature: &[u8; 384], -) -> Result<(), SignatureError> { - rsassa_pss_shake::verify::(pk, message, signature) -} diff --git a/crypto/rsa/src/rsa_4096.rs b/crypto/rsa/src/rsa_4096.rs index f6b2bb9b..75c8c240 100644 --- a/crypto/rsa/src/rsa_4096.rs +++ b/crypto/rsa/src/rsa_4096.rs @@ -2,14 +2,11 @@ //! docs for the pattern every concrete modulus size in this crate follows. use crate::keys::{RsaPrivateKey, RsaPublicKey}; -use crate::rsassa_pkcs1_v1_5; use crate::rsassa_pkcs1_v1_5::RSASSA_PKCS1_v1_5; -use crate::rsassa_pss; use crate::rsassa_pss::RSASSA_PSS; -use crate::rsassa_pss_shake; use crate::rsassa_pss_shake::RSASSA_PSS_SHAKE; use bouncycastle_core::errors::SignatureError; -use bouncycastle_core::traits::{RNG, SignaturePrivateKey, SignaturePublicKey}; +use bouncycastle_core::traits::{SignaturePrivateKey, SignaturePublicKey}; use bouncycastle_sha2::{SHA256, SHA384, SHA512}; use bouncycastle_sha3::SHAKE256; @@ -94,194 +91,3 @@ pub type RSASSA_PSS_SHA512 = #[allow(non_camel_case_types)] pub type RSASSA_PSS_SHAKE256 = RSASSA_PSS_SHAKE; - -/// RSASSA-PKCS1-v1_5 (RFC 8017 §8.2) signing with SHA-256. See [`rsassa_pkcs1_v1_5::sign`] for -/// what each error means. -pub fn pkcs1_v1_5_sign_sha256( - sk: &Rsa4096PrivateKey, - message: &[u8], -) -> Result<[u8; 512], SignatureError> { - rsassa_pkcs1_v1_5::sign::(sk, message) -} - -/// RSASSA-PKCS1-v1_5 (RFC 8017 §8.2) verification against a SHA-256 digest. See -/// [`rsassa_pkcs1_v1_5::verify`] for what each error means. -pub fn pkcs1_v1_5_verify_sha256( - pk: &Rsa4096PublicKey, - message: &[u8], - signature: &[u8; 512], -) -> Result<(), SignatureError> { - rsassa_pkcs1_v1_5::verify::(pk, message, signature) -} - -/// RSASSA-PKCS1-v1_5 (RFC 8017 §8.2) signing with SHA-384. See [`rsassa_pkcs1_v1_5::sign`] for -/// what each error means. -pub fn pkcs1_v1_5_sign_sha384( - sk: &Rsa4096PrivateKey, - message: &[u8], -) -> Result<[u8; 512], SignatureError> { - rsassa_pkcs1_v1_5::sign::(sk, message) -} - -/// RSASSA-PKCS1-v1_5 (RFC 8017 §8.2) verification against a SHA-384 digest. See -/// [`rsassa_pkcs1_v1_5::verify`] for what each error means. -pub fn pkcs1_v1_5_verify_sha384( - pk: &Rsa4096PublicKey, - message: &[u8], - signature: &[u8; 512], -) -> Result<(), SignatureError> { - rsassa_pkcs1_v1_5::verify::(pk, message, signature) -} - -/// RSASSA-PKCS1-v1_5 (RFC 8017 §8.2) signing with SHA-512. See [`rsassa_pkcs1_v1_5::sign`] for -/// what each error means. -pub fn pkcs1_v1_5_sign_sha512( - sk: &Rsa4096PrivateKey, - message: &[u8], -) -> Result<[u8; 512], SignatureError> { - rsassa_pkcs1_v1_5::sign::(sk, message) -} - -/// RSASSA-PKCS1-v1_5 (RFC 8017 §8.2) verification against a SHA-512 digest. See -/// [`rsassa_pkcs1_v1_5::verify`] for what each error means. -pub fn pkcs1_v1_5_verify_sha512( - pk: &Rsa4096PublicKey, - message: &[u8], - signature: &[u8; 512], -) -> Result<(), SignatureError> { - rsassa_pkcs1_v1_5::verify::(pk, message, signature) -} - -/// RSASSA-PSS (RFC 8017 §8.1) signing with SHA-256 and a 32-byte salt drawn fresh from `rng`. See -/// [`rsassa_pss::sign`] for what each error means. -pub fn pss_sign_sha256( - sk: &Rsa4096PrivateKey, - message: &[u8], - rng: &mut dyn RNG, -) -> Result<[u8; 512], SignatureError> { - rsassa_pss::sign::(sk, message, rng) -} - -/// As [`pss_sign_sha256`], but with the salt supplied directly instead of drawn from an RNG. -pub fn pss_sign_sha256_with_salt( - sk: &Rsa4096PrivateKey, - message: &[u8], - salt: &[u8; 32], -) -> Result<[u8; 512], SignatureError> { - rsassa_pss::sign_with_salt::( - sk, message, salt, - ) -} - -/// RSASSA-PSS (RFC 8017 §8.1) verification against a SHA-256/MGF1-SHA-256/32-byte-salt encoding. -/// See [`rsassa_pss::verify`] for what each error means. -pub fn pss_verify_sha256( - pk: &Rsa4096PublicKey, - message: &[u8], - signature: &[u8; 512], -) -> Result<(), SignatureError> { - rsassa_pss::verify::(pk, message, signature) -} - -/// RSASSA-PSS (RFC 8017 §8.1) signing with SHA-384 and a 48-byte salt drawn fresh from `rng`. See -/// [`rsassa_pss::sign`] for what each error means. -pub fn pss_sign_sha384( - sk: &Rsa4096PrivateKey, - message: &[u8], - rng: &mut dyn RNG, -) -> Result<[u8; 512], SignatureError> { - rsassa_pss::sign::( - sk, message, rng, - ) -} - -/// As [`pss_sign_sha384`], but with the salt supplied directly instead of drawn from an RNG. -pub fn pss_sign_sha384_with_salt( - sk: &Rsa4096PrivateKey, - message: &[u8], - salt: &[u8; 48], -) -> Result<[u8; 512], SignatureError> { - rsassa_pss::sign_with_salt::( - sk, message, salt, - ) -} - -/// RSASSA-PSS (RFC 8017 §8.1) verification against a SHA-384/MGF1-SHA-384/48-byte-salt encoding. -/// See [`rsassa_pss::verify`] for what each error means. -pub fn pss_verify_sha384( - pk: &Rsa4096PublicKey, - message: &[u8], - signature: &[u8; 512], -) -> Result<(), SignatureError> { - rsassa_pss::verify::(pk, message, signature) -} - -/// RSASSA-PSS (RFC 8017 §8.1) signing with SHA-512 and a 64-byte salt drawn fresh from `rng`. See -/// [`rsassa_pss::sign`] for what each error means. -pub fn pss_sign_sha512( - sk: &Rsa4096PrivateKey, - message: &[u8], - rng: &mut dyn RNG, -) -> Result<[u8; 512], SignatureError> { - rsassa_pss::sign::( - sk, message, rng, - ) -} - -/// As [`pss_sign_sha512`], but with the salt supplied directly instead of drawn from an RNG. -pub fn pss_sign_sha512_with_salt( - sk: &Rsa4096PrivateKey, - message: &[u8], - salt: &[u8; 64], -) -> Result<[u8; 512], SignatureError> { - rsassa_pss::sign_with_salt::( - sk, message, salt, - ) -} - -/// RSASSA-PSS (RFC 8017 §8.1) verification against a SHA-512/MGF1-SHA-512/64-byte-salt encoding. -/// See [`rsassa_pss::verify`] for what each error means. -pub fn pss_verify_sha512( - pk: &Rsa4096PublicKey, - message: &[u8], - signature: &[u8; 512], -) -> Result<(), SignatureError> { - rsassa_pss::verify::(pk, message, signature) -} - -/// RSASSA-PSS-SHAKE256 (`id-RSASSA-PSS-SHAKE256`, RFC 8702 §3.2.1) signing: SHAKE256 as both the -/// message hash and, natively rather than through MGF1, the mask generation function, with a -/// 64-byte salt drawn fresh from `rng`. RFC 8702 §5 recommends this pairing for a 4096-bit or -/// larger RSA modulus. See [`rsassa_pss_shake::sign`] for what each error means. -pub fn pss_shake256_sign( - sk: &Rsa4096PrivateKey, - message: &[u8], - rng: &mut dyn RNG, -) -> Result<[u8; 512], SignatureError> { - rsassa_pss_shake::sign::( - sk, message, rng, - ) -} - -/// As [`pss_shake256_sign`], but with the salt supplied directly instead of drawn from an RNG. -pub fn pss_shake256_sign_with_salt( - sk: &Rsa4096PrivateKey, - message: &[u8], - salt: &[u8; 64], -) -> Result<[u8; 512], SignatureError> { - rsassa_pss_shake::sign_with_salt::( - sk, message, salt, - ) -} - -/// RSASSA-PSS-SHAKE256 (RFC 8702 §3.2.1) verification. See [`rsassa_pss_shake::verify`] for what -/// each error means. -pub fn pss_shake256_verify( - pk: &Rsa4096PublicKey, - message: &[u8], - signature: &[u8; 512], -) -> Result<(), SignatureError> { - rsassa_pss_shake::verify::( - pk, message, signature, - ) -} diff --git a/crypto/rsa/src/rsa_8192.rs b/crypto/rsa/src/rsa_8192.rs index ab0daeb1..ca8ddc0f 100644 --- a/crypto/rsa/src/rsa_8192.rs +++ b/crypto/rsa/src/rsa_8192.rs @@ -2,12 +2,10 @@ //! docs for the pattern every concrete modulus size in this crate follows. use crate::keys::{RsaPrivateKey, RsaPublicKey}; -use crate::rsassa_pkcs1_v1_5; use crate::rsassa_pkcs1_v1_5::RSASSA_PKCS1_v1_5; -use crate::rsassa_pss; use crate::rsassa_pss::RSASSA_PSS; use bouncycastle_core::errors::SignatureError; -use bouncycastle_core::traits::{RNG, SignaturePrivateKey, SignaturePublicKey}; +use bouncycastle_core::traits::{SignaturePrivateKey, SignaturePublicKey}; use bouncycastle_sha2::{SHA256, SHA384, SHA512}; /// An RSA-8192 private key (`p`, `q` each 4096 bits). @@ -87,159 +85,3 @@ pub type RSASSA_PSS_SHA384 = #[allow(non_camel_case_types)] pub type RSASSA_PSS_SHA512 = RSASSA_PSS; - -/// RSASSA-PKCS1-v1_5 (RFC 8017 §8.2) signing with SHA-256. See [`rsassa_pkcs1_v1_5::sign`] for -/// what each error means. -pub fn pkcs1_v1_5_sign_sha256( - sk: &Rsa8192PrivateKey, - message: &[u8], -) -> Result<[u8; 1024], SignatureError> { - rsassa_pkcs1_v1_5::sign::(sk, message) -} - -/// RSASSA-PKCS1-v1_5 (RFC 8017 §8.2) verification against a SHA-256 digest. See -/// [`rsassa_pkcs1_v1_5::verify`] for what each error means. -pub fn pkcs1_v1_5_verify_sha256( - pk: &Rsa8192PublicKey, - message: &[u8], - signature: &[u8; 1024], -) -> Result<(), SignatureError> { - rsassa_pkcs1_v1_5::verify::(pk, message, signature) -} - -/// RSASSA-PKCS1-v1_5 (RFC 8017 §8.2) signing with SHA-384. See [`rsassa_pkcs1_v1_5::sign`] for -/// what each error means. -pub fn pkcs1_v1_5_sign_sha384( - sk: &Rsa8192PrivateKey, - message: &[u8], -) -> Result<[u8; 1024], SignatureError> { - rsassa_pkcs1_v1_5::sign::(sk, message) -} - -/// RSASSA-PKCS1-v1_5 (RFC 8017 §8.2) verification against a SHA-384 digest. See -/// [`rsassa_pkcs1_v1_5::verify`] for what each error means. -pub fn pkcs1_v1_5_verify_sha384( - pk: &Rsa8192PublicKey, - message: &[u8], - signature: &[u8; 1024], -) -> Result<(), SignatureError> { - rsassa_pkcs1_v1_5::verify::(pk, message, signature) -} - -/// RSASSA-PKCS1-v1_5 (RFC 8017 §8.2) signing with SHA-512. See [`rsassa_pkcs1_v1_5::sign`] for -/// what each error means. -pub fn pkcs1_v1_5_sign_sha512( - sk: &Rsa8192PrivateKey, - message: &[u8], -) -> Result<[u8; 1024], SignatureError> { - rsassa_pkcs1_v1_5::sign::(sk, message) -} - -/// RSASSA-PKCS1-v1_5 (RFC 8017 §8.2) verification against a SHA-512 digest. See -/// [`rsassa_pkcs1_v1_5::verify`] for what each error means. -pub fn pkcs1_v1_5_verify_sha512( - pk: &Rsa8192PublicKey, - message: &[u8], - signature: &[u8; 1024], -) -> Result<(), SignatureError> { - rsassa_pkcs1_v1_5::verify::(pk, message, signature) -} - -/// RSASSA-PSS (RFC 8017 §8.1) signing with SHA-256 and a 32-byte salt drawn fresh from `rng`. See -/// [`rsassa_pss::sign`] for what each error means. -pub fn pss_sign_sha256( - sk: &Rsa8192PrivateKey, - message: &[u8], - rng: &mut dyn RNG, -) -> Result<[u8; 1024], SignatureError> { - rsassa_pss::sign::( - sk, message, rng, - ) -} - -/// As [`pss_sign_sha256`], but with the salt supplied directly instead of drawn from an RNG. -pub fn pss_sign_sha256_with_salt( - sk: &Rsa8192PrivateKey, - message: &[u8], - salt: &[u8; 32], -) -> Result<[u8; 1024], SignatureError> { - rsassa_pss::sign_with_salt::( - sk, message, salt, - ) -} - -/// RSASSA-PSS (RFC 8017 §8.1) verification against a SHA-256/MGF1-SHA-256/32-byte-salt encoding. -/// See [`rsassa_pss::verify`] for what each error means. -pub fn pss_verify_sha256( - pk: &Rsa8192PublicKey, - message: &[u8], - signature: &[u8; 1024], -) -> Result<(), SignatureError> { - rsassa_pss::verify::(pk, message, signature) -} - -/// RSASSA-PSS (RFC 8017 §8.1) signing with SHA-384 and a 48-byte salt drawn fresh from `rng`. See -/// [`rsassa_pss::sign`] for what each error means. -pub fn pss_sign_sha384( - sk: &Rsa8192PrivateKey, - message: &[u8], - rng: &mut dyn RNG, -) -> Result<[u8; 1024], SignatureError> { - rsassa_pss::sign::( - sk, message, rng, - ) -} - -/// As [`pss_sign_sha384`], but with the salt supplied directly instead of drawn from an RNG. -pub fn pss_sign_sha384_with_salt( - sk: &Rsa8192PrivateKey, - message: &[u8], - salt: &[u8; 48], -) -> Result<[u8; 1024], SignatureError> { - rsassa_pss::sign_with_salt::( - sk, message, salt, - ) -} - -/// RSASSA-PSS (RFC 8017 §8.1) verification against a SHA-384/MGF1-SHA-384/48-byte-salt encoding. -/// See [`rsassa_pss::verify`] for what each error means. -pub fn pss_verify_sha384( - pk: &Rsa8192PublicKey, - message: &[u8], - signature: &[u8; 1024], -) -> Result<(), SignatureError> { - rsassa_pss::verify::(pk, message, signature) -} - -/// RSASSA-PSS (RFC 8017 §8.1) signing with SHA-512 and a 64-byte salt drawn fresh from `rng`. See -/// [`rsassa_pss::sign`] for what each error means. -pub fn pss_sign_sha512( - sk: &Rsa8192PrivateKey, - message: &[u8], - rng: &mut dyn RNG, -) -> Result<[u8; 1024], SignatureError> { - rsassa_pss::sign::( - sk, message, rng, - ) -} - -/// As [`pss_sign_sha512`], but with the salt supplied directly instead of drawn from an RNG. -pub fn pss_sign_sha512_with_salt( - sk: &Rsa8192PrivateKey, - message: &[u8], - salt: &[u8; 64], -) -> Result<[u8; 1024], SignatureError> { - rsassa_pss::sign_with_salt::( - sk, message, salt, - ) -} - -/// RSASSA-PSS (RFC 8017 §8.1) verification against a SHA-512/MGF1-SHA-512/64-byte-salt encoding. -/// See [`rsassa_pss::verify`] for what each error means. -pub fn pss_verify_sha512( - pk: &Rsa8192PublicKey, - message: &[u8], - signature: &[u8; 1024], -) -> Result<(), SignatureError> { - rsassa_pss::verify::(pk, message, signature) -} diff --git a/crypto/rsa/src/rsassa_pkcs1_v1_5.rs b/crypto/rsa/src/rsassa_pkcs1_v1_5.rs index e9783196..23aaaab4 100644 --- a/crypto/rsa/src/rsassa_pkcs1_v1_5.rs +++ b/crypto/rsa/src/rsassa_pkcs1_v1_5.rs @@ -5,11 +5,11 @@ //! the hash function `H` (`H_LEN`/`T_LEN` sized to it) -- a concrete modulus size wires these to //! literals (e.g. RSA-2048/SHA-256 in [`crate::rsa_2048`]) rather than a caller choosing them. //! -//! Two shapes of the same operation: the free functions [`sign`]/[`verify`] take a whole message, -//! and [`RSASSA_PKCS1_v1_5`] implements `bouncycastle_core`'s [`Signer`]/[`SignatureVerifier`] -//! traits over the same widths, adding the streaming (`sign_init`/`sign_update`/`sign_final`) -//! form and a `&[u8]`-typed signature on the verify side. Both go through [`sign_from_hash`]/ -//! [`verify_from_hash`], so there is exactly one encoding path to test. +//! [`RSASSA_PKCS1_v1_5`] implements `bouncycastle_core`'s [`Signer`]/[`SignatureVerifier`] traits +//! over those widths -- one-shot and streaming (`sign_init`/`sign_update`/`sign_final`), with a +//! `&[u8]`-typed signature on the verify side -- on top of [`sign_from_hash`]/[`verify_from_hash`], +//! which take the message hash rather than the message and are the pre-hash entry points for a +//! caller that has already computed it. use crate::codec::{be_bytes_from_limbs, limbs_from_be_bytes}; use crate::emsa_pkcs1_v1_5::{emsa_pkcs1_v1_5_encode_from_hash, emsa_pkcs1_v1_5_verify_from_hash}; @@ -22,7 +22,7 @@ use bouncycastle_core::traits::{ }; /// Streaming state for RSASSA-PKCS1-v1_5's [`Signer`] and [`SignatureVerifier`] impls, at the -/// widths the const parameters fix (the same list [`sign`] takes, plus the key encoding lengths +/// widths the const parameters fix (the list [`sign_from_hash`] takes, plus the key encoding lengths /// `SK_LEN`/`PK_LEN` the key traits are indexed by). One type serves both roles, mirroring /// `bouncycastle_ecdsa::ecdsa_p256::ECDSAP256`: exactly one of `sk`/`pk` is `Some`, chosen by /// which trait's `_init` constructed this value, and calling the other trait's `_final` on it is @@ -173,51 +173,27 @@ where // RFC 8017 §8.2.2 step 1: "Length checking: If the length of the signature S is not k // octets, output "invalid signature" and stop." -- the one place in this crate that step // is a runtime check, since the trait hands over a `&[u8]` rather than the `[u8; K_LEN]` - // the free functions take. + // [`verify_from_hash`] takes. let sig: &[u8; K_LEN] = sig.try_into().map_err(|_| SignatureError::SignatureVerificationFailed)?; let mut digest = [0u8; H_LEN]; self.hash.do_final_out(&mut digest); // Step 2.b: "If RSAVP1 outputs "signature representative out of range", output "invalid - // signature" and stop." The free function [`verify`] deliberately lets RSAVP1's own error - // through instead (see its docs); the trait's contract is the RFC's -- one "invalid - // signature" answer for every way a signature can fail -- so it is folded in here. + // signature" and stop." [`verify_from_hash`] deliberately lets RSAVP1's own error through + // instead (see its docs); the trait's contract is the RFC's -- one "invalid signature" + // answer for every way a signature can fail -- so it is folded in here. verify_from_hash::(&pk, &digest, sig) .map_err(|_| SignatureError::SignatureVerificationFailed) } } -/// RSASSA-PKCS1-V1_5-SIGN (RFC 8017 §8.2.1): `S = I2OSP(RSASP1(K, OS2IP(EM)), k)`, where -/// `EM = EMSA-PKCS1-V1_5-ENCODE(M, k)`. Step 1's two errors ("message too long" -- unreachable -/// here, since the encoding's own length is fixed at compile time by `K_LEN`, never computed from -/// `message`'s length -- and "RSA modulus too short") are folded into -/// [`emsa_pkcs1_v1_5_encode_from_hash`]'s `debug_assert`, not raised here as a runtime error, for -/// the same reason given there. -/// -/// Hashes `message` (EMSA-PKCS1-v1_5 step 1) and hands the digest to [`sign_from_hash`]. -pub fn sign< - H: Hash + HashAlgParams + AlgorithmOID + Default, - const H_LEN: usize, - const T_LEN: usize, - const L: usize, - const L2: usize, - const L21: usize, - const HALF: usize, - const HALF2: usize, - const HALF21: usize, - const K_LEN: usize, ->( - sk: &RsaPrivateKey, - message: &[u8], -) -> Result<[u8; K_LEN], SignatureError> { - let mut digest = [0u8; H_LEN]; - H::default().hash_out(message, &mut digest); - sign_from_hash::(sk, &digest) -} - -/// [`sign`] given the message's hash `digest` (`H`'s output over the message) instead of the -/// message itself -- for a caller that hashed the message incrementally, such as a streaming -/// `Signer`. The `H` bound is only what [`emsa_pkcs1_v1_5_encode_from_hash`] needs to build the +/// RSASSA-PKCS1-V1_5-SIGN (RFC 8017 §8.2.1), `S = I2OSP(RSASP1(K, OS2IP(EM)), k)` with +/// `EM = EMSA-PKCS1-V1_5-ENCODE(M, k)`, given the message's hash `digest` (`H`'s output over `M`) +/// rather than `M` itself: the entry point for a caller that hashed the message incrementally +/// (the [`Signer`] impl) or already holds the digest. Step 1's two errors ("message too long" -- +/// unreachable, since the encoding's length is fixed at compile time by `K_LEN` -- and "RSA +/// modulus too short") are folded into [`emsa_pkcs1_v1_5_encode_from_hash`]'s `debug_assert`, not +/// raised here as a runtime error, for the reason given there. The `H` bound is only what [`emsa_pkcs1_v1_5_encode_from_hash`] needs to build the /// `DigestInfo`; no hashing happens here. pub fn sign_from_hash< H: HashAlgParams + AlgorithmOID, @@ -240,41 +216,20 @@ pub fn sign_from_hash< Ok(be_bytes_from_limbs::(&s)) } -/// RSASSA-PKCS1-V1_5-VERIFY (RFC 8017 §8.2.2): recovers `EM' = I2OSP(RSAVP1((n, e), OS2IP(S)), -/// k)` and checks it against `message` via [`emsa_pkcs1_v1_5_verify_from_hash`] -- a decode, not -/// RFC 8017's own step 4 (re-encode `message` and compare bytes to `EM'`), because a byte +/// RSASSA-PKCS1-V1_5-VERIFY (RFC 8017 §8.2.2), given the message's hash `digest` rather than the +/// message (the counterpart of [`sign_from_hash`]): recovers `EM' = I2OSP(RSAVP1((n, e), +/// OS2IP(S)), k)` and checks it against `digest` via [`emsa_pkcs1_v1_5_verify_from_hash`] -- a +/// decode, not RFC 8017's own step 4 (re-encode and compare bytes to `EM'`), because a byte /// comparison against this crate's own (always-`NULL`-including) encoding would reject an /// otherwise-valid signature whose `DigestInfo` omits the `AlgorithmIdentifier`'s `NULL` -/// parameters -- a real-world leniency [`emsa_pkcs1_v1_5_verify_from_hash`]'s docs explain. Step -/// 1's length check (`S` must be exactly -/// `k` octets) doesn't apply: `signature` is already a fixed `K_LEN`-byte array, not an -/// arbitrary-length octet string, so a wrong length is a compile-time type error at the call site -/// instead. Step 2's "signature representative out of range" surfaces as [`rsavp1`]'s own `Err`, -/// propagated directly rather than folded into "invalid signature": a caller working through -/// CAVP/wycheproof-style vectors needs to tell "malformed input" apart from "well-formed but -/// wrong", the same distinction RFC 8017 itself draws by giving the range check its own error -/// text. -/// -/// Hashes `message` and hands the digest to [`verify_from_hash`]. -pub fn verify< - H: Hash + HashAlgParams + AlgorithmOID + Default, - const H_LEN: usize, - const L: usize, - const L2: usize, - const L21: usize, - const K_LEN: usize, ->( - pk: &RsaPublicKey, - message: &[u8], - signature: &[u8; K_LEN], -) -> Result<(), SignatureError> { - let mut digest = [0u8; H_LEN]; - H::default().hash_out(message, &mut digest); - verify_from_hash::(pk, &digest, signature) -} - -/// [`verify`] given the message's hash `digest` instead of the message -- the counterpart of -/// [`sign_from_hash`], for a streaming `SignatureVerifier`. +/// parameters -- a real-world leniency that function's docs explain. Step 1's length check (`S` +/// must be exactly `k` octets) doesn't apply here: `signature` is a fixed `K_LEN`-byte array, so a +/// wrong length is a type error at the call site; the [`SignatureVerifier`] impl, which takes a +/// `&[u8]`, performs it. Step 2's "signature representative out of range" surfaces as +/// [`rsavp1`]'s own `Err`, propagated directly rather than folded into "invalid signature": a +/// caller working through CAVP/wycheproof-style vectors needs to tell "malformed input" apart from +/// "well-formed but wrong", the same distinction RFC 8017 itself draws by giving the range check +/// its own error text (the trait impl folds it, per step 2.b). pub fn verify_from_hash< H: AlgorithmOID, const H_LEN: usize, diff --git a/crypto/rsa/src/rsassa_pss.rs b/crypto/rsa/src/rsassa_pss.rs index c3c19426..0370ad5c 100644 --- a/crypto/rsa/src/rsassa_pss.rs +++ b/crypto/rsa/src/rsassa_pss.rs @@ -4,10 +4,11 @@ //! (`8 + H_LEN + S_LEN`); a concrete modulus size wires these to literals (RSA-2048/SHA-256 in //! [`crate::rsa_2048`]). //! -//! As in [`crate::rsassa_pkcs1_v1_5`], the free functions take a whole message (and, for -//! signing, an explicit RNG or salt) while [`RSASSA_PSS`] implements `bouncycastle_core`'s -//! [`Signer`]/[`SignatureVerifier`] traits over the same widths, streaming the message and -//! drawing its salt from the library's default RNG. Both go through the `*_from_hash` functions. +//! As in [`crate::rsassa_pkcs1_v1_5`], [`RSASSA_PSS`] implements `bouncycastle_core`'s +//! [`Signer`]/[`SignatureVerifier`] traits over those widths on top of the `*_from_hash` +//! functions, which take the message hash rather than the message; the salt comes from the +//! library's default RNG unless the caller supplies one ([`RSASSA_PSS::sign_randomized`], +//! [`RSASSA_PSS::set_signer_salt`]). use crate::codec::{be_bytes_from_limbs, limbs_from_be_bytes}; use crate::emsa_pss::{emsa_pss_encode_from_hash, emsa_pss_verify_from_hash}; @@ -20,7 +21,7 @@ use bouncycastle_core::traits::{ use bouncycastle_rng::DefaultRNG; /// Streaming state for RSASSA-PSS's [`Signer`] and [`SignatureVerifier`] impls, at the widths the -/// const parameters fix (the list [`sign`] takes, plus the key encoding lengths `SK_LEN`/`PK_LEN` +/// const parameters fix (the list [`sign_from_hash`] takes, plus the key encoding lengths `SK_LEN`/`PK_LEN` /// the key traits are indexed by). The same one-type-both-roles shape as /// [`crate::rsassa_pkcs1_v1_5::RSASSA_PKCS1_v1_5`], whose docs cover the `sk`/`pk` arrangement, /// the ignored `ctx`, the naming, and the cloned key; concrete pairings are aliases such as @@ -314,52 +315,10 @@ where } /// RSASSA-PSS-SIGN (RFC 8017 §8.1.1) with the salt supplied directly rather than drawn from an -/// RNG: EMSA-PSS is randomized only in its choice of salt (§9.1's own note 5), so fixing it makes -/// this deterministic and directly testable against a known salt. [`sign`] is the RNG-backed -/// entry point real callers want. -/// -/// Hashes `message` (EMSA-PSS step 2) and hands `mHash` to [`sign_from_hash_with_salt`]. -pub fn sign_with_salt< - H: Hash + Default, - const H_LEN: usize, - const SEED_LEN: usize, - const S_LEN: usize, - const M_PRIME_LEN: usize, - const DB_LEN: usize, - const L: usize, - const L2: usize, - const L21: usize, - const HALF: usize, - const HALF2: usize, - const HALF21: usize, - const K_LEN: usize, ->( - sk: &RsaPrivateKey, - message: &[u8], - salt: &[u8; S_LEN], -) -> Result<[u8; K_LEN], SignatureError> { - let mut m_hash = [0u8; H_LEN]; - H::default().hash_out(message, &mut m_hash); - sign_from_hash_with_salt::< - H, - H_LEN, - SEED_LEN, - S_LEN, - M_PRIME_LEN, - DB_LEN, - L, - L2, - L21, - HALF, - HALF2, - HALF21, - K_LEN, - >(sk, &m_hash, salt) -} - -/// [`sign_with_salt`] given the message's hash `m_hash` (`H`'s output over the message) instead of -/// the message itself -- for a caller that hashed the message incrementally, such as a streaming -/// `Signer`. +/// RNG, given the message's hash `m_hash` (`H`'s output over the message) rather than the message +/// itself -- what the [`Signer`] impl's `sign_final` calls once it has hashed the streamed +/// message and settled the salt. EMSA-PSS is randomized only in its choice of salt (§9.1's own +/// note 5), so a fixed salt makes this deterministic and directly testable against a known salt. pub fn sign_from_hash_with_salt< H: Hash + Default, const H_LEN: usize, @@ -387,49 +346,9 @@ pub fn sign_from_hash_with_salt< Ok(be_bytes_from_limbs::(&s)) } -/// RSASSA-PSS-SIGN (RFC 8017 §8.1.1), drawing a fresh `S_LEN`-byte salt from `rng` for each -/// signature (step 4 of EMSA-PSS-ENCODE). Hashes `message` and hands `mHash` to -/// [`sign_from_hash`]. -pub fn sign< - H: Hash + Default, - const H_LEN: usize, - const SEED_LEN: usize, - const S_LEN: usize, - const M_PRIME_LEN: usize, - const DB_LEN: usize, - const L: usize, - const L2: usize, - const L21: usize, - const HALF: usize, - const HALF2: usize, - const HALF21: usize, - const K_LEN: usize, ->( - sk: &RsaPrivateKey, - message: &[u8], - rng: &mut dyn RNG, -) -> Result<[u8; K_LEN], SignatureError> { - let mut m_hash = [0u8; H_LEN]; - H::default().hash_out(message, &mut m_hash); - sign_from_hash::< - H, - H_LEN, - SEED_LEN, - S_LEN, - M_PRIME_LEN, - DB_LEN, - L, - L2, - L21, - HALF, - HALF2, - HALF21, - K_LEN, - >(sk, &m_hash, rng) -} - -/// [`sign`] given the message's hash `m_hash` instead of the message: draws the salt from `rng` -/// (EMSA-PSS-ENCODE step 4) and hands both to [`sign_from_hash_with_salt`]. +/// RSASSA-PSS-SIGN (RFC 8017 §8.1.1) given the message's hash `m_hash` instead of the message: +/// draws a fresh `S_LEN`-byte salt from `rng` (EMSA-PSS-ENCODE step 4) and hands both to +/// [`sign_from_hash_with_salt`]. pub fn sign_from_hash< H: Hash + Default, const H_LEN: usize, @@ -468,35 +387,11 @@ pub fn sign_from_hash< >(sk, m_hash, &salt) } -/// RSASSA-PSS-VERIFY (RFC 8017 §8.1.2): recovers `EM = I2OSP(RSAVP1((n, e), OS2IP(S)), emLen)` -/// and checks it against `message` via EMSA-PSS-VERIFY, which recovers the salt from `EM` itself -/// (EMSA-PSS's own verification operation, §9.1.2) rather than needing it supplied. Hashes -/// `message` and hands `mHash` to [`verify_from_hash`]. -pub fn verify< - H: Hash + Default, - const H_LEN: usize, - const SEED_LEN: usize, - const S_LEN: usize, - const M_PRIME_LEN: usize, - const DB_LEN: usize, - const L: usize, - const L2: usize, - const L21: usize, - const K_LEN: usize, ->( - pk: &RsaPublicKey, - message: &[u8], - signature: &[u8; K_LEN], -) -> Result<(), SignatureError> { - let mut m_hash = [0u8; H_LEN]; - H::default().hash_out(message, &mut m_hash); - verify_from_hash::( - pk, &m_hash, signature, - ) -} - -/// [`verify`] given the message's hash `m_hash` instead of the message -- the counterpart of -/// [`sign_from_hash`], for a streaming `SignatureVerifier`. +/// RSASSA-PSS-VERIFY (RFC 8017 §8.1.2) given the message's hash `m_hash` instead of the message +/// (the counterpart of [`sign_from_hash`]): recovers `EM = I2OSP(RSAVP1((n, e), OS2IP(S)), +/// emLen)` and checks it against `m_hash` via EMSA-PSS-VERIFY, which recovers the salt from `EM` +/// itself (§9.1.2) rather than needing it supplied. RSAVP1's range error propagates as its own +/// `Err`, as in [`crate::rsassa_pkcs1_v1_5::verify_from_hash`]. pub fn verify_from_hash< H: Hash + Default, const H_LEN: usize, diff --git a/crypto/rsa/src/rsassa_pss_shake.rs b/crypto/rsa/src/rsassa_pss_shake.rs index d72ecebe..08cc0819 100644 --- a/crypto/rsa/src/rsassa_pss_shake.rs +++ b/crypto/rsa/src/rsassa_pss_shake.rs @@ -2,8 +2,9 @@ //! generation function -- `id-RSASSA-PSS-SHAKE128`/`id-RSASSA-PSS-SHAKE256` (RFC 8702 §3.2.1). //! Otherwise identical to [`crate::rsassa_pss`] (RFC 8017 §8.1): same RSASP1/RSAVP1 orchestration, //! same fresh-salt-per-signature approach, just built on [`crate::emsa_pss_shake`] in place of -//! [`crate::emsa_pss`] -- and the same free-function/[`RSASSA_PSS_SHAKE`]-trait-type split, -//! with `X: XOF` in place of `H: Hash` and no `SEED_LEN` (there is no MGF1 counter to size). +//! [`crate::emsa_pss`] -- and the same [`RSASSA_PSS_SHAKE`] trait type over `*_from_hash` +//! functions, with `X: XOF` in place of `H: Hash` and no `SEED_LEN` (there is no MGF1 counter to +//! size). use crate::codec::{be_bytes_from_limbs, limbs_from_be_bytes}; use crate::emsa_pss_shake::{emsa_pss_encode_shake_from_hash, emsa_pss_verify_shake_from_hash}; @@ -19,7 +20,7 @@ use bouncycastle_rng::DefaultRNG; /// [`crate::rsassa_pss::RSASSA_PSS`] (whose docs cover the shared behaviour, including where the /// salt comes from and the [`Self::sign_randomized`]/[`Self::set_signer_salt`] ways to control /// it) built on the SHAKE-native encoding instead. `X`'s `Hash` methods (a `XOF` is a `Hash`) -/// absorb the streamed message; its `H_LEN`-byte output is `mHash`, as in the free functions. +/// absorb the streamed message; its `H_LEN`-byte output is `mHash`. /// Concrete pairings are aliases such as `crate::rsa_2048::RSASSA_PSS_SHAKE128`. #[allow(non_camel_case_types)] pub struct RSASSA_PSS_SHAKE< @@ -281,50 +282,10 @@ where } } -/// RSASSA-PSS-SIGN (RFC 8017 §8.1.1) with the salt supplied directly rather than drawn from an -/// RNG, mirroring [`crate::rsassa_pss::sign_with_salt`]: EMSA-PSS is randomized only in its choice -/// of salt, so fixing it makes this deterministic and directly testable. [`sign`] is the -/// RNG-backed entry point real callers want. Hashes `message` (EMSA-PSS step 2) and hands `mHash` -/// to [`sign_from_hash_with_salt`]. -pub fn sign_with_salt< - X: XOF + Default, - const H_LEN: usize, - const S_LEN: usize, - const M_PRIME_LEN: usize, - const DB_LEN: usize, - const L: usize, - const L2: usize, - const L21: usize, - const HALF: usize, - const HALF2: usize, - const HALF21: usize, - const K_LEN: usize, ->( - sk: &RsaPrivateKey, - message: &[u8], - salt: &[u8; S_LEN], -) -> Result<[u8; K_LEN], SignatureError> { - let mut m_hash = [0u8; H_LEN]; - X::default().hash_out(message, &mut m_hash); - sign_from_hash_with_salt::< - X, - H_LEN, - S_LEN, - M_PRIME_LEN, - DB_LEN, - L, - L2, - L21, - HALF, - HALF2, - HALF21, - K_LEN, - >(sk, &m_hash, salt) -} - -/// [`sign_with_salt`] given the message's hash `m_hash` (`X`'s `H_LEN`-byte output over the -/// message) instead of the message itself -- for a caller that hashed the message incrementally, -/// such as a streaming `Signer`. +/// RSASSA-PSS-SIGN (RFC 8017 §8.1.1) with the salt supplied directly, given the message's hash +/// `m_hash` (`X`'s `H_LEN`-byte output over the message) rather than the message -- mirroring +/// [`crate::rsassa_pss::sign_from_hash_with_salt`], and what the [`Signer`] impl's `sign_final` +/// calls. pub fn sign_from_hash_with_salt< X: XOF + Default, const H_LEN: usize, @@ -351,37 +312,10 @@ pub fn sign_from_hash_with_salt< Ok(be_bytes_from_limbs::(&s)) } -/// RSASSA-PSS-SIGN (RFC 8017 §8.1.1), drawing a fresh `S_LEN`-byte salt from `rng` for each -/// signature (step 4 of EMSA-PSS-ENCODE). RFC 8702 §3.2.1 fixes `S_LEN` at 32 bytes for -/// `id-RSASSA-PSS-SHAKE128` and 64 for `id-RSASSA-PSS-SHAKE256`. Hashes `message` and hands -/// `mHash` to [`sign_from_hash`]. -pub fn sign< - X: XOF + Default, - const H_LEN: usize, - const S_LEN: usize, - const M_PRIME_LEN: usize, - const DB_LEN: usize, - const L: usize, - const L2: usize, - const L21: usize, - const HALF: usize, - const HALF2: usize, - const HALF21: usize, - const K_LEN: usize, ->( - sk: &RsaPrivateKey, - message: &[u8], - rng: &mut dyn RNG, -) -> Result<[u8; K_LEN], SignatureError> { - let mut m_hash = [0u8; H_LEN]; - X::default().hash_out(message, &mut m_hash); - sign_from_hash::( - sk, &m_hash, rng, - ) -} - -/// [`sign`] given the message's hash `m_hash` instead of the message: draws the salt from `rng` -/// (EMSA-PSS-ENCODE step 4) and hands both to [`sign_from_hash_with_salt`]. +/// RSASSA-PSS-SIGN (RFC 8017 §8.1.1) given the message's hash `m_hash`: draws a fresh +/// `S_LEN`-byte salt from `rng` (EMSA-PSS-ENCODE step 4; RFC 8702 §3.2.1 fixes `S_LEN` at 32 bytes +/// for `id-RSASSA-PSS-SHAKE128` and 64 for `id-RSASSA-PSS-SHAKE256`) and hands both to +/// [`sign_from_hash_with_salt`]. pub fn sign_from_hash< X: XOF + Default, const H_LEN: usize, @@ -418,33 +352,9 @@ pub fn sign_from_hash< >(sk, m_hash, &salt) } -/// RSASSA-PSS-VERIFY (RFC 8017 §8.1.2), mirroring [`crate::rsassa_pss::verify`] but built on the -/// SHAKE-native EMSA-PSS-VERIFY, which recovers the salt from `EM` itself. Hashes `message` and -/// hands `mHash` to [`verify_from_hash`]. -pub fn verify< - X: XOF + Default, - const H_LEN: usize, - const S_LEN: usize, - const M_PRIME_LEN: usize, - const DB_LEN: usize, - const L: usize, - const L2: usize, - const L21: usize, - const K_LEN: usize, ->( - pk: &RsaPublicKey, - message: &[u8], - signature: &[u8; K_LEN], -) -> Result<(), SignatureError> { - let mut m_hash = [0u8; H_LEN]; - X::default().hash_out(message, &mut m_hash); - verify_from_hash::( - pk, &m_hash, signature, - ) -} - -/// [`verify`] given the message's hash `m_hash` instead of the message -- the counterpart of -/// [`sign_from_hash`], for a streaming `SignatureVerifier`. +/// RSASSA-PSS-VERIFY (RFC 8017 §8.1.2) given the message's hash `m_hash`, mirroring +/// [`crate::rsassa_pss::verify_from_hash`] but built on the SHAKE-native EMSA-PSS-VERIFY, which +/// recovers the salt from `EM` itself. pub fn verify_from_hash< X: XOF + Default, const H_LEN: usize, diff --git a/crypto/rsa/tests/rsa_1024_tests.rs b/crypto/rsa/tests/rsa_1024_tests.rs index 95203fc2..267f25f4 100644 --- a/crypto/rsa/tests/rsa_1024_tests.rs +++ b/crypto/rsa/tests/rsa_1024_tests.rs @@ -11,7 +11,6 @@ use bouncycastle_core::traits::{SignaturePublicKey, SignatureVerifier}; use bouncycastle_hex::decode as hex_decode; use bouncycastle_rsa::rsa_1024::{ PK_LEN, RSASSA_PKCS1_v1_5_SHA256, RSASSA_PKCS1_v1_5_SHA384, Rsa1024PublicKey, - pkcs1_v1_5_verify_sha256, pkcs1_v1_5_verify_sha384, }; use serde_json::Value; use std::fs; @@ -81,14 +80,14 @@ fn run_sig_gen_group_as_verify_vectors( #[test] fn pkcs1_v1_5_sha256_accepts_genuine_sig_gen_signatures() { run_sig_gen_group_as_verify_vectors("SHA-256", |pk, msg, sig| { - pkcs1_v1_5_verify_sha256(pk, msg, sig).is_ok() + RSASSA_PKCS1_v1_5_SHA256::verify(pk, 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| { - pkcs1_v1_5_verify_sha384(pk, msg, sig).is_ok() + RSASSA_PKCS1_v1_5_SHA384::verify(pk, msg, None, sig).is_ok() }); } @@ -117,17 +116,17 @@ fn run_sig_gen_group_rejects_wrong_message( #[test] fn pkcs1_v1_5_sha256_rejects_wrong_message() { run_sig_gen_group_rejects_wrong_message("SHA-256", |pk, msg, sig| { - pkcs1_v1_5_verify_sha256(pk, msg, sig).is_ok() + RSASSA_PKCS1_v1_5_SHA256::verify(pk, msg, None, sig).is_ok() }); } -/// Mutation testing found that `pkcs1_v1_5_verify_sha384` had no rejection-path test of its own +/// 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| { - pkcs1_v1_5_verify_sha384(pk, msg, sig).is_ok() + RSASSA_PKCS1_v1_5_SHA384::verify(pk, msg, None, sig).is_ok() }); } @@ -136,27 +135,7 @@ fn pkcs1_v1_5_sha384_rejects_wrong_message() { // No `Signer` 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 // `SignatureVerifier` and `SignaturePublicKey` impls are checked directly against the same -// genuine Wycheproof material as the free functions. - -#[test] -fn trait_verify_accepts_genuine_sig_gen_signatures() { - run_sig_gen_group_as_verify_vectors("SHA-256", |pk, msg, sig| { - RSASSA_PKCS1_v1_5_SHA256::verify(pk, msg, None, sig).is_ok() - }); - run_sig_gen_group_as_verify_vectors("SHA-384", |pk, msg, sig| { - RSASSA_PKCS1_v1_5_SHA384::verify(pk, msg, None, sig).is_ok() - }); -} - -#[test] -fn trait_verify_rejects_wrong_message() { - run_sig_gen_group_rejects_wrong_message("SHA-256", |pk, msg, sig| { - RSASSA_PKCS1_v1_5_SHA256::verify(pk, msg, None, sig).is_ok() - }); - run_sig_gen_group_rejects_wrong_message("SHA-384", |pk, msg, sig| { - RSASSA_PKCS1_v1_5_SHA384::verify(pk, msg, None, sig).is_ok() - }); -} +// 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 "invalid signature", never accepted. diff --git a/crypto/rsa/tests/rsa_1536_tests.rs b/crypto/rsa/tests/rsa_1536_tests.rs index c93d5229..ca9a69e8 100644 --- a/crypto/rsa/tests/rsa_1536_tests.rs +++ b/crypto/rsa/tests/rsa_1536_tests.rs @@ -9,7 +9,7 @@ use bouncycastle_core::traits::{SignaturePublicKey, SignatureVerifier}; use bouncycastle_hex::decode as hex_decode; use bouncycastle_rsa::rsa_1536::{ PK_LEN, RSASSA_PKCS1_v1_5_SHA256, RSASSA_PKCS1_v1_5_SHA384, RSASSA_PKCS1_v1_5_SHA512, - Rsa1536PublicKey, pkcs1_v1_5_verify_sha256, pkcs1_v1_5_verify_sha384, pkcs1_v1_5_verify_sha512, + Rsa1536PublicKey, }; use serde_json::Value; use std::fs; @@ -79,21 +79,21 @@ fn run_sig_gen_group_as_verify_vectors( #[test] fn pkcs1_v1_5_sha256_accepts_genuine_sig_gen_signatures() { run_sig_gen_group_as_verify_vectors("SHA-256", |pk, msg, sig| { - pkcs1_v1_5_verify_sha256(pk, msg, sig).is_ok() + RSASSA_PKCS1_v1_5_SHA256::verify(pk, 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| { - pkcs1_v1_5_verify_sha384(pk, msg, sig).is_ok() + RSASSA_PKCS1_v1_5_SHA384::verify(pk, 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| { - pkcs1_v1_5_verify_sha512(pk, msg, sig).is_ok() + RSASSA_PKCS1_v1_5_SHA512::verify(pk, msg, None, sig).is_ok() }); } @@ -117,24 +117,24 @@ fn run_sig_gen_group_rejects_wrong_message( #[test] fn pkcs1_v1_5_sha256_rejects_wrong_message() { run_sig_gen_group_rejects_wrong_message("SHA-256", |pk, msg, sig| { - pkcs1_v1_5_verify_sha256(pk, msg, sig).is_ok() + RSASSA_PKCS1_v1_5_SHA256::verify(pk, msg, None, sig).is_ok() }); } -/// Mutation testing found that `pkcs1_v1_5_verify_sha384`/`_sha512` had no rejection-path test of +/// 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| { - pkcs1_v1_5_verify_sha384(pk, msg, sig).is_ok() + RSASSA_PKCS1_v1_5_SHA384::verify(pk, 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| { - pkcs1_v1_5_verify_sha512(pk, msg, sig).is_ok() + RSASSA_PKCS1_v1_5_SHA512::verify(pk, msg, None, sig).is_ok() }); } @@ -143,32 +143,6 @@ fn pkcs1_v1_5_sha512_rejects_wrong_message() { // 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_accepts_genuine_sig_gen_signatures() { - run_sig_gen_group_as_verify_vectors("SHA-256", |pk, msg, sig| { - RSASSA_PKCS1_v1_5_SHA256::verify(pk, msg, None, sig).is_ok() - }); - run_sig_gen_group_as_verify_vectors("SHA-384", |pk, msg, sig| { - RSASSA_PKCS1_v1_5_SHA384::verify(pk, msg, None, sig).is_ok() - }); - run_sig_gen_group_as_verify_vectors("SHA-512", |pk, msg, sig| { - RSASSA_PKCS1_v1_5_SHA512::verify(pk, msg, None, sig).is_ok() - }); -} - -#[test] -fn trait_verify_rejects_wrong_message() { - run_sig_gen_group_rejects_wrong_message("SHA-256", |pk, msg, sig| { - RSASSA_PKCS1_v1_5_SHA256::verify(pk, msg, None, sig).is_ok() - }); - run_sig_gen_group_rejects_wrong_message("SHA-384", |pk, msg, sig| { - RSASSA_PKCS1_v1_5_SHA384::verify(pk, msg, None, sig).is_ok() - }); - run_sig_gen_group_rejects_wrong_message("SHA-512", |pk, msg, sig| { - RSASSA_PKCS1_v1_5_SHA512::verify(pk, msg, None, sig).is_ok() - }); -} - #[test] fn trait_verify_rejects_truncated_signature() { run_sig_gen_group_as_verify_vectors("SHA-256", |pk, msg, sig| { 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 index 0f3ed66c..ff4fb121 100644 --- 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 @@ -14,13 +14,12 @@ //! the hash in question -- is checked against all of Wycheproof's real vectors for both hashes. use bouncycastle_core::errors::SignatureError; -use bouncycastle_core::traits::Signer; +use bouncycastle_core::traits::{SignatureVerifier, Signer}; use bouncycastle_core_test_framework::signature::TestFrameworkSignature; use bouncycastle_hex::decode as hex_decode; use bouncycastle_rsa::rsa_2048::{ PK_LEN, RSASSA_PKCS1_v1_5_SHA384, RSASSA_PKCS1_v1_5_SHA512, Rsa2048PrivateKey, - Rsa2048PublicKey, SIG_LEN, SK_LEN, pkcs1_v1_5_sign_sha384, pkcs1_v1_5_sign_sha512, - pkcs1_v1_5_verify_sha384, pkcs1_v1_5_verify_sha512, + Rsa2048PublicKey, SIG_LEN, SK_LEN, }; use serde_json::Value; use std::fs; @@ -99,18 +98,18 @@ fn genuine_key() -> Rsa2048PrivateKey { fn pkcs1_v1_5_sha384_round_trips() { let sk = genuine_key(); let pk = Rsa2048PublicKey::new(sk.n(), 0x10001).unwrap(); - let sig = pkcs1_v1_5_sign_sha384(&sk, b"hello").expect("signing must succeed"); - pkcs1_v1_5_verify_sha384(&pk, b"hello", &sig).expect("must verify"); - assert!(pkcs1_v1_5_verify_sha384(&pk, b"goodbye", &sig).is_err()); + let sig = RSASSA_PKCS1_v1_5_SHA384::sign(&sk, b"hello", None).expect("signing must succeed"); + RSASSA_PKCS1_v1_5_SHA384::verify(&pk, b"hello", None, &sig).expect("must verify"); + assert!(RSASSA_PKCS1_v1_5_SHA384::verify(&pk, b"goodbye", None, &sig).is_err()); } #[test] fn pkcs1_v1_5_sha512_round_trips() { let sk = genuine_key(); let pk = Rsa2048PublicKey::new(sk.n(), 0x10001).unwrap(); - let sig = pkcs1_v1_5_sign_sha512(&sk, b"hello").expect("signing must succeed"); - pkcs1_v1_5_verify_sha512(&pk, b"hello", &sig).expect("must verify"); - assert!(pkcs1_v1_5_verify_sha512(&pk, b"goodbye", &sig).is_err()); + let sig = RSASSA_PKCS1_v1_5_SHA512::sign(&sk, b"hello", None).expect("signing must succeed"); + RSASSA_PKCS1_v1_5_SHA512::verify(&pk, b"hello", None, &sig).expect("must verify"); + assert!(RSASSA_PKCS1_v1_5_SHA512::verify(&pk, b"goodbye", None, &sig).is_err()); } fn run_verify_vectors( @@ -183,7 +182,7 @@ fn run_verify_vectors( fn rsa_signature_sha384_wycheproof_vectors() { run_verify_vectors( "rsa_signature_2048_sha384_test.json", - |pk, msg, sig| pkcs1_v1_5_verify_sha384(pk, msg, sig).is_ok(), + |pk, msg, sig| RSASSA_PKCS1_v1_5_SHA384::verify(pk, msg, None, sig).is_ok(), "SHA-384", 258, 7, @@ -195,7 +194,7 @@ fn rsa_signature_sha384_wycheproof_vectors() { fn rsa_signature_sha512_wycheproof_vectors() { run_verify_vectors( "rsa_signature_2048_sha512_test.json", - |pk, msg, sig| pkcs1_v1_5_verify_sha512(pk, msg, sig).is_ok(), + |pk, msg, sig| RSASSA_PKCS1_v1_5_SHA512::verify(pk, msg, None, sig).is_ok(), "SHA-512", 259, 8, @@ -236,17 +235,3 @@ fn pkcs1_v1_5_sha384_sha512_trait_conformance_suite() { SIG_LEN, >(fixed_keypair, false); } - -#[test] -fn pkcs1_v1_5_sha384_sha512_trait_matches_free_functions() { - let (_, sk) = fixed_keypair().unwrap(); - let msg = b"same message, both APIs"; - assert_eq!( - RSASSA_PKCS1_v1_5_SHA384::sign(&sk, msg, None).unwrap(), - pkcs1_v1_5_sign_sha384(&sk, msg).unwrap() - ); - assert_eq!( - RSASSA_PKCS1_v1_5_SHA512::sign(&sk, msg, None).unwrap(), - pkcs1_v1_5_sign_sha512(&sk, msg).unwrap() - ); -} diff --git a/crypto/rsa/tests/rsa_2048_pkcs1_v1_5_tests.rs b/crypto/rsa/tests/rsa_2048_pkcs1_v1_5_tests.rs index 8d5fac46..a16b4df6 100644 --- a/crypto/rsa/tests/rsa_2048_pkcs1_v1_5_tests.rs +++ b/crypto/rsa/tests/rsa_2048_pkcs1_v1_5_tests.rs @@ -32,15 +32,16 @@ //! constructed edge case. use bouncycastle_core::errors::SignatureError; -use bouncycastle_core::traits::{SignatureVerifier, Signer}; +use bouncycastle_core::traits::{Hash, SignatureVerifier, Signer}; use bouncycastle_core_test_framework::signature::{ TestFrameworkSignature, TestFrameworkSignatureKeys, }; use bouncycastle_hex::decode as hex_decode; use bouncycastle_rsa::rsa_2048::{ PK_LEN, RSASSA_PKCS1_v1_5_SHA256, Rsa2048PrivateKey, Rsa2048PublicKey, SIG_LEN, SK_LEN, - pkcs1_v1_5_sign_sha256, pkcs1_v1_5_verify_sha256, }; +use bouncycastle_rsa::rsassa_pkcs1_v1_5; +use bouncycastle_sha2::SHA256; use serde_json::Value; use std::fs; use std::path::Path; @@ -145,7 +146,7 @@ fn pkcs1_v1_5_sig_gen_2048_sha256() { 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 = pkcs1_v1_5_sign_sha256(&sk, &msg).unwrap_or_else(|e| { + let sig = RSASSA_PKCS1_v1_5_SHA256::sign(&sk, &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"); @@ -153,78 +154,9 @@ fn pkcs1_v1_5_sig_gen_2048_sha256() { assert_eq!(num_tests, 8); } -#[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_missing_null = 0usize; - - for group in doc["testGroups"].as_array().unwrap() { - assert_eq!(group["sha"], "SHA-256"); - 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 = Rsa2048PublicKey::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(); - - // A signature of the wrong length cannot even be represented as this crate's fixed - // [u8; 256] type; that is itself correct rejection (RFC 8017 SS8.2.2 step 1). - 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 = pkcs1_v1_5_verify_sha256(&pk, &msg, &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; - } - "acceptable" => { - // The only "acceptable" verdict in this file is MissingNull (RFC 8017's - // AlgorithmIdentifier `parameters` field omitted rather than NULL); per this - // crate's explicit policy (see `emsa_pkcs1_v1_5::emsa_pkcs1_v1_5_verify`'s - // docs), that is accepted, not merely tolerated either way. Any other - // "acceptable" flag combination is an unreviewed case, not silently ignored. - 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, 259, "expected 257 + 1 + 1 tests across all three groups"); - assert_eq!(num_missing_null, 1); - assert_eq!(num_valid, 9); - assert_eq!(num_invalid, 249); -} - // ---- bouncycastle_core trait conformance ------------------------------------------------------ -/// The same genuine key pair as the free-function tests above, in the `fn() -> Result<(PK, SK)>` +/// 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<(Rsa2048PublicKey, Rsa2048PrivateKey), SignatureError> { let sk = wycheproof_key(); @@ -256,23 +188,19 @@ fn key_trait_boundary_conditions() { .test_keys::(fixed_keypair); } -/// The trait path and the free-function path are one computation: byte-identical signatures -/// (PKCS#1 v1.5 is deterministic) whether streamed or one-shot, and each side verifies the -/// other's output. +/// Streamed and one-shot signing are one computation: PKCS#1 v1.5 is deterministic, so the +/// chunked `sign_init`/`sign_update`/`sign_final` path reproduces `Signer::sign` byte for byte. #[test] -fn pkcs1_v1_5_sha256_trait_matches_free_functions() { +fn streamed_signature_equals_one_shot() { let (pk, sk) = fixed_keypair().unwrap(); - let msg = b"the same message, three ways"; - let free = pkcs1_v1_5_sign_sha256(&sk, msg).unwrap(); + let msg = b"the same message, two ways"; let one_shot = RSASSA_PKCS1_v1_5_SHA256::sign(&sk, msg, None).unwrap(); let mut signer = RSASSA_PKCS1_v1_5_SHA256::sign_init(&sk, None).unwrap(); signer.sign_update(&msg[..10]); signer.sign_update(&msg[10..]); let streamed = signer.sign_final().unwrap(); - assert_eq!(one_shot, free); - assert_eq!(streamed, free); - pkcs1_v1_5_verify_sha256(&pk, msg, &one_shot).unwrap(); - RSASSA_PKCS1_v1_5_SHA256::verify(&pk, msg, None, &free).unwrap(); + assert_eq!(streamed, one_shot); + RSASSA_PKCS1_v1_5_SHA256::verify(&pk, msg, None, &streamed).unwrap(); } /// RFC 8017 §8.2.2 step 1 ("If the length of the signature S is not k octets, output 'invalid @@ -308,12 +236,15 @@ fn trait_final_in_the_wrong_role_is_an_error() { assert!(matches!(signer.verify_final(&out), Err(SignatureError::GenericError(_)))); } -/// `rsa_signature_2048_sha256_test.json` again, this time through `SignatureVerifier::verify`'s -/// `&[u8]` signature: unlike [`rsa_signature_sha256_all_groups`], the wrong-length vectors reach -/// the verifier here and must come back as `SignatureVerificationFailed` (RFC 8017 §8.2.2 step -/// 1) rather than being rejected by the test's own `try_into`. +/// All three groups of `rsa_signature_2048_sha256_test.json` (259 vectors; the first group's key +/// is [`wycheproof_key`]'s, the other two are unrelated keys parsed from the JSON) through +/// `SignatureVerifier::verify`'s `&[u8]` signature, so the wrong-length vectors reach the +/// verifier and must come back as `SignatureVerificationFailed` (RFC 8017 §8.2.2 step 1). The one +/// "acceptable" vector is `MissingNull` (a `DigestInfo` whose `AlgorithmIdentifier` omits the +/// `NULL` parameters), accepted by this crate's explicit policy -- see +/// `emsa_pkcs1_v1_5::emsa_pkcs1_v1_5_verify_from_hash`'s docs. #[test] -fn rsa_signature_sha256_all_groups_via_trait() { +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"); @@ -335,8 +266,7 @@ fn rsa_signature_sha256_all_groups_via_trait() { let sig = hex_decode(test["sig"].as_str().unwrap()).unwrap(); let result = RSASSA_PKCS1_v1_5_SHA256::verify(&pk, &msg, None, &sig); match test["result"].as_str().unwrap() { - // "acceptable" is only ever MissingNull in this file, accepted by policy -- see - // rsa_signature_sha256_all_groups. + // "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; @@ -367,15 +297,19 @@ fn rsa_signature_sha256_all_groups_via_trait() { /// 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 free function deliberately surfaces RSAVP1's own -/// `DecodingError` so vector-driven callers can tell malformed from wrong -- see -/// `rsassa_pkcs1_v1_5::verify`'s docs. `0xff..ff` is `2^2048 - 1 >= n` for any 2048-bit `n`. +/// 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::default().hash_out(b"msg", &mut digest); assert!(matches!( - pkcs1_v1_5_verify_sha256(&pk, b"msg", &too_big), + rsassa_pkcs1_v1_5::verify_from_hash::( + &pk, &digest, &too_big + ), Err(SignatureError::DecodingError(_)) )); assert!(matches!( diff --git a/crypto/rsa/tests/rsa_2048_pss_sha384_sha512_tests.rs b/crypto/rsa/tests/rsa_2048_pss_sha384_sha512_tests.rs index c023968e..1fc199bb 100644 --- a/crypto/rsa/tests/rsa_2048_pss_sha384_sha512_tests.rs +++ b/crypto/rsa/tests/rsa_2048_pss_sha384_sha512_tests.rs @@ -13,13 +13,23 @@ use bouncycastle_hex::decode as hex_decode; use bouncycastle_rng::DefaultRNG; use bouncycastle_rsa::rsa_2048::{ PK_LEN, RSASSA_PSS_SHA384, RSASSA_PSS_SHA512, Rsa2048PrivateKey, Rsa2048PublicKey, SIG_LEN, - SK_LEN, pss_sign_sha384, pss_sign_sha384_with_salt, pss_sign_sha512, pss_sign_sha512_with_salt, - pss_verify_sha384, pss_verify_sha512, + SK_LEN, }; use serde_json::Value; use std::fs; use std::path::Path; +/// Signs through the streaming trait path with a fixed salt (`set_signer_salt`) -- the +/// deterministic PSS mode, for tests against a known salt. Returns `sign_final`'s `Result`. +macro_rules! sign_with_salt { + ($ty:ty, $sk:expr, $msg:expr, $salt:expr) => {{ + let mut signer = <$ty>::sign_init($sk, None).unwrap(); + signer.set_signer_salt($salt); + signer.sign_update($msg); + signer.sign_final() + }}; +} + const TEST_DATA_PATH_RELATIVE: &str = "../../../wycheproof/testvectors_v1"; const TEST_DATA_PATH: &str = "../wycheproof/testvectors_v1"; @@ -93,9 +103,10 @@ fn pss_sha384_fixed_salt_round_trips() { let sk = genuine_key(); let pk = Rsa2048PublicKey::new(sk.n(), 0x10001).unwrap(); let salt = [0x42u8; 48]; - let sig = pss_sign_sha384_with_salt(&sk, b"hello", &salt).expect("signing must succeed"); - pss_verify_sha384(&pk, b"hello", &sig).expect("must verify"); - assert!(pss_verify_sha384(&pk, b"goodbye", &sig).is_err()); + let sig = + sign_with_salt!(RSASSA_PSS_SHA384, &sk, b"hello", salt).expect("signing must succeed"); + RSASSA_PSS_SHA384::verify(&pk, b"hello", None, &sig).expect("must verify"); + assert!(RSASSA_PSS_SHA384::verify(&pk, b"goodbye", None, &sig).is_err()); } #[test] @@ -103,11 +114,13 @@ fn pss_sha384_rng_produces_fresh_salts_that_both_verify() { let sk = genuine_key(); let pk = Rsa2048PublicKey::new(sk.n(), 0x10001).unwrap(); let mut rng = DefaultRNG::default(); - let sig_a = pss_sign_sha384(&sk, b"hello", &mut rng).expect("signing must succeed"); - let sig_b = pss_sign_sha384(&sk, b"hello", &mut rng).expect("signing must succeed"); + let sig_a = + RSASSA_PSS_SHA384::sign_randomized(&sk, b"hello", &mut rng).expect("signing must succeed"); + let sig_b = + RSASSA_PSS_SHA384::sign_randomized(&sk, b"hello", &mut rng).expect("signing must succeed"); assert_ne!(sig_a, sig_b); - pss_verify_sha384(&pk, b"hello", &sig_a).expect("sig_a must verify"); - pss_verify_sha384(&pk, b"hello", &sig_b).expect("sig_b must verify"); + RSASSA_PSS_SHA384::verify(&pk, b"hello", None, &sig_a).expect("sig_a must verify"); + RSASSA_PSS_SHA384::verify(&pk, b"hello", None, &sig_b).expect("sig_b must verify"); } #[test] @@ -115,9 +128,10 @@ fn pss_sha512_fixed_salt_round_trips() { let sk = genuine_key(); let pk = Rsa2048PublicKey::new(sk.n(), 0x10001).unwrap(); let salt = [0x42u8; 64]; - let sig = pss_sign_sha512_with_salt(&sk, b"hello", &salt).expect("signing must succeed"); - pss_verify_sha512(&pk, b"hello", &sig).expect("must verify"); - assert!(pss_verify_sha512(&pk, b"goodbye", &sig).is_err()); + let sig = + sign_with_salt!(RSASSA_PSS_SHA512, &sk, b"hello", salt).expect("signing must succeed"); + RSASSA_PSS_SHA512::verify(&pk, b"hello", None, &sig).expect("must verify"); + assert!(RSASSA_PSS_SHA512::verify(&pk, b"goodbye", None, &sig).is_err()); } #[test] @@ -125,11 +139,13 @@ fn pss_sha512_rng_produces_fresh_salts_that_both_verify() { let sk = genuine_key(); let pk = Rsa2048PublicKey::new(sk.n(), 0x10001).unwrap(); let mut rng = DefaultRNG::default(); - let sig_a = pss_sign_sha512(&sk, b"hello", &mut rng).expect("signing must succeed"); - let sig_b = pss_sign_sha512(&sk, b"hello", &mut rng).expect("signing must succeed"); + let sig_a = + RSASSA_PSS_SHA512::sign_randomized(&sk, b"hello", &mut rng).expect("signing must succeed"); + let sig_b = + RSASSA_PSS_SHA512::sign_randomized(&sk, b"hello", &mut rng).expect("signing must succeed"); assert_ne!(sig_a, sig_b); - pss_verify_sha512(&pk, b"hello", &sig_a).expect("sig_a must verify"); - pss_verify_sha512(&pk, b"hello", &sig_b).expect("sig_b must verify"); + RSASSA_PSS_SHA512::verify(&pk, b"hello", None, &sig_a).expect("sig_a must verify"); + RSASSA_PSS_SHA512::verify(&pk, b"hello", None, &sig_b).expect("sig_b must verify"); } #[test] @@ -162,7 +178,7 @@ fn rsa_pss_sha384_mgf1_48_wycheproof_vectors() { continue; }; - let verified = pss_verify_sha384(&pk, &msg, &sig).is_ok(); + let verified = RSASSA_PSS_SHA384::verify(&pk, &msg, None, &sig).is_ok(); match test["result"].as_str().unwrap() { "valid" => { assert!(verified, "tcId {tc_id}: expected valid, got invalid"); @@ -216,14 +232,16 @@ fn pss_sha384_sha512_trait_conformance_suite() { } #[test] -fn pss_sha384_sha512_trait_and_free_functions_cross_verify() { +fn pss_sha384_and_sha512_reject_each_others_signatures() { let (pk, sk) = fixed_keypair().unwrap(); let msg = b"PSS across both APIs"; - pss_verify_sha384(&pk, msg, &RSASSA_PSS_SHA384::sign(&sk, msg, None).unwrap()).unwrap(); - pss_verify_sha512(&pk, msg, &RSASSA_PSS_SHA512::sign(&sk, msg, None).unwrap()).unwrap(); + RSASSA_PSS_SHA384::verify(&pk, msg, None, &RSASSA_PSS_SHA384::sign(&sk, msg, None).unwrap()) + .unwrap(); + RSASSA_PSS_SHA512::verify(&pk, msg, None, &RSASSA_PSS_SHA512::sign(&sk, msg, None).unwrap()) + .unwrap(); let mut rng = DefaultRNG::default(); - let free_384 = pss_sign_sha384(&sk, msg, &mut rng).unwrap(); - let free_512 = pss_sign_sha512(&sk, msg, &mut rng).unwrap(); + let free_384 = RSASSA_PSS_SHA384::sign_randomized(&sk, msg, &mut rng).unwrap(); + let free_512 = RSASSA_PSS_SHA512::sign_randomized(&sk, msg, &mut rng).unwrap(); RSASSA_PSS_SHA384::verify(&pk, msg, None, &free_384).unwrap(); RSASSA_PSS_SHA512::verify(&pk, msg, None, &free_512).unwrap(); // The two hash pairings are distinct encodings: neither accepts the other's signature. diff --git a/crypto/rsa/tests/rsa_2048_pss_shake128_tests.rs b/crypto/rsa/tests/rsa_2048_pss_shake128_tests.rs index 0dc0d724..4bac4edc 100644 --- a/crypto/rsa/tests/rsa_2048_pss_shake128_tests.rs +++ b/crypto/rsa/tests/rsa_2048_pss_shake128_tests.rs @@ -6,18 +6,30 @@ //! checked against all of Wycheproof's real vectors. use bouncycastle_core::errors::SignatureError; -use bouncycastle_core::traits::{RNG, SignatureVerifier, Signer}; +use bouncycastle_core::traits::{Hash, RNG, SignatureVerifier, Signer}; use bouncycastle_core_test_framework::signature::TestFrameworkSignature; use bouncycastle_hex::decode as hex_decode; use bouncycastle_rng::DefaultRNG; use bouncycastle_rsa::rsa_2048::{ PK_LEN, RSASSA_PSS_SHAKE128, Rsa2048PrivateKey, Rsa2048PublicKey, SIG_LEN, SK_LEN, - pss_shake128_sign, pss_shake128_sign_with_salt, pss_shake128_verify, }; +use bouncycastle_rsa::rsassa_pss_shake; +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_signer_salt`) -- the +/// deterministic PSS mode, for tests against a known salt. Returns `sign_final`'s `Result`. +macro_rules! sign_with_salt { + ($ty:ty, $sk:expr, $msg:expr, $salt:expr) => {{ + let mut signer = <$ty>::sign_init($sk, None).unwrap(); + signer.set_signer_salt($salt); + signer.sign_update($msg); + signer.sign_final() + }}; +} + const TEST_DATA_PATH_RELATIVE: &str = "../../../wycheproof/testvectors_v1"; const TEST_DATA_PATH: &str = "../wycheproof/testvectors_v1"; @@ -93,15 +105,15 @@ fn pss_shake128_sign_with_fixed_salt_round_trips() { let pk = Rsa2048PublicKey::new(sk.n(), 0x10001).unwrap(); let salt = [0x42u8; 32]; - let sig = pss_shake128_sign_with_salt(&sk, b"the message to sign", &salt) + let sig = sign_with_salt!(RSASSA_PSS_SHAKE128, &sk, b"the message to sign", salt) .expect("signing must succeed"); - pss_shake128_verify(&pk, b"the message to sign", &sig).expect("must verify"); + RSASSA_PSS_SHAKE128::verify(&pk, b"the message to sign", None, &sig).expect("must verify"); // Deterministic given the same salt. - let sig2 = pss_shake128_sign_with_salt(&sk, b"the message to sign", &salt).unwrap(); + let sig2 = sign_with_salt!(RSASSA_PSS_SHAKE128, &sk, b"the message to sign", salt).unwrap(); assert_eq!(sig, sig2); - assert!(pss_shake128_verify(&pk, b"a different message", &sig).is_err()); + assert!(RSASSA_PSS_SHAKE128::verify(&pk, b"a different message", None, &sig).is_err()); } #[test] @@ -110,11 +122,13 @@ fn pss_shake128_sign_with_rng_produces_fresh_salts_that_both_verify() { let pk = Rsa2048PublicKey::new(sk.n(), 0x10001).unwrap(); let mut rng = DefaultRNG::default(); - let sig_a = pss_shake128_sign(&sk, b"hello", &mut rng).expect("signing must succeed"); - let sig_b = pss_shake128_sign(&sk, b"hello", &mut rng).expect("signing must succeed"); + let sig_a = RSASSA_PSS_SHAKE128::sign_randomized(&sk, b"hello", &mut rng) + .expect("signing must succeed"); + let sig_b = RSASSA_PSS_SHAKE128::sign_randomized(&sk, b"hello", &mut rng) + .expect("signing must succeed"); assert_ne!(sig_a, sig_b, "PSS is randomized: two signatures of the same message must differ"); - pss_shake128_verify(&pk, b"hello", &sig_a).expect("sig_a must verify"); - pss_shake128_verify(&pk, b"hello", &sig_b).expect("sig_b must verify"); + RSASSA_PSS_SHAKE128::verify(&pk, b"hello", None, &sig_a).expect("sig_a must verify"); + RSASSA_PSS_SHAKE128::verify(&pk, b"hello", None, &sig_b).expect("sig_b must verify"); } #[test] @@ -147,7 +161,7 @@ fn rsa_pss_2048_shake128_wycheproof_vectors() { continue; }; - let verified = pss_shake128_verify(&pk, &msg, &sig).is_ok(); + let verified = RSASSA_PSS_SHAKE128::verify(&pk, &msg, None, &sig).is_ok(); match test["result"].as_str().unwrap() { "valid" => { assert!(verified, "tcId {tc_id}: expected valid, got invalid"); @@ -191,16 +205,6 @@ fn pss_shake128_trait_conformance_suite() { >(fixed_keypair, true); } -#[test] -fn pss_shake128_trait_and_free_functions_cross_verify() { - let (pk, sk) = fixed_keypair().unwrap(); - let msg = b"PSS-SHAKE128 across both APIs"; - pss_shake128_verify(&pk, msg, &RSASSA_PSS_SHAKE128::sign(&sk, msg, None).unwrap()).unwrap(); - let from_free = pss_shake128_sign(&sk, msg, &mut DefaultRNG::default()).unwrap(); - RSASSA_PSS_SHAKE128::verify(&pk, msg, None, &from_free).unwrap(); - assert!(RSASSA_PSS_SHAKE128::verify(&pk, b"other", None, &from_free).is_err()); -} - /// A fixed-output RNG (all-`0x42` bytes), as `bouncycastle-ecdsa`'s tests use: pins that /// `sign_randomized` takes its salt from the caller's RNG and nowhere else. struct FixedRng; @@ -236,8 +240,9 @@ impl RNG for FixedRng { } /// `set_signer_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 fixed-salt free -/// function over the same salt, while an unfixed streamed signature is fresh. +/// `set_signer_rnd`): the result is deterministic and byte-identical to the generic +/// `rsassa_pss_shake::sign_from_hash_with_salt` over the same digest and salt, while an unfixed +/// streamed signature is fresh. #[test] fn set_signer_salt_fixes_the_salt_on_the_streaming_path() { let (pk, sk) = fixed_keypair().unwrap(); @@ -249,7 +254,24 @@ fn set_signer_salt_fixes_the_salt_on_the_streaming_path() { signer.sign_update(&msg[..11]); signer.sign_update(&msg[11..]); let sig = signer.sign_final().unwrap(); - assert_eq!(sig, pss_shake128_sign_with_salt(&sk, msg, &salt).unwrap()); + let mut digest = [0u8; 32]; + SHAKE128::default().hash_out(msg, &mut digest); + let expected = rsassa_pss_shake::sign_from_hash_with_salt::< + SHAKE128, + 32, + 32, + 72, + 223, + 32, + 64, + 65, + 16, + 32, + 33, + 256, + >(&sk, &digest, &salt) + .unwrap(); + assert_eq!(sig, expected); RSASSA_PSS_SHAKE128::verify(&pk, msg, None, &sig).unwrap(); let mut fresh = RSASSA_PSS_SHAKE128::sign_init(&sk, None).unwrap(); @@ -265,20 +287,22 @@ fn set_signer_salt_fixes_the_salt_on_the_streaming_path() { /// `sign_randomized` 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 through both the trait and the free-function verifier. +/// is fresh per call and verifies. #[test] fn sign_randomized_takes_the_salt_from_the_callers_rng() { let (pk, sk) = fixed_keypair().unwrap(); let msg = b"caller-supplied RNG"; let from_fixed_rng = RSASSA_PSS_SHAKE128::sign_randomized(&sk, msg, &mut FixedRng).unwrap(); - assert_eq!(from_fixed_rng, pss_shake128_sign_with_salt(&sk, msg, &[0x42u8; 32]).unwrap()); + assert_eq!( + from_fixed_rng, + sign_with_salt!(RSASSA_PSS_SHAKE128, &sk, msg, [0x42u8; 32]).unwrap() + ); let mut rng = DefaultRNG::default(); let a = RSASSA_PSS_SHAKE128::sign_randomized(&sk, msg, &mut rng).unwrap(); let b = RSASSA_PSS_SHAKE128::sign_randomized(&sk, msg, &mut rng).unwrap(); assert_ne!(a, b); RSASSA_PSS_SHAKE128::verify(&pk, msg, None, &a).unwrap(); - pss_shake128_verify(&pk, msg, &b).unwrap(); + RSASSA_PSS_SHAKE128::verify(&pk, msg, None, &b).unwrap(); assert!(RSASSA_PSS_SHAKE128::verify(&pk, b"other", None, &a).is_err()); - let _ = pss_shake128_sign; // the free functions stay the explicit-RNG one-shot path } diff --git a/crypto/rsa/tests/rsa_2048_pss_tests.rs b/crypto/rsa/tests/rsa_2048_pss_tests.rs index df08a905..afe1be0a 100644 --- a/crypto/rsa/tests/rsa_2048_pss_tests.rs +++ b/crypto/rsa/tests/rsa_2048_pss_tests.rs @@ -11,18 +11,30 @@ //! by comparing moduli in Python before writing this file). use bouncycastle_core::errors::SignatureError; -use bouncycastle_core::traits::{RNG, SignatureVerifier, Signer}; +use bouncycastle_core::traits::{Hash, RNG, SignatureVerifier, Signer}; use bouncycastle_core_test_framework::signature::TestFrameworkSignature; use bouncycastle_hex::decode as hex_decode; use bouncycastle_rng::DefaultRNG; use bouncycastle_rsa::rsa_2048::{ PK_LEN, RSASSA_PSS_SHA256, Rsa2048PrivateKey, Rsa2048PublicKey, SIG_LEN, SK_LEN, - pss_sign_sha256, pss_sign_sha256_with_salt, pss_verify_sha256, }; +use bouncycastle_rsa::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_signer_salt`) -- the +/// deterministic PSS mode, for tests against a known salt. Returns `sign_final`'s `Result`. +macro_rules! sign_with_salt { + ($ty:ty, $sk:expr, $msg:expr, $salt:expr) => {{ + let mut signer = <$ty>::sign_init($sk, None).unwrap(); + signer.set_signer_salt($salt); + signer.sign_update($msg); + signer.sign_final() + }}; +} + const TEST_DATA_PATH_RELATIVE: &str = "../../../wycheproof/testvectors_v1"; const TEST_DATA_PATH: &str = "../wycheproof/testvectors_v1"; @@ -98,15 +110,15 @@ fn pss_sign_with_fixed_salt_round_trips() { let pk = Rsa2048PublicKey::new(sk.n(), 0x10001).unwrap(); let salt = [0x42u8; 32]; - let sig = pss_sign_sha256_with_salt(&sk, b"the message to sign", &salt) + let sig = sign_with_salt!(RSASSA_PSS_SHA256, &sk, b"the message to sign", salt) .expect("signing must succeed"); - pss_verify_sha256(&pk, b"the message to sign", &sig).expect("must verify"); + RSASSA_PSS_SHA256::verify(&pk, b"the message to sign", None, &sig).expect("must verify"); // Deterministic given the same salt. - let sig2 = pss_sign_sha256_with_salt(&sk, b"the message to sign", &salt).unwrap(); + let sig2 = sign_with_salt!(RSASSA_PSS_SHA256, &sk, b"the message to sign", salt).unwrap(); assert_eq!(sig, sig2); - assert!(pss_verify_sha256(&pk, b"a different message", &sig).is_err()); + assert!(RSASSA_PSS_SHA256::verify(&pk, b"a different message", None, &sig).is_err()); } #[test] @@ -115,11 +127,13 @@ fn pss_sign_with_rng_produces_fresh_salts_that_both_verify() { let pk = Rsa2048PublicKey::new(sk.n(), 0x10001).unwrap(); let mut rng = DefaultRNG::default(); - let sig_a = pss_sign_sha256(&sk, b"hello", &mut rng).expect("signing must succeed"); - let sig_b = pss_sign_sha256(&sk, b"hello", &mut rng).expect("signing must succeed"); + let sig_a = + RSASSA_PSS_SHA256::sign_randomized(&sk, b"hello", &mut rng).expect("signing must succeed"); + let sig_b = + RSASSA_PSS_SHA256::sign_randomized(&sk, b"hello", &mut rng).expect("signing must succeed"); assert_ne!(sig_a, sig_b, "PSS is randomized: two signatures of the same message must differ"); - pss_verify_sha256(&pk, b"hello", &sig_a).expect("sig_a must verify"); - pss_verify_sha256(&pk, b"hello", &sig_b).expect("sig_b must verify"); + RSASSA_PSS_SHA256::verify(&pk, b"hello", None, &sig_a).expect("sig_a must verify"); + RSASSA_PSS_SHA256::verify(&pk, b"hello", None, &sig_b).expect("sig_b must verify"); } #[test] @@ -152,7 +166,7 @@ fn rsa_pss_sha256_mgf1_32_wycheproof_vectors() { continue; }; - let verified = pss_verify_sha256(&pk, &msg, &sig).is_ok(); + let verified = RSASSA_PSS_SHA256::verify(&pk, &msg, None, &sig).is_ok(); match test["result"].as_str().unwrap() { "valid" => { assert!(verified, "tcId {tc_id}: expected valid, got invalid"); @@ -196,19 +210,6 @@ fn pss_sha256_trait_conformance_suite() { >(fixed_keypair, true); } -/// The trait's default-RNG salt and the free functions' caller-supplied RNG produce signatures -/// each side's verifier accepts: one encoding, two ways in. -#[test] -fn pss_sha256_trait_and_free_functions_cross_verify() { - let (pk, sk) = fixed_keypair().unwrap(); - let msg = b"PSS across both APIs"; - let from_trait = RSASSA_PSS_SHA256::sign(&sk, msg, None).unwrap(); - pss_verify_sha256(&pk, msg, &from_trait).unwrap(); - let from_free = pss_sign_sha256(&sk, msg, &mut DefaultRNG::default()).unwrap(); - RSASSA_PSS_SHA256::verify(&pk, msg, None, &from_free).unwrap(); - assert!(RSASSA_PSS_SHA256::verify(&pk, b"other", None, &from_free).is_err()); -} - /// A fixed-output RNG (all-`0x42` bytes), as `bouncycastle-ecdsa`'s tests use: pins that /// `sign_randomized` takes its salt from the caller's RNG and nowhere else. struct FixedRng; @@ -244,8 +245,9 @@ impl RNG for FixedRng { } /// `set_signer_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 fixed-salt free -/// function over the same salt, while an unfixed streamed signature is fresh. +/// `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_signer_salt_fixes_the_salt_on_the_streaming_path() { let (pk, sk) = fixed_keypair().unwrap(); @@ -257,7 +259,25 @@ fn set_signer_salt_fixes_the_salt_on_the_streaming_path() { signer.sign_update(&msg[..11]); signer.sign_update(&msg[11..]); let sig = signer.sign_final().unwrap(); - assert_eq!(sig, pss_sign_sha256_with_salt(&sk, msg, &salt).unwrap()); + let mut digest = [0u8; 32]; + SHA256::default().hash_out(msg, &mut digest); + let expected = rsassa_pss::sign_from_hash_with_salt::< + SHA256, + 32, + 36, + 32, + 72, + 223, + 32, + 64, + 65, + 16, + 32, + 33, + 256, + >(&sk, &digest, &salt) + .unwrap(); + assert_eq!(sig, expected); RSASSA_PSS_SHA256::verify(&pk, msg, None, &sig).unwrap(); let mut fresh = RSASSA_PSS_SHA256::sign_init(&sk, None).unwrap(); @@ -273,20 +293,19 @@ fn set_signer_salt_fixes_the_salt_on_the_streaming_path() { /// `sign_randomized` 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 through both the trait and the free-function verifier. +/// is fresh per call and verifies. #[test] fn sign_randomized_takes_the_salt_from_the_callers_rng() { let (pk, sk) = fixed_keypair().unwrap(); let msg = b"caller-supplied RNG"; let from_fixed_rng = RSASSA_PSS_SHA256::sign_randomized(&sk, msg, &mut FixedRng).unwrap(); - assert_eq!(from_fixed_rng, pss_sign_sha256_with_salt(&sk, msg, &[0x42u8; 32]).unwrap()); + assert_eq!(from_fixed_rng, sign_with_salt!(RSASSA_PSS_SHA256, &sk, msg, [0x42u8; 32]).unwrap()); let mut rng = DefaultRNG::default(); let a = RSASSA_PSS_SHA256::sign_randomized(&sk, msg, &mut rng).unwrap(); let b = RSASSA_PSS_SHA256::sign_randomized(&sk, msg, &mut rng).unwrap(); assert_ne!(a, b); RSASSA_PSS_SHA256::verify(&pk, msg, None, &a).unwrap(); - pss_verify_sha256(&pk, msg, &b).unwrap(); + RSASSA_PSS_SHA256::verify(&pk, msg, None, &b).unwrap(); assert!(RSASSA_PSS_SHA256::verify(&pk, b"other", None, &a).is_err()); - let _ = pss_sign_sha256; // the free functions stay the explicit-RNG one-shot path } diff --git a/crypto/rsa/tests/rsa_3072_pss_shake128_tests.rs b/crypto/rsa/tests/rsa_3072_pss_shake128_tests.rs index 424c465b..8ad96a0c 100644 --- a/crypto/rsa/tests/rsa_3072_pss_shake128_tests.rs +++ b/crypto/rsa/tests/rsa_3072_pss_shake128_tests.rs @@ -10,12 +10,22 @@ use bouncycastle_hex::decode as hex_decode; use bouncycastle_rng::DefaultRNG; use bouncycastle_rsa::rsa_3072::{ PK_LEN, RSASSA_PSS_SHAKE128, Rsa3072PrivateKey, Rsa3072PublicKey, SIG_LEN, SK_LEN, - pss_shake128_sign, pss_shake128_sign_with_salt, pss_shake128_verify, }; use serde_json::Value; use std::fs; use std::path::Path; +/// Signs through the streaming trait path with a fixed salt (`set_signer_salt`) -- the +/// deterministic PSS mode, for tests against a known salt. Returns `sign_final`'s `Result`. +macro_rules! sign_with_salt { + ($ty:ty, $sk:expr, $msg:expr, $salt:expr) => {{ + let mut signer = <$ty>::sign_init($sk, None).unwrap(); + signer.set_signer_salt($salt); + signer.sign_update($msg); + signer.sign_final() + }}; +} + const TEST_DATA_PATH_RELATIVE: &str = "../../../wycheproof/testvectors_v1"; const TEST_DATA_PATH: &str = "../wycheproof/testvectors_v1"; @@ -101,14 +111,14 @@ fn pss_shake128_sign_with_fixed_salt_round_trips() { let pk = Rsa3072PublicKey::new(sk.n(), 0x10001).unwrap(); let salt = [0x42u8; 32]; - let sig = pss_shake128_sign_with_salt(&sk, b"the message to sign", &salt) + let sig = sign_with_salt!(RSASSA_PSS_SHAKE128, &sk, b"the message to sign", salt) .expect("signing must succeed"); - pss_shake128_verify(&pk, b"the message to sign", &sig).expect("must verify"); + RSASSA_PSS_SHAKE128::verify(&pk, b"the message to sign", None, &sig).expect("must verify"); - let sig2 = pss_shake128_sign_with_salt(&sk, b"the message to sign", &salt).unwrap(); + let sig2 = sign_with_salt!(RSASSA_PSS_SHAKE128, &sk, b"the message to sign", salt).unwrap(); assert_eq!(sig, sig2); - assert!(pss_shake128_verify(&pk, b"a different message", &sig).is_err()); + assert!(RSASSA_PSS_SHAKE128::verify(&pk, b"a different message", None, &sig).is_err()); } #[test] @@ -117,11 +127,13 @@ fn pss_shake128_sign_with_rng_produces_fresh_salts_that_both_verify() { let pk = Rsa3072PublicKey::new(sk.n(), 0x10001).unwrap(); let mut rng = DefaultRNG::default(); - let sig_a = pss_shake128_sign(&sk, b"hello", &mut rng).expect("signing must succeed"); - let sig_b = pss_shake128_sign(&sk, b"hello", &mut rng).expect("signing must succeed"); + let sig_a = RSASSA_PSS_SHAKE128::sign_randomized(&sk, b"hello", &mut rng) + .expect("signing must succeed"); + let sig_b = RSASSA_PSS_SHAKE128::sign_randomized(&sk, b"hello", &mut rng) + .expect("signing must succeed"); assert_ne!(sig_a, sig_b, "PSS is randomized: two signatures of the same message must differ"); - pss_shake128_verify(&pk, b"hello", &sig_a).expect("sig_a must verify"); - pss_shake128_verify(&pk, b"hello", &sig_b).expect("sig_b must verify"); + RSASSA_PSS_SHAKE128::verify(&pk, b"hello", None, &sig_a).expect("sig_a must verify"); + RSASSA_PSS_SHAKE128::verify(&pk, b"hello", None, &sig_b).expect("sig_b must verify"); } #[test] @@ -154,7 +166,7 @@ fn rsa_pss_3072_shake128_wycheproof_vectors() { continue; }; - let verified = pss_shake128_verify(&pk, &msg, &sig).is_ok(); + let verified = RSASSA_PSS_SHAKE128::verify(&pk, &msg, None, &sig).is_ok(); match test["result"].as_str().unwrap() { "valid" => { assert!(verified, "tcId {tc_id}: expected valid, got invalid"); @@ -194,12 +206,3 @@ fn pss_shake128_trait_conformance_suite() { SIG_LEN, >(fixed_keypair, false); } - -#[test] -fn pss_shake128_trait_and_free_functions_cross_verify() { - let (pk, sk) = fixed_keypair().unwrap(); - let msg = b"PSS-SHAKE128 at RSA-3072, both APIs"; - pss_shake128_verify(&pk, msg, &RSASSA_PSS_SHAKE128::sign(&sk, msg, None).unwrap()).unwrap(); - let from_free = pss_shake128_sign(&sk, msg, &mut DefaultRNG::default()).unwrap(); - RSASSA_PSS_SHAKE128::verify(&pk, msg, None, &from_free).unwrap(); -} diff --git a/crypto/rsa/tests/rsa_3072_tests.rs b/crypto/rsa/tests/rsa_3072_tests.rs index bf395bb2..0106303d 100644 --- a/crypto/rsa/tests/rsa_3072_tests.rs +++ b/crypto/rsa/tests/rsa_3072_tests.rs @@ -3,7 +3,7 @@ //! (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_sign_sha{256,384,512}[_with_salt]` function is actually exercised at least once). +//! 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 @@ -20,15 +20,23 @@ use bouncycastle_rng::DefaultRNG; 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, Rsa3072PrivateKey, Rsa3072PublicKey, - SIG_LEN, SK_LEN, pkcs1_v1_5_sign_sha256, pkcs1_v1_5_sign_sha384, pkcs1_v1_5_sign_sha512, - pkcs1_v1_5_verify_sha256, pkcs1_v1_5_verify_sha384, pkcs1_v1_5_verify_sha512, pss_sign_sha256, - pss_sign_sha256_with_salt, pss_sign_sha384, pss_sign_sha384_with_salt, pss_sign_sha512, - pss_sign_sha512_with_salt, pss_verify_sha256, pss_verify_sha384, pss_verify_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_signer_salt`) -- the +/// deterministic PSS mode, for tests against a known salt. Returns `sign_final`'s `Result`. +macro_rules! sign_with_salt { + ($ty:ty, $sk:expr, $msg:expr, $salt:expr) => {{ + let mut signer = <$ty>::sign_init($sk, None).unwrap(); + signer.set_signer_salt($salt); + signer.sign_update($msg); + signer.sign_final() + }}; +} + const TEST_DATA_PATH_RELATIVE: &str = "../../../wycheproof/testvectors_v1"; const TEST_DATA_PATH: &str = "../wycheproof/testvectors_v1"; @@ -123,7 +131,7 @@ fn pkcs1_v1_5_sig_gen_3072_sha256() { 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 = pkcs1_v1_5_sign_sha256(&sk, &msg).unwrap_or_else(|e| { + let sig = RSASSA_PKCS1_v1_5_SHA256::sign(&sk, &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"); @@ -135,14 +143,14 @@ fn pkcs1_v1_5_sig_gen_3072_sha256() { fn pkcs1_v1_5_sha384_and_sha512_round_trip() { let sk = genuine_key(); let pk = Rsa3072PublicKey::new(sk.n(), 0x10001).unwrap(); - let sig384 = pkcs1_v1_5_sign_sha384(&sk, b"hello").unwrap(); - pkcs1_v1_5_verify_sha384(&pk, b"hello", &sig384).unwrap(); - let sig512 = pkcs1_v1_5_sign_sha512(&sk, b"hello").unwrap(); - pkcs1_v1_5_verify_sha512(&pk, b"hello", &sig512).unwrap(); + let sig384 = RSASSA_PKCS1_v1_5_SHA384::sign(&sk, b"hello", None).unwrap(); + RSASSA_PKCS1_v1_5_SHA384::verify(&pk, b"hello", None, &sig384).unwrap(); + let sig512 = RSASSA_PKCS1_v1_5_SHA512::sign(&sk, b"hello", None).unwrap(); + RSASSA_PKCS1_v1_5_SHA512::verify(&pk, b"hello", None, &sig512).unwrap(); } -/// Mutation testing found that `pss_sign_sha256_with_salt`, `pss_sign_sha384` (the RNG variant), -/// `pss_sign_sha512_with_salt`, and `pss_verify_sha384`/`pss_verify_sha512`'s rejection paths were +/// 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. @@ -154,9 +162,10 @@ fn pss_sha256_fixed_salt_round_trips() { let sk = genuine_key(); let pk = Rsa3072PublicKey::new(sk.n(), 0x10001).unwrap(); let salt = [0x22u8; 32]; - let sig = pss_sign_sha256_with_salt(&sk, b"hello", &salt).expect("signing must succeed"); - pss_verify_sha256(&pk, b"hello", &sig).expect("must verify"); - assert!(pss_verify_sha256(&pk, b"goodbye", &sig).is_err()); + let sig = + sign_with_salt!(RSASSA_PSS_SHA256, &sk, b"hello", salt).expect("signing must succeed"); + RSASSA_PSS_SHA256::verify(&pk, b"hello", None, &sig).expect("must verify"); + assert!(RSASSA_PSS_SHA256::verify(&pk, b"goodbye", None, &sig).is_err()); } #[test] @@ -164,11 +173,13 @@ fn pss_sha256_rng_produces_fresh_salts_that_both_verify() { let sk = genuine_key(); let pk = Rsa3072PublicKey::new(sk.n(), 0x10001).unwrap(); let mut rng = DefaultRNG::default(); - let sig_a = pss_sign_sha256(&sk, b"hello", &mut rng).expect("signing must succeed"); - let sig_b = pss_sign_sha256(&sk, b"hello", &mut rng).expect("signing must succeed"); + let sig_a = + RSASSA_PSS_SHA256::sign_randomized(&sk, b"hello", &mut rng).expect("signing must succeed"); + let sig_b = + RSASSA_PSS_SHA256::sign_randomized(&sk, b"hello", &mut rng).expect("signing must succeed"); assert_ne!(sig_a, sig_b, "PSS is randomized: two signatures of the same message must differ"); - pss_verify_sha256(&pk, b"hello", &sig_a).expect("sig_a must verify"); - pss_verify_sha256(&pk, b"hello", &sig_b).expect("sig_b must verify"); + RSASSA_PSS_SHA256::verify(&pk, b"hello", None, &sig_a).expect("sig_a must verify"); + RSASSA_PSS_SHA256::verify(&pk, b"hello", None, &sig_b).expect("sig_b must verify"); } #[test] @@ -176,9 +187,10 @@ fn pss_sha384_fixed_salt_round_trips() { let sk = genuine_key(); let pk = Rsa3072PublicKey::new(sk.n(), 0x10001).unwrap(); let salt = [0x11u8; 48]; - let sig = pss_sign_sha384_with_salt(&sk, b"hello", &salt).expect("signing must succeed"); - pss_verify_sha384(&pk, b"hello", &sig).expect("must verify"); - assert!(pss_verify_sha384(&pk, b"goodbye", &sig).is_err()); + let sig = + sign_with_salt!(RSASSA_PSS_SHA384, &sk, b"hello", salt).expect("signing must succeed"); + RSASSA_PSS_SHA384::verify(&pk, b"hello", None, &sig).expect("must verify"); + assert!(RSASSA_PSS_SHA384::verify(&pk, b"goodbye", None, &sig).is_err()); } #[test] @@ -186,11 +198,13 @@ fn pss_sha384_rng_produces_fresh_salts_that_both_verify() { let sk = genuine_key(); let pk = Rsa3072PublicKey::new(sk.n(), 0x10001).unwrap(); let mut rng = DefaultRNG::default(); - let sig_a = pss_sign_sha384(&sk, b"hello", &mut rng).expect("signing must succeed"); - let sig_b = pss_sign_sha384(&sk, b"hello", &mut rng).expect("signing must succeed"); + let sig_a = + RSASSA_PSS_SHA384::sign_randomized(&sk, b"hello", &mut rng).expect("signing must succeed"); + let sig_b = + RSASSA_PSS_SHA384::sign_randomized(&sk, b"hello", &mut rng).expect("signing must succeed"); assert_ne!(sig_a, sig_b, "PSS is randomized: two signatures of the same message must differ"); - pss_verify_sha384(&pk, b"hello", &sig_a).expect("sig_a must verify"); - pss_verify_sha384(&pk, b"hello", &sig_b).expect("sig_b must verify"); + RSASSA_PSS_SHA384::verify(&pk, b"hello", None, &sig_a).expect("sig_a must verify"); + RSASSA_PSS_SHA384::verify(&pk, b"hello", None, &sig_b).expect("sig_b must verify"); } #[test] @@ -198,9 +212,10 @@ fn pss_sha512_fixed_salt_round_trips() { let sk = genuine_key(); let pk = Rsa3072PublicKey::new(sk.n(), 0x10001).unwrap(); let salt = [0x33u8; 64]; - let sig = pss_sign_sha512_with_salt(&sk, b"hello", &salt).expect("signing must succeed"); - pss_verify_sha512(&pk, b"hello", &sig).expect("must verify"); - assert!(pss_verify_sha512(&pk, b"goodbye", &sig).is_err()); + let sig = + sign_with_salt!(RSASSA_PSS_SHA512, &sk, b"hello", salt).expect("signing must succeed"); + RSASSA_PSS_SHA512::verify(&pk, b"hello", None, &sig).expect("must verify"); + assert!(RSASSA_PSS_SHA512::verify(&pk, b"goodbye", None, &sig).is_err()); } #[test] @@ -208,11 +223,13 @@ fn pss_sha512_rng_produces_fresh_salts_that_both_verify() { let sk = genuine_key(); let pk = Rsa3072PublicKey::new(sk.n(), 0x10001).unwrap(); let mut rng = DefaultRNG::default(); - let sig_a = pss_sign_sha512(&sk, b"hello", &mut rng).expect("signing must succeed"); - let sig_b = pss_sign_sha512(&sk, b"hello", &mut rng).expect("signing must succeed"); + let sig_a = + RSASSA_PSS_SHA512::sign_randomized(&sk, b"hello", &mut rng).expect("signing must succeed"); + let sig_b = + RSASSA_PSS_SHA512::sign_randomized(&sk, b"hello", &mut rng).expect("signing must succeed"); assert_ne!(sig_a, sig_b, "PSS is randomized: two signatures of the same message must differ"); - pss_verify_sha512(&pk, b"hello", &sig_a).expect("sig_a must verify"); - pss_verify_sha512(&pk, b"hello", &sig_b).expect("sig_b must verify"); + RSASSA_PSS_SHA512::verify(&pk, b"hello", None, &sig_a).expect("sig_a must verify"); + RSASSA_PSS_SHA512::verify(&pk, b"hello", None, &sig_b).expect("sig_b must verify"); } fn run_pkcs1_v1_5_verify_vectors( @@ -274,14 +291,14 @@ fn run_pkcs1_v1_5_verify_vectors( fn rsa_signature_3072_sha256_wycheproof_vectors() { run_pkcs1_v1_5_verify_vectors( "rsa_signature_3072_sha256_test.json", - |pk, msg, sig| pkcs1_v1_5_verify_sha256(pk, msg, sig).is_ok(), + |pk, msg, sig| RSASSA_PKCS1_v1_5_SHA256::verify(pk, msg, None, sig).is_ok(), "SHA-256", 8, 250, ); } -/// Mutation testing found `pkcs1_v1_5_verify_sha384` had no rejection-path coverage at this +/// 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. @@ -289,14 +306,14 @@ fn rsa_signature_3072_sha256_wycheproof_vectors() { fn rsa_signature_3072_sha384_wycheproof_vectors() { run_pkcs1_v1_5_verify_vectors( "rsa_signature_3072_sha384_test.json", - |pk, msg, sig| pkcs1_v1_5_verify_sha384(pk, msg, sig).is_ok(), + |pk, msg, sig| RSASSA_PKCS1_v1_5_SHA384::verify(pk, msg, None, sig).is_ok(), "SHA-384", 7, 251, ); } -/// As [`rsa_signature_3072_sha384_wycheproof_vectors`], for `pkcs1_v1_5_verify_sha512`. This +/// 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. @@ -304,7 +321,7 @@ fn rsa_signature_3072_sha384_wycheproof_vectors() { fn rsa_signature_3072_sha512_wycheproof_vectors() { run_pkcs1_v1_5_verify_vectors( "rsa_signature_3072_sha512_test.json", - |pk, msg, sig| pkcs1_v1_5_verify_sha512(pk, msg, sig).is_ok(), + |pk, msg, sig| RSASSA_PKCS1_v1_5_SHA512::verify(pk, msg, None, sig).is_ok(), "SHA-512", 8, 251, @@ -335,7 +352,7 @@ fn rsa_pss_3072_sha256_mgf1_32_wycheproof_vectors() { num_invalid += 1; continue; }; - let verified = pss_verify_sha256(&pk, &msg, &sig).is_ok(); + let verified = RSASSA_PSS_SHA256::verify(&pk, &msg, None, &sig).is_ok(); match test["result"].as_str().unwrap() { "valid" => { assert!(verified, "tcId {tc_id}: expected valid"); @@ -432,18 +449,3 @@ fn key_trait_boundary_conditions() { TestFrameworkSignatureKeys::new() .test_keys::(fixed_keypair); } - -/// Trait and free-function paths agree at this width: identical PKCS#1 v1.5 signatures, and -/// PSS signatures each side's verifier accepts. -#[test] -fn trait_matches_free_functions() { - let (pk, sk) = fixed_keypair().unwrap(); - let msg = b"RSA-3072, both APIs"; - assert_eq!( - RSASSA_PKCS1_v1_5_SHA256::sign(&sk, msg, None).unwrap(), - pkcs1_v1_5_sign_sha256(&sk, msg).unwrap() - ); - pss_verify_sha256(&pk, msg, &RSASSA_PSS_SHA256::sign(&sk, msg, None).unwrap()).unwrap(); - let from_free = pss_sign_sha256(&sk, msg, &mut DefaultRNG::default()).unwrap(); - RSASSA_PSS_SHA256::verify(&pk, msg, None, &from_free).unwrap(); -} diff --git a/crypto/rsa/tests/rsa_4096_pss_shake256_tests.rs b/crypto/rsa/tests/rsa_4096_pss_shake256_tests.rs index 038dea36..0270d366 100644 --- a/crypto/rsa/tests/rsa_4096_pss_shake256_tests.rs +++ b/crypto/rsa/tests/rsa_4096_pss_shake256_tests.rs @@ -6,14 +6,22 @@ use bouncycastle_core::traits::{SignatureVerifier, Signer}; use bouncycastle_hex::decode as hex_decode; use bouncycastle_rng::DefaultRNG; -use bouncycastle_rsa::rsa_4096::{ - RSASSA_PSS_SHAKE256, Rsa4096PrivateKey, Rsa4096PublicKey, pss_shake256_sign, - pss_shake256_sign_with_salt, pss_shake256_verify, -}; +use bouncycastle_rsa::rsa_4096::{RSASSA_PSS_SHAKE256, Rsa4096PrivateKey, Rsa4096PublicKey}; use serde_json::Value; use std::fs; use std::path::Path; +/// Signs through the streaming trait path with a fixed salt (`set_signer_salt`) -- the +/// deterministic PSS mode, for tests against a known salt. Returns `sign_final`'s `Result`. +macro_rules! sign_with_salt { + ($ty:ty, $sk:expr, $msg:expr, $salt:expr) => {{ + let mut signer = <$ty>::sign_init($sk, None).unwrap(); + signer.set_signer_salt($salt); + signer.sign_update($msg); + signer.sign_final() + }}; +} + const TEST_DATA_PATH_RELATIVE: &str = "../../../wycheproof/testvectors_v1"; const TEST_DATA_PATH: &str = "../wycheproof/testvectors_v1"; @@ -109,14 +117,14 @@ fn pss_shake256_sign_with_fixed_salt_round_trips() { let pk = Rsa4096PublicKey::new(sk.n(), 0x10001).unwrap(); let salt = [0x42u8; 64]; - let sig = pss_shake256_sign_with_salt(&sk, b"the message to sign", &salt) + let sig = sign_with_salt!(RSASSA_PSS_SHAKE256, &sk, b"the message to sign", salt) .expect("signing must succeed"); - pss_shake256_verify(&pk, b"the message to sign", &sig).expect("must verify"); + RSASSA_PSS_SHAKE256::verify(&pk, b"the message to sign", None, &sig).expect("must verify"); - let sig2 = pss_shake256_sign_with_salt(&sk, b"the message to sign", &salt).unwrap(); + let sig2 = sign_with_salt!(RSASSA_PSS_SHAKE256, &sk, b"the message to sign", salt).unwrap(); assert_eq!(sig, sig2); - assert!(pss_shake256_verify(&pk, b"a different message", &sig).is_err()); + assert!(RSASSA_PSS_SHAKE256::verify(&pk, b"a different message", None, &sig).is_err()); } #[test] @@ -125,11 +133,13 @@ fn pss_shake256_sign_with_rng_produces_fresh_salts_that_both_verify() { let pk = Rsa4096PublicKey::new(sk.n(), 0x10001).unwrap(); let mut rng = DefaultRNG::default(); - let sig_a = pss_shake256_sign(&sk, b"hello", &mut rng).expect("signing must succeed"); - let sig_b = pss_shake256_sign(&sk, b"hello", &mut rng).expect("signing must succeed"); + let sig_a = RSASSA_PSS_SHAKE256::sign_randomized(&sk, b"hello", &mut rng) + .expect("signing must succeed"); + let sig_b = RSASSA_PSS_SHAKE256::sign_randomized(&sk, b"hello", &mut rng) + .expect("signing must succeed"); assert_ne!(sig_a, sig_b, "PSS is randomized: two signatures of the same message must differ"); - pss_shake256_verify(&pk, b"hello", &sig_a).expect("sig_a must verify"); - pss_shake256_verify(&pk, b"hello", &sig_b).expect("sig_b must verify"); + RSASSA_PSS_SHAKE256::verify(&pk, b"hello", None, &sig_a).expect("sig_a must verify"); + RSASSA_PSS_SHAKE256::verify(&pk, b"hello", None, &sig_b).expect("sig_b must verify"); } #[test] @@ -162,7 +172,7 @@ fn rsa_pss_4096_shake256_wycheproof_vectors() { continue; }; - let verified = pss_shake256_verify(&pk, &msg, &sig).is_ok(); + let verified = RSASSA_PSS_SHAKE256::verify(&pk, &msg, None, &sig).is_ok(); match test["result"].as_str().unwrap() { "valid" => { assert!(verified, "tcId {tc_id}: expected valid, got invalid"); @@ -186,16 +196,17 @@ fn rsa_pss_4096_shake256_wycheproof_vectors() { /// 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 -/// trip and cross-verification against the free functions. +/// trips through `Signer::sign` and `sign_randomized`. #[test] -fn pss_shake256_trait_round_trip_and_cross_verify() { +fn pss_shake256_trait_round_trips() { let sk = genuine_key(); let pk = Rsa4096PublicKey::new(sk.n(), 0x10001).unwrap(); let msg = b"PSS-SHAKE256 at RSA-4096, both APIs"; let from_trait = RSASSA_PSS_SHAKE256::sign(&sk, msg, None).unwrap(); RSASSA_PSS_SHAKE256::verify(&pk, msg, None, &from_trait).unwrap(); - pss_shake256_verify(&pk, msg, &from_trait).unwrap(); - let from_free = pss_shake256_sign(&sk, msg, &mut DefaultRNG::default()).unwrap(); + RSASSA_PSS_SHAKE256::verify(&pk, msg, None, &from_trait).unwrap(); + let from_free = + RSASSA_PSS_SHAKE256::sign_randomized(&sk, msg, &mut DefaultRNG::default()).unwrap(); RSASSA_PSS_SHAKE256::verify(&pk, msg, None, &from_free).unwrap(); assert!(RSASSA_PSS_SHAKE256::verify(&pk, 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 index 92bfe739..dffb66be 100644 --- a/crypto/rsa/tests/rsa_4096_tests.rs +++ b/crypto/rsa/tests/rsa_4096_tests.rs @@ -3,8 +3,8 @@ //! _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 -//! function (`pkcs1_v1_5_sign_sha384`/`_sha512`, and all six `pss_sign_sha{256,384,512} -//! [_with_salt]`) is exercised by a self-consistency round trip instead, following +//! 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 @@ -21,15 +21,23 @@ use bouncycastle_rng::DefaultRNG; 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, Rsa4096PrivateKey, Rsa4096PublicKey, - SIG_LEN, SK_LEN, pkcs1_v1_5_sign_sha256, pkcs1_v1_5_sign_sha384, pkcs1_v1_5_sign_sha512, - pkcs1_v1_5_verify_sha256, pkcs1_v1_5_verify_sha384, pkcs1_v1_5_verify_sha512, pss_sign_sha256, - pss_sign_sha256_with_salt, pss_sign_sha384, pss_sign_sha384_with_salt, pss_sign_sha512, - pss_sign_sha512_with_salt, pss_verify_sha256, pss_verify_sha384, pss_verify_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_signer_salt`) -- the +/// deterministic PSS mode, for tests against a known salt. Returns `sign_final`'s `Result`. +macro_rules! sign_with_salt { + ($ty:ty, $sk:expr, $msg:expr, $salt:expr) => {{ + let mut signer = <$ty>::sign_init($sk, None).unwrap(); + signer.set_signer_salt($salt); + signer.sign_update($msg); + signer.sign_final() + }}; +} + const TEST_DATA_PATH_RELATIVE: &str = "../../../wycheproof/testvectors_v1"; const TEST_DATA_PATH: &str = "../wycheproof/testvectors_v1"; @@ -134,7 +142,7 @@ fn pkcs1_v1_5_sig_gen_4096_sha256() { 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 = pkcs1_v1_5_sign_sha256(&sk, &msg).unwrap_or_else(|e| { + let sig = RSASSA_PKCS1_v1_5_SHA256::sign(&sk, &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"); @@ -142,7 +150,7 @@ fn pkcs1_v1_5_sig_gen_4096_sha256() { assert_eq!(num_tests, 8); } -/// Mutation testing found that `pkcs1_v1_5_sign_sha384`/`_sha512` were never called by any test at +/// 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. @@ -150,10 +158,10 @@ fn pkcs1_v1_5_sig_gen_4096_sha256() { fn pkcs1_v1_5_sha384_and_sha512_round_trip() { let sk = genuine_key(); let pk = Rsa4096PublicKey::new(sk.n(), 0x10001).unwrap(); - let sig384 = pkcs1_v1_5_sign_sha384(&sk, b"hello").unwrap(); - pkcs1_v1_5_verify_sha384(&pk, b"hello", &sig384).unwrap(); - let sig512 = pkcs1_v1_5_sign_sha512(&sk, b"hello").unwrap(); - pkcs1_v1_5_verify_sha512(&pk, b"hello", &sig512).unwrap(); + let sig384 = RSASSA_PKCS1_v1_5_SHA384::sign(&sk, b"hello", None).unwrap(); + RSASSA_PKCS1_v1_5_SHA384::verify(&pk, b"hello", None, &sig384).unwrap(); + let sig512 = RSASSA_PKCS1_v1_5_SHA512::sign(&sk, b"hello", None).unwrap(); + RSASSA_PKCS1_v1_5_SHA512::verify(&pk, b"hello", None, &sig512).unwrap(); } fn run_pkcs1_v1_5_verify_vectors( @@ -215,7 +223,7 @@ fn run_pkcs1_v1_5_verify_vectors( fn rsa_signature_4096_sha256_wycheproof_vectors() { run_pkcs1_v1_5_verify_vectors( "rsa_signature_4096_sha256_test.json", - |pk, msg, sig| pkcs1_v1_5_verify_sha256(pk, msg, sig).is_ok(), + |pk, msg, sig| RSASSA_PKCS1_v1_5_SHA256::verify(pk, msg, None, sig).is_ok(), "SHA-256", 7, 250, @@ -226,7 +234,7 @@ fn rsa_signature_4096_sha256_wycheproof_vectors() { fn rsa_signature_4096_sha384_wycheproof_vectors() { run_pkcs1_v1_5_verify_vectors( "rsa_signature_4096_sha384_test.json", - |pk, msg, sig| pkcs1_v1_5_verify_sha384(pk, msg, sig).is_ok(), + |pk, msg, sig| RSASSA_PKCS1_v1_5_SHA384::verify(pk, msg, None, sig).is_ok(), "SHA-384", 7, 251, @@ -237,7 +245,7 @@ fn rsa_signature_4096_sha384_wycheproof_vectors() { fn rsa_signature_4096_sha512_wycheproof_vectors() { run_pkcs1_v1_5_verify_vectors( "rsa_signature_4096_sha512_test.json", - |pk, msg, sig| pkcs1_v1_5_verify_sha512(pk, msg, sig).is_ok(), + |pk, msg, sig| RSASSA_PKCS1_v1_5_SHA512::verify(pk, msg, None, sig).is_ok(), "SHA-512", 7, 251, @@ -296,7 +304,7 @@ fn run_pss_verify_vectors( fn rsa_pss_4096_sha256_mgf1_32_wycheproof_vectors() { run_pss_verify_vectors( "rsa_pss_4096_sha256_mgf1_32_test.json", - |pk, msg, sig| pss_verify_sha256(pk, msg, sig).is_ok(), + |pk, msg, sig| RSASSA_PSS_SHA256::verify(pk, msg, None, sig).is_ok(), "SHA-256", 32, 63, @@ -308,7 +316,7 @@ fn rsa_pss_4096_sha256_mgf1_32_wycheproof_vectors() { fn rsa_pss_4096_sha384_mgf1_48_wycheproof_vectors() { run_pss_verify_vectors( "rsa_pss_4096_sha384_mgf1_48_test.json", - |pk, msg, sig| pss_verify_sha384(pk, msg, sig).is_ok(), + |pk, msg, sig| RSASSA_PSS_SHA384::verify(pk, msg, None, sig).is_ok(), "SHA-384", 48, 95, @@ -320,7 +328,7 @@ fn rsa_pss_4096_sha384_mgf1_48_wycheproof_vectors() { fn rsa_pss_4096_sha512_mgf1_64_wycheproof_vectors() { run_pss_verify_vectors( "rsa_pss_4096_sha512_mgf1_64_test.json", - |pk, msg, sig| pss_verify_sha512(pk, msg, sig).is_ok(), + |pk, msg, sig| RSASSA_PSS_SHA512::verify(pk, msg, None, sig).is_ok(), "SHA-512", 64, 132, @@ -328,7 +336,7 @@ fn rsa_pss_4096_sha512_mgf1_64_wycheproof_vectors() { ); } -/// Mutation testing found that none of the six `pss_sign_sha{256,384,512}[_with_salt]` functions +/// 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- @@ -339,9 +347,10 @@ fn pss_sha256_fixed_salt_round_trips() { let sk = genuine_key(); let pk = Rsa4096PublicKey::new(sk.n(), 0x10001).unwrap(); let salt = [0x22u8; 32]; - let sig = pss_sign_sha256_with_salt(&sk, b"hello", &salt).expect("signing must succeed"); - pss_verify_sha256(&pk, b"hello", &sig).expect("must verify"); - assert!(pss_verify_sha256(&pk, b"goodbye", &sig).is_err()); + let sig = + sign_with_salt!(RSASSA_PSS_SHA256, &sk, b"hello", salt).expect("signing must succeed"); + RSASSA_PSS_SHA256::verify(&pk, b"hello", None, &sig).expect("must verify"); + assert!(RSASSA_PSS_SHA256::verify(&pk, b"goodbye", None, &sig).is_err()); } #[test] @@ -349,11 +358,13 @@ fn pss_sha256_rng_produces_fresh_salts_that_both_verify() { let sk = genuine_key(); let pk = Rsa4096PublicKey::new(sk.n(), 0x10001).unwrap(); let mut rng = DefaultRNG::default(); - let sig_a = pss_sign_sha256(&sk, b"hello", &mut rng).expect("signing must succeed"); - let sig_b = pss_sign_sha256(&sk, b"hello", &mut rng).expect("signing must succeed"); + let sig_a = + RSASSA_PSS_SHA256::sign_randomized(&sk, b"hello", &mut rng).expect("signing must succeed"); + let sig_b = + RSASSA_PSS_SHA256::sign_randomized(&sk, b"hello", &mut rng).expect("signing must succeed"); assert_ne!(sig_a, sig_b, "PSS is randomized: two signatures of the same message must differ"); - pss_verify_sha256(&pk, b"hello", &sig_a).expect("sig_a must verify"); - pss_verify_sha256(&pk, b"hello", &sig_b).expect("sig_b must verify"); + RSASSA_PSS_SHA256::verify(&pk, b"hello", None, &sig_a).expect("sig_a must verify"); + RSASSA_PSS_SHA256::verify(&pk, b"hello", None, &sig_b).expect("sig_b must verify"); } #[test] @@ -361,9 +372,10 @@ fn pss_sha384_fixed_salt_round_trips() { let sk = genuine_key(); let pk = Rsa4096PublicKey::new(sk.n(), 0x10001).unwrap(); let salt = [0x11u8; 48]; - let sig = pss_sign_sha384_with_salt(&sk, b"hello", &salt).expect("signing must succeed"); - pss_verify_sha384(&pk, b"hello", &sig).expect("must verify"); - assert!(pss_verify_sha384(&pk, b"goodbye", &sig).is_err()); + let sig = + sign_with_salt!(RSASSA_PSS_SHA384, &sk, b"hello", salt).expect("signing must succeed"); + RSASSA_PSS_SHA384::verify(&pk, b"hello", None, &sig).expect("must verify"); + assert!(RSASSA_PSS_SHA384::verify(&pk, b"goodbye", None, &sig).is_err()); } #[test] @@ -371,11 +383,13 @@ fn pss_sha384_rng_produces_fresh_salts_that_both_verify() { let sk = genuine_key(); let pk = Rsa4096PublicKey::new(sk.n(), 0x10001).unwrap(); let mut rng = DefaultRNG::default(); - let sig_a = pss_sign_sha384(&sk, b"hello", &mut rng).expect("signing must succeed"); - let sig_b = pss_sign_sha384(&sk, b"hello", &mut rng).expect("signing must succeed"); + let sig_a = + RSASSA_PSS_SHA384::sign_randomized(&sk, b"hello", &mut rng).expect("signing must succeed"); + let sig_b = + RSASSA_PSS_SHA384::sign_randomized(&sk, b"hello", &mut rng).expect("signing must succeed"); assert_ne!(sig_a, sig_b, "PSS is randomized: two signatures of the same message must differ"); - pss_verify_sha384(&pk, b"hello", &sig_a).expect("sig_a must verify"); - pss_verify_sha384(&pk, b"hello", &sig_b).expect("sig_b must verify"); + RSASSA_PSS_SHA384::verify(&pk, b"hello", None, &sig_a).expect("sig_a must verify"); + RSASSA_PSS_SHA384::verify(&pk, b"hello", None, &sig_b).expect("sig_b must verify"); } #[test] @@ -383,9 +397,10 @@ fn pss_sha512_fixed_salt_round_trips() { let sk = genuine_key(); let pk = Rsa4096PublicKey::new(sk.n(), 0x10001).unwrap(); let salt = [0x33u8; 64]; - let sig = pss_sign_sha512_with_salt(&sk, b"hello", &salt).expect("signing must succeed"); - pss_verify_sha512(&pk, b"hello", &sig).expect("must verify"); - assert!(pss_verify_sha512(&pk, b"goodbye", &sig).is_err()); + let sig = + sign_with_salt!(RSASSA_PSS_SHA512, &sk, b"hello", salt).expect("signing must succeed"); + RSASSA_PSS_SHA512::verify(&pk, b"hello", None, &sig).expect("must verify"); + assert!(RSASSA_PSS_SHA512::verify(&pk, b"goodbye", None, &sig).is_err()); } #[test] @@ -393,11 +408,13 @@ fn pss_sha512_rng_produces_fresh_salts_that_both_verify() { let sk = genuine_key(); let pk = Rsa4096PublicKey::new(sk.n(), 0x10001).unwrap(); let mut rng = DefaultRNG::default(); - let sig_a = pss_sign_sha512(&sk, b"hello", &mut rng).expect("signing must succeed"); - let sig_b = pss_sign_sha512(&sk, b"hello", &mut rng).expect("signing must succeed"); + let sig_a = + RSASSA_PSS_SHA512::sign_randomized(&sk, b"hello", &mut rng).expect("signing must succeed"); + let sig_b = + RSASSA_PSS_SHA512::sign_randomized(&sk, b"hello", &mut rng).expect("signing must succeed"); assert_ne!(sig_a, sig_b, "PSS is randomized: two signatures of the same message must differ"); - pss_verify_sha512(&pk, b"hello", &sig_a).expect("sig_a must verify"); - pss_verify_sha512(&pk, b"hello", &sig_b).expect("sig_b must verify"); + RSASSA_PSS_SHA512::verify(&pk, b"hello", None, &sig_a).expect("sig_a must verify"); + RSASSA_PSS_SHA512::verify(&pk, b"hello", None, &sig_b).expect("sig_b must verify"); } // ---- bouncycastle_core trait conformance ------------------------------------------------------ @@ -441,10 +458,9 @@ fn key_trait_boundary_conditions() { .test_keys::(fixed_keypair); } -/// Sign then verify through the traits, verify the free functions' signature over the same -/// message through the trait, and reject a different message -- what a wrong width constant in -/// this size's aliases would break. -fn trait_round_trip(pk: &Rsa4096PublicKey, sk: &Rsa4096PrivateKey, free_sig: &[u8; SIG_LEN]) +/// Sign one-shot and streamed, verify both, and reject a different message -- what a wrong width +/// constant in this size's aliases would break. +fn trait_round_trip(pk: &Rsa4096PublicKey, sk: &Rsa4096PrivateKey) where S: Signer + SignatureVerifier, @@ -452,25 +468,18 @@ where let msg = b"RSA-4096 trait round trip"; let sig = S::sign(sk, msg, None).unwrap(); S::verify(pk, msg, None, &sig).unwrap(); - S::verify(pk, msg, None, free_sig).unwrap(); + let mut signer = S::sign_init(sk, None).unwrap(); + signer.sign_update(&msg[..8]); + signer.sign_update(&msg[8..]); + S::verify(pk, msg, None, &signer.sign_final().unwrap()).unwrap(); assert!(S::verify(pk, b"a different message", None, &sig).is_err()); } #[test] fn remaining_pairings_trait_round_trips() { let (pk, sk) = fixed_keypair().unwrap(); - let msg = b"RSA-4096 trait round trip"; - let mut rng = DefaultRNG::default(); - trait_round_trip::( - &pk, - &sk, - &pkcs1_v1_5_sign_sha384(&sk, msg).unwrap(), - ); - trait_round_trip::( - &pk, - &sk, - &pkcs1_v1_5_sign_sha512(&sk, msg).unwrap(), - ); - trait_round_trip::(&pk, &sk, &pss_sign_sha384(&sk, msg, &mut rng).unwrap()); - trait_round_trip::(&pk, &sk, &pss_sign_sha512(&sk, msg, &mut rng).unwrap()); + trait_round_trip::(&pk, &sk); + trait_round_trip::(&pk, &sk); + trait_round_trip::(&pk, &sk); + trait_round_trip::(&pk, &sk); } diff --git a/crypto/rsa/tests/rsa_8192_tests.rs b/crypto/rsa/tests/rsa_8192_tests.rs index e60d637f..c39e744d 100644 --- a/crypto/rsa/tests/rsa_8192_tests.rs +++ b/crypto/rsa/tests/rsa_8192_tests.rs @@ -7,10 +7,10 @@ //! (`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 `pkcs1_v1_5_sign_sha{256,384,512}`; PSS is randomized, so its +//! 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_verify_sha{256,384,512}`, a genuine independent-implementation cross-check even though +//! 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: @@ -30,16 +30,24 @@ use bouncycastle_rng::DefaultRNG; 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, Rsa8192PrivateKey, Rsa8192PublicKey, - SIG_LEN, SK_LEN, pkcs1_v1_5_sign_sha256, pkcs1_v1_5_sign_sha384, pkcs1_v1_5_sign_sha512, - pkcs1_v1_5_verify_sha256, pkcs1_v1_5_verify_sha384, pkcs1_v1_5_verify_sha512, pss_sign_sha256, - pss_sign_sha256_with_salt, pss_sign_sha384, pss_sign_sha384_with_salt, pss_sign_sha512, - pss_sign_sha512_with_salt, pss_verify_sha256, pss_verify_sha384, pss_verify_sha512, + SIG_LEN, SK_LEN, }; 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_signer_salt`) -- the +/// deterministic PSS mode, for tests against a known salt. Returns `sign_final`'s `Result`. +macro_rules! sign_with_salt { + ($ty:ty, $sk:expr, $msg:expr, $salt:expr) => {{ + let mut signer = <$ty>::sign_init($sk, None).unwrap(); + signer.set_signer_salt($salt); + signer.sign_update($msg); + signer.sign_final() + }}; +} + const TEST_DATA_PATH_RELATIVE: &str = "../../../wycheproof/testvectors_v1"; const TEST_DATA_PATH: &str = "../wycheproof/testvectors_v1"; @@ -175,13 +183,13 @@ const BC_JAVA_PSS_SHA256_SIG: &str = "71c1b3dd982fd6e1e8be1e20c8a4d42fbe6a8b204a #[test] fn pkcs1_v1_5_matches_bc_java_byte_for_byte() { let sk = genuine_key(); - let sig256 = pkcs1_v1_5_sign_sha256(&sk, b"hello").unwrap(); + let sig256 = RSASSA_PKCS1_v1_5_SHA256::sign(&sk, b"hello", None).unwrap(); assert_eq!(sig256.to_vec(), hex_decode(BC_JAVA_SHA256_SIG).unwrap()); - let sig384 = pkcs1_v1_5_sign_sha384(&sk, b"hello").unwrap(); + let sig384 = RSASSA_PKCS1_v1_5_SHA384::sign(&sk, b"hello", None).unwrap(); assert_eq!(sig384.to_vec(), hex_decode(BC_JAVA_SHA384_SIG).unwrap()); - let sig512 = pkcs1_v1_5_sign_sha512(&sk, b"hello").unwrap(); + let sig512 = RSASSA_PKCS1_v1_5_SHA512::sign(&sk, b"hello", None).unwrap(); assert_eq!(sig512.to_vec(), hex_decode(BC_JAVA_SHA512_SIG).unwrap()); } @@ -192,9 +200,12 @@ fn pkcs1_v1_5_verifies_bc_java_signatures() { 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(); - pkcs1_v1_5_verify_sha256(&pk, b"hello", &sig256).expect("BC Java's SHA-256 sig must verify"); - pkcs1_v1_5_verify_sha384(&pk, b"hello", &sig384).expect("BC Java's SHA-384 sig must verify"); - pkcs1_v1_5_verify_sha512(&pk, b"hello", &sig512).expect("BC Java's SHA-512 sig must verify"); + RSASSA_PKCS1_v1_5_SHA256::verify(&pk, b"hello", None, &sig256) + .expect("BC Java's SHA-256 sig must verify"); + RSASSA_PKCS1_v1_5_SHA384::verify(&pk, b"hello", None, &sig384) + .expect("BC Java's SHA-384 sig must verify"); + RSASSA_PKCS1_v1_5_SHA512::verify(&pk, b"hello", None, &sig512) + .expect("BC Java's SHA-512 sig must verify"); } #[test] @@ -202,12 +213,12 @@ fn pss_verifies_bc_java_sha256_signature() { let sk = genuine_key(); let pk = Rsa8192PublicKey::new(sk.n(), 0x10001).unwrap(); let sig: [u8; 1024] = hex_decode(BC_JAVA_PSS_SHA256_SIG).unwrap().try_into().unwrap(); - pss_verify_sha256(&pk, b"hello", &sig) + RSASSA_PSS_SHA256::verify(&pk, b"hello", None, &sig) .expect("BC Java's PSS/SHA-256 signature (default salt length = hLen) must verify"); } -/// Mutation testing found that `pss_sign_sha256_with_salt`, `pss_sign_sha384`/`pss_sign_sha512` -/// (the RNG variants), and `pss_verify_sha384`/`pss_verify_sha512`'s rejection paths were never +/// 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 @@ -217,9 +228,10 @@ fn pss_sha256_fixed_salt_round_trips() { let sk = genuine_key(); let pk = Rsa8192PublicKey::new(sk.n(), 0x10001).unwrap(); let salt = [0x33u8; 32]; - let sig = pss_sign_sha256_with_salt(&sk, b"hello", &salt).expect("signing must succeed"); - pss_verify_sha256(&pk, b"hello", &sig).expect("must verify"); - assert!(pss_verify_sha256(&pk, b"goodbye", &sig).is_err()); + let sig = + sign_with_salt!(RSASSA_PSS_SHA256, &sk, b"hello", salt).expect("signing must succeed"); + RSASSA_PSS_SHA256::verify(&pk, b"hello", None, &sig).expect("must verify"); + assert!(RSASSA_PSS_SHA256::verify(&pk, b"goodbye", None, &sig).is_err()); } #[test] @@ -227,11 +239,13 @@ fn pss_sha256_rng_produces_fresh_salts_that_both_verify() { let sk = genuine_key(); let pk = Rsa8192PublicKey::new(sk.n(), 0x10001).unwrap(); let mut rng = DefaultRNG::default(); - let sig_a = pss_sign_sha256(&sk, b"hello", &mut rng).expect("signing must succeed"); - let sig_b = pss_sign_sha256(&sk, b"hello", &mut rng).expect("signing must succeed"); + let sig_a = + RSASSA_PSS_SHA256::sign_randomized(&sk, b"hello", &mut rng).expect("signing must succeed"); + let sig_b = + RSASSA_PSS_SHA256::sign_randomized(&sk, b"hello", &mut rng).expect("signing must succeed"); assert_ne!(sig_a, sig_b, "PSS is randomized: two signatures of the same message must differ"); - pss_verify_sha256(&pk, b"hello", &sig_a).expect("sig_a must verify"); - pss_verify_sha256(&pk, b"hello", &sig_b).expect("sig_b must verify"); + RSASSA_PSS_SHA256::verify(&pk, b"hello", None, &sig_a).expect("sig_a must verify"); + RSASSA_PSS_SHA256::verify(&pk, b"hello", None, &sig_b).expect("sig_b must verify"); } #[test] @@ -239,9 +253,10 @@ fn pss_sha384_fixed_salt_round_trips() { let sk = genuine_key(); let pk = Rsa8192PublicKey::new(sk.n(), 0x10001).unwrap(); let salt = [0x11u8; 48]; - let sig = pss_sign_sha384_with_salt(&sk, b"hello", &salt).expect("signing must succeed"); - pss_verify_sha384(&pk, b"hello", &sig).expect("must verify"); - assert!(pss_verify_sha384(&pk, b"goodbye", &sig).is_err()); + let sig = + sign_with_salt!(RSASSA_PSS_SHA384, &sk, b"hello", salt).expect("signing must succeed"); + RSASSA_PSS_SHA384::verify(&pk, b"hello", None, &sig).expect("must verify"); + assert!(RSASSA_PSS_SHA384::verify(&pk, b"goodbye", None, &sig).is_err()); } #[test] @@ -249,11 +264,13 @@ fn pss_sha384_rng_produces_fresh_salts_that_both_verify() { let sk = genuine_key(); let pk = Rsa8192PublicKey::new(sk.n(), 0x10001).unwrap(); let mut rng = DefaultRNG::default(); - let sig_a = pss_sign_sha384(&sk, b"hello", &mut rng).expect("signing must succeed"); - let sig_b = pss_sign_sha384(&sk, b"hello", &mut rng).expect("signing must succeed"); + let sig_a = + RSASSA_PSS_SHA384::sign_randomized(&sk, b"hello", &mut rng).expect("signing must succeed"); + let sig_b = + RSASSA_PSS_SHA384::sign_randomized(&sk, b"hello", &mut rng).expect("signing must succeed"); assert_ne!(sig_a, sig_b, "PSS is randomized: two signatures of the same message must differ"); - pss_verify_sha384(&pk, b"hello", &sig_a).expect("sig_a must verify"); - pss_verify_sha384(&pk, b"hello", &sig_b).expect("sig_b must verify"); + RSASSA_PSS_SHA384::verify(&pk, b"hello", None, &sig_a).expect("sig_a must verify"); + RSASSA_PSS_SHA384::verify(&pk, b"hello", None, &sig_b).expect("sig_b must verify"); } #[test] @@ -261,9 +278,10 @@ fn pss_sha512_fixed_salt_round_trips() { let sk = genuine_key(); let pk = Rsa8192PublicKey::new(sk.n(), 0x10001).unwrap(); let salt = [0x22u8; 64]; - let sig = pss_sign_sha512_with_salt(&sk, b"hello", &salt).expect("signing must succeed"); - pss_verify_sha512(&pk, b"hello", &sig).expect("must verify"); - assert!(pss_verify_sha512(&pk, b"goodbye", &sig).is_err()); + let sig = + sign_with_salt!(RSASSA_PSS_SHA512, &sk, b"hello", salt).expect("signing must succeed"); + RSASSA_PSS_SHA512::verify(&pk, b"hello", None, &sig).expect("must verify"); + assert!(RSASSA_PSS_SHA512::verify(&pk, b"goodbye", None, &sig).is_err()); } #[test] @@ -271,11 +289,13 @@ fn pss_sha512_rng_produces_fresh_salts_that_both_verify() { let sk = genuine_key(); let pk = Rsa8192PublicKey::new(sk.n(), 0x10001).unwrap(); let mut rng = DefaultRNG::default(); - let sig_a = pss_sign_sha512(&sk, b"hello", &mut rng).expect("signing must succeed"); - let sig_b = pss_sign_sha512(&sk, b"hello", &mut rng).expect("signing must succeed"); + let sig_a = + RSASSA_PSS_SHA512::sign_randomized(&sk, b"hello", &mut rng).expect("signing must succeed"); + let sig_b = + RSASSA_PSS_SHA512::sign_randomized(&sk, b"hello", &mut rng).expect("signing must succeed"); assert_ne!(sig_a, sig_b, "PSS is randomized: two signatures of the same message must differ"); - pss_verify_sha512(&pk, b"hello", &sig_a).expect("sig_a must verify"); - pss_verify_sha512(&pk, b"hello", &sig_b).expect("sig_b must verify"); + RSASSA_PSS_SHA512::verify(&pk, b"hello", None, &sig_a).expect("sig_a must verify"); + RSASSA_PSS_SHA512::verify(&pk, b"hello", None, &sig_b).expect("sig_b must verify"); } /// Every distinct `(result, flags)` combination in `filename`'s (single) test group, in file @@ -341,7 +361,7 @@ fn run_sampled_pkcs1_v1_5_verify_vectors( fn rsa_signature_8192_sha256_wycheproof_vectors_sampled() { run_sampled_pkcs1_v1_5_verify_vectors( "rsa_signature_8192_sha256_test.json", - |pk, msg, sig| pkcs1_v1_5_verify_sha256(pk, msg, sig).is_ok(), + |pk, msg, sig| RSASSA_PKCS1_v1_5_SHA256::verify(pk, msg, None, sig).is_ok(), "SHA-256", ); } @@ -350,7 +370,7 @@ fn rsa_signature_8192_sha256_wycheproof_vectors_sampled() { fn rsa_signature_8192_sha384_wycheproof_vectors_sampled() { run_sampled_pkcs1_v1_5_verify_vectors( "rsa_signature_8192_sha384_test.json", - |pk, msg, sig| pkcs1_v1_5_verify_sha384(pk, msg, sig).is_ok(), + |pk, msg, sig| RSASSA_PKCS1_v1_5_SHA384::verify(pk, msg, None, sig).is_ok(), "SHA-384", ); } @@ -359,7 +379,7 @@ fn rsa_signature_8192_sha384_wycheproof_vectors_sampled() { fn rsa_signature_8192_sha512_wycheproof_vectors_sampled() { run_sampled_pkcs1_v1_5_verify_vectors( "rsa_signature_8192_sha512_test.json", - |pk, msg, sig| pkcs1_v1_5_verify_sha512(pk, msg, sig).is_ok(), + |pk, msg, sig| RSASSA_PKCS1_v1_5_SHA512::verify(pk, msg, None, sig).is_ok(), "SHA-512", ); } @@ -394,7 +414,7 @@ fn key_trait_boundary_conditions() { .test_keys::(fixed_keypair); } -fn trait_round_trip(pk: &Rsa8192PublicKey, sk: &Rsa8192PrivateKey, free_sig: &[u8; SIG_LEN]) +fn trait_round_trip(pk: &Rsa8192PublicKey, sk: &Rsa8192PrivateKey) where S: Signer + SignatureVerifier, @@ -402,32 +422,25 @@ where let msg = b"RSA-8192 trait round trip"; let sig = S::sign(sk, msg, None).unwrap(); S::verify(pk, msg, None, &sig).unwrap(); - S::verify(pk, msg, None, free_sig).unwrap(); + let mut signer = S::sign_init(sk, None).unwrap(); + signer.sign_update(&msg[..8]); + signer.sign_update(&msg[8..]); + S::verify(pk, msg, None, &signer.sign_final().unwrap()).unwrap(); assert!(S::verify(pk, b"a different message", None, &sig).is_err()); } #[test] fn remaining_pairings_trait_round_trips() { let (pk, sk) = fixed_keypair().unwrap(); - let msg = b"RSA-8192 trait round trip"; - let mut rng = DefaultRNG::default(); - trait_round_trip::( - &pk, - &sk, - &pkcs1_v1_5_sign_sha384(&sk, msg).unwrap(), - ); - trait_round_trip::( - &pk, - &sk, - &pkcs1_v1_5_sign_sha512(&sk, msg).unwrap(), - ); - trait_round_trip::(&pk, &sk, &pss_sign_sha256(&sk, msg, &mut rng).unwrap()); - trait_round_trip::(&pk, &sk, &pss_sign_sha384(&sk, msg, &mut rng).unwrap()); - trait_round_trip::(&pk, &sk, &pss_sign_sha512(&sk, msg, &mut rng).unwrap()); + trait_round_trip::(&pk, &sk); + trait_round_trip::(&pk, &sk); + trait_round_trip::(&pk, &sk); + trait_round_trip::(&pk, &sk); + trait_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 free-function +/// accepts BC Java's PSS signature -- the same cross-implementation check as the /// tests above, through `Signer`/`SignatureVerifier`. #[test] fn trait_matches_bc_java() { diff --git a/mem_usage_benches/src/bench_rsa_mem_usage.rs b/mem_usage_benches/src/bench_rsa_mem_usage.rs index e49bb9f0..691edd6c 100644 --- a/mem_usage_benches/src/bench_rsa_mem_usage.rs +++ b/mem_usage_benches/src/bench_rsa_mem_usage.rs @@ -30,6 +30,7 @@ #![allow(dead_code)] #![allow(unused_imports)] +use bouncycastle::core::traits::{SignatureVerifier, Signer}; use bouncycastle::rsa::{rsa_1024, rsa_1536, rsa_2048, rsa_3072, rsa_4096, rsa_8192}; const MSG: &[u8] = b"peak stack usage of RSA sign/verify, held constant across every modulus size"; @@ -105,7 +106,7 @@ fn bench_1024_verify() { ); let msg = bouncycastle::hex::decode("0000000000000000000000000000000000000000").unwrap(); - if rsa_1024::pkcs1_v1_5_verify_sha256(&pk, &msg, &sig).is_ok() { + if rsa_1024::RSASSA_PKCS1_v1_5_SHA256::verify(&pk, &msg, None, &sig).is_ok() { eprintln!("Verification succeeded!"); } else { panic!("Verification failed! -- figure that out"); @@ -149,7 +150,7 @@ fn genuine_2048_key() -> rsa_2048::Rsa2048PrivateKey { fn bench_2048_sign() { eprintln!("RSA-2048/Sign"); let sk = genuine_2048_key(); - let sig = rsa_2048::pkcs1_v1_5_sign_sha256(&sk, MSG).unwrap(); + let sig = rsa_2048::RSASSA_PKCS1_v1_5_SHA256::sign(&sk, MSG, None).unwrap(); println!("{:x?}", sig); } @@ -157,9 +158,9 @@ fn bench_2048_verify() { eprintln!("RSA-2048/Verify"); let sk = genuine_2048_key(); let pk = rsa_2048::Rsa2048PublicKey::new(sk.n(), 0x10001).unwrap(); - let sig = rsa_2048::pkcs1_v1_5_sign_sha256(&sk, MSG).unwrap(); + let sig = rsa_2048::RSASSA_PKCS1_v1_5_SHA256::sign(&sk, MSG, None).unwrap(); - if rsa_2048::pkcs1_v1_5_verify_sha256(&pk, MSG, &sig).is_ok() { + if rsa_2048::RSASSA_PKCS1_v1_5_SHA256::verify(&pk, MSG, None, &sig).is_ok() { eprintln!("Verification succeeded!"); } else { panic!("Verification failed! -- figure that out"); @@ -263,7 +264,7 @@ fn genuine_8192_key() -> rsa_8192::Rsa8192PrivateKey { fn bench_8192_sign() { eprintln!("RSA-8192/Sign"); let sk = genuine_8192_key(); - let sig = rsa_8192::pkcs1_v1_5_sign_sha256(&sk, MSG).unwrap(); + let sig = rsa_8192::RSASSA_PKCS1_v1_5_SHA256::sign(&sk, MSG, None).unwrap(); println!("{:x?}", sig); } @@ -271,9 +272,9 @@ fn bench_8192_verify() { eprintln!("RSA-8192/Verify"); let sk = genuine_8192_key(); let pk = rsa_8192::Rsa8192PublicKey::new(sk.n(), 0x10001).unwrap(); - let sig = rsa_8192::pkcs1_v1_5_sign_sha256(&sk, MSG).unwrap(); + let sig = rsa_8192::RSASSA_PKCS1_v1_5_SHA256::sign(&sk, MSG, None).unwrap(); - if rsa_8192::pkcs1_v1_5_verify_sha256(&pk, MSG, &sig).is_ok() { + if rsa_8192::RSASSA_PKCS1_v1_5_SHA256::verify(&pk, MSG, None, &sig).is_ok() { eprintln!("Verification succeeded!"); } else { panic!("Verification failed! -- figure that out"); From ccaf2d7483d0573f45f7b7505da727e12c782296 Mon Sep 17 00:00:00 2001 From: David Hook Date: Mon, 21 Sep 2026 10:34:12 +1000 Subject: [PATCH 17/55] rsa: rename the key type aliases RsaPrivateKey/RsaPublicKey to RSAPrivateKey/RSAPublicKey The workspace's other signature crates spell the algorithm in their key type names the way the specification does -- ECDSAP256PrivateKey, MLDSAPublicKey, SM2PrivateKey -- and QUALITY_AND_STYLE asks for specification capitalisation on identifiers a specification names; this crate's Rsa2048PrivateKey and siblings were the one camel-cased outlier. Pure rename across the six size modules, their tests and benches, the crate docs, the CLI and the memory-usage harness; the generic RsaPrivateKey/RsaPublicKey they alias, which no specification names, keep their spelling. Co-Authored-By: Claude Fable 5.1 --- cli/src/rsa_cmd.rs | 40 ++++++------- cli/tests/rsa_cli_tests.rs | 14 ++--- crypto/rsa/benches/rsa_1024_benches.rs | 6 +- crypto/rsa/benches/rsa_1536_benches.rs | 8 +-- crypto/rsa/benches/rsa_2048_benches.rs | 12 ++-- crypto/rsa/benches/rsa_3072_benches.rs | 12 ++-- crypto/rsa/benches/rsa_4096_benches.rs | 12 ++-- crypto/rsa/benches/rsa_8192_benches.rs | 10 ++-- crypto/rsa/src/keys.rs | 6 +- crypto/rsa/src/lib.rs | 14 ++--- crypto/rsa/src/rsa_1024.rs | 8 +-- crypto/rsa/src/rsa_1536.rs | 8 +-- crypto/rsa/src/rsa_2048.rs | 12 ++-- crypto/rsa/src/rsa_3072.rs | 12 ++-- crypto/rsa/src/rsa_4096.rs | 12 ++-- crypto/rsa/src/rsa_8192.rs | 12 ++-- crypto/rsa/tests/keys_tests.rs | 2 +- crypto/rsa/tests/rsa_1024_tests.rs | 18 +++--- crypto/rsa/tests/rsa_1536_tests.rs | 20 +++---- ...rsa_2048_pkcs1_v1_5_sha384_sha512_tests.rs | 28 ++++----- crypto/rsa/tests/rsa_2048_pkcs1_v1_5_tests.rs | 18 +++--- .../tests/rsa_2048_pss_sha384_sha512_tests.rs | 28 ++++----- .../rsa/tests/rsa_2048_pss_shake128_tests.rs | 20 +++---- crypto/rsa/tests/rsa_2048_pss_tests.rs | 20 +++---- .../rsa/tests/rsa_3072_pss_shake128_tests.rs | 20 +++---- crypto/rsa/tests/rsa_3072_tests.rs | 60 +++++++++---------- .../rsa/tests/rsa_4096_pss_shake256_tests.rs | 14 ++--- crypto/rsa/tests/rsa_4096_tests.rs | 52 ++++++++-------- crypto/rsa/tests/rsa_8192_tests.rs | 46 +++++++------- mem_usage_benches/src/bench_rsa_mem_usage.rs | 34 +++++------ 30 files changed, 289 insertions(+), 289 deletions(-) diff --git a/cli/src/rsa_cmd.rs b/cli/src/rsa_cmd.rs index 53e0cfc3..32ca10c8 100644 --- a/cli/src/rsa_cmd.rs +++ b/cli/src/rsa_cmd.rs @@ -207,18 +207,18 @@ pub(crate) fn rsa_1024_cmd( sigfile: &Option, ) { use rsa_1024::{ - PK_LEN, RSASSA_PKCS1_v1_5_SHA256, RSASSA_PKCS1_v1_5_SHA384, Rsa1024PublicKey, SIG_LEN, + PK_LEN, RSA1024PublicKey, RSASSA_PKCS1_v1_5_SHA256, RSASSA_PKCS1_v1_5_SHA384, SIG_LEN, }; match (scheme, hash) { (RSAScheme::Pkcs1v15, RSAHash::Sha256) => { - do_verify::( + do_verify::( pkfile, sigfile, "RSA-1024/PKCS#1v1.5/SHA-256", ) } (RSAScheme::Pkcs1v15, RSAHash::Sha384) => { - do_verify::( + do_verify::( pkfile, sigfile, "RSA-1024/PKCS#1v1.5/SHA-384", @@ -236,26 +236,26 @@ pub(crate) fn rsa_1536_cmd( sigfile: &Option, ) { use rsa_1536::{ - PK_LEN, RSASSA_PKCS1_v1_5_SHA256, RSASSA_PKCS1_v1_5_SHA384, RSASSA_PKCS1_v1_5_SHA512, - Rsa1536PublicKey, SIG_LEN, + PK_LEN, RSA1536PublicKey, 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::( + do_verify::( pkfile, sigfile, "RSA-1536/PKCS#1v1.5/SHA-256", ) } (RSAScheme::Pkcs1v15, RSAHash::Sha384) => { - do_verify::( + do_verify::( pkfile, sigfile, "RSA-1536/PKCS#1v1.5/SHA-384", ) } (RSAScheme::Pkcs1v15, RSAHash::Sha512) => { - do_verify::( + do_verify::( pkfile, sigfile, "RSA-1536/PKCS#1v1.5/SHA-512", @@ -278,9 +278,9 @@ pub(crate) fn rsa_2048_cmd( 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, - Rsa2048PrivateKey as SK, Rsa2048PublicKey as PK, SIG_LEN, SK_LEN, + PK_LEN, RSA2048PrivateKey as SK, RSA2048PublicKey as PK, 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, }; let args = (skfile, pkfile, sigfile, output_hex); let run = @@ -333,9 +333,9 @@ pub(crate) fn rsa_3072_cmd( 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, - Rsa3072PrivateKey as SK, Rsa3072PublicKey as PK, SIG_LEN, SK_LEN, + PK_LEN, RSA3072PrivateKey as SK, RSA3072PublicKey as PK, 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, }; let args = (skfile, pkfile, sigfile, output_hex); let run = @@ -389,9 +389,9 @@ pub(crate) fn rsa_4096_cmd( 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, - Rsa4096PrivateKey as SK, Rsa4096PublicKey as PK, SIG_LEN, SK_LEN, + PK_LEN, RSA4096PrivateKey as SK, RSA4096PublicKey as PK, 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, }; let args = (skfile, pkfile, sigfile, output_hex); let run = @@ -446,9 +446,9 @@ pub(crate) fn rsa_8192_cmd( 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, Rsa8192PrivateKey as SK, - Rsa8192PublicKey as PK, SIG_LEN, SK_LEN, + PK_LEN, RSA8192PrivateKey as SK, RSA8192PublicKey as PK, 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, }; let args = (skfile, pkfile, sigfile, output_hex); let run = diff --git a/cli/tests/rsa_cli_tests.rs b/cli/tests/rsa_cli_tests.rs index a7b7bad1..62cd8a8c 100644 --- a/cli/tests/rsa_cli_tests.rs +++ b/cli/tests/rsa_cli_tests.rs @@ -12,8 +12,8 @@ use bouncycastle::core::traits::{ SignaturePrivateKey, SignaturePublicKey, SignatureVerifier, Signer, }; use bouncycastle::rsa::rsa_2048::{ - PK_LEN, RSASSA_PKCS1_v1_5_SHA256, RSASSA_PSS_SHA256, RSASSA_PSS_SHAKE128, Rsa2048PrivateKey, - Rsa2048PublicKey, SIG_LEN, + PK_LEN, RSA2048PrivateKey, RSA2048PublicKey, RSASSA_PKCS1_v1_5_SHA256, RSASSA_PSS_SHA256, + RSASSA_PSS_SHAKE128, SIG_LEN, }; use std::io::{ErrorKind, Write}; use std::path::PathBuf; @@ -158,12 +158,12 @@ fn temp_file(tag: &str, contents: &[u8]) -> String { path.to_string_lossy().into_owned() } -fn sk_2048() -> Rsa2048PrivateKey { - Rsa2048PrivateKey::from_bytes(&unhex(SK_2048_HEX)).expect("the documented key decodes") +fn sk_2048() -> RSA2048PrivateKey { + RSA2048PrivateKey::from_bytes(&unhex(SK_2048_HEX)).expect("the documented key decodes") } -fn pk_2048() -> Rsa2048PublicKey { - Rsa2048PublicKey::from_bytes(&unhex(PK_2048_HEX)).expect("the documented key decodes") +fn pk_2048() -> RSA2048PublicKey { + RSA2048PublicKey::from_bytes(&unhex(PK_2048_HEX)).expect("the documented key decodes") } /// The CLI accepts key and signature files as hex (as written here) or binary. @@ -229,7 +229,7 @@ fn rsa_2048_pkcs1v15_signature_matches_the_library_and_verifies() { /// One PSS pairing: two CLI signatures of one message differ (a fresh salt each), and both /// verify -- through the library's `SignatureVerifier` `V` and through the CLI. -fn pss_case>(hash: &str, msg: &[u8]) { +fn pss_case>(hash: &str, msg: &[u8]) { let pk = pk_2048(); let sig_a = rsa_2048_sign("pss", hash, msg); let sig_b = rsa_2048_sign("pss", hash, msg); diff --git a/crypto/rsa/benches/rsa_1024_benches.rs b/crypto/rsa/benches/rsa_1024_benches.rs index bf844d54..9bcd67e7 100644 --- a/crypto/rsa/benches/rsa_1024_benches.rs +++ b/crypto/rsa/benches/rsa_1024_benches.rs @@ -9,7 +9,7 @@ use std::hint::black_box; use bouncycastle_hex::decode as hex_decode; use bouncycastle_rsa::rsa_1024::{ - RSASSA_PKCS1_v1_5_SHA256, RSASSA_PKCS1_v1_5_SHA384, Rsa1024PublicKey, + RSA1024PublicKey, RSASSA_PKCS1_v1_5_SHA256, RSASSA_PKCS1_v1_5_SHA384, }; fn bench_rsa_1024(c: &mut Criterion) { @@ -19,7 +19,7 @@ fn bench_rsa_1024(c: &mut Criterion) { 0xb909dd0f4c6014f2, 0x9c8a5810b6d05990, 0x40760d1f23fe9250, 0x90adb011a919575a, 0x45e48572113cab28, 0xcb9ca9ec12000fc8, 0x91b4fcaf62a14595, 0xac9048a7a4f560af, ]; - let pk_sha256 = Rsa1024PublicKey::new(&n_sha256, 0x10001).unwrap(); + let pk_sha256 = RSA1024PublicKey::new(&n_sha256, 0x10001).unwrap(); let msg_sha256 = hex_decode("0000000000000000000000000000000000000000").unwrap(); let sig_sha256: [u8; 128] = hex_decode( "41339884a9b3940e8488d666bb158063c6a2a2717cae7f564834a876fcbf7098ecf3acbfabf37d38a8e6127b1e313744f1f896e165efdaea0b2e7673867842b9e94db0868ed9a92bcdcb370a4e20ff275c82595e4400a8b9e9f12482f014846b48216f321266ae6ae6338dbcdc41b711e483e6e3e728772e7f9f5ef95c30196b", @@ -34,7 +34,7 @@ fn bench_rsa_1024(c: &mut Criterion) { 0xe60ee26a7b7cfccb, 0xaf86df2283c8e327, 0x7dea6692a1713516, 0xe94e94385dffc5e2, 0x8cf0173a0a309a1e, 0x3ea5161e5450d16a, 0xba51135f78844d9a, 0xa1d3912e65d994e0, ]; - let pk_sha384 = Rsa1024PublicKey::new(&n_sha384, 0x10001).unwrap(); + let pk_sha384 = RSA1024PublicKey::new(&n_sha384, 0x10001).unwrap(); let msg_sha384 = hex_decode("0000000000000000000000000000000000000000").unwrap(); let sig_sha384: [u8; 128] = hex_decode( "74b9a7b9548a281c5a258520c879e0e64d8a28812a7b6461c6e418e0502b61008a8e535a5b55fb64529a6a6df2f60ef33c1844b27f81532be2bc2992d0eb5e524112da90bf40adefcf206469639ff3895a9826674ee1acbdd623842ab0a9a36d48da13ba17c4ee069254da2ea418d5a8f135e2a414c0654a266d538621917545", diff --git a/crypto/rsa/benches/rsa_1536_benches.rs b/crypto/rsa/benches/rsa_1536_benches.rs index 84734678..4c3e058e 100644 --- a/crypto/rsa/benches/rsa_1536_benches.rs +++ b/crypto/rsa/benches/rsa_1536_benches.rs @@ -9,7 +9,7 @@ use std::hint::black_box; use bouncycastle_hex::decode as hex_decode; use bouncycastle_rsa::rsa_1536::{ - RSASSA_PKCS1_v1_5_SHA256, RSASSA_PKCS1_v1_5_SHA384, RSASSA_PKCS1_v1_5_SHA512, Rsa1536PublicKey, + RSA1536PublicKey, RSASSA_PKCS1_v1_5_SHA256, RSASSA_PKCS1_v1_5_SHA384, RSASSA_PKCS1_v1_5_SHA512, }; fn bench_rsa_1536(c: &mut Criterion) { @@ -21,7 +21,7 @@ fn bench_rsa_1536(c: &mut Criterion) { 0x5e2c811a56b5d946, 0x6c9fc8200b205487, 0x7b401487a9c85917, 0x41744b5872ccebc8, 0x86eb04d51f21ac52, 0xe029a743f0649ae5, 0x6cf4930cf2615140, 0xeb477c90d46bd189, ]; - let pk_sha256 = Rsa1536PublicKey::new(&n_sha256, 0x10001).unwrap(); + let pk_sha256 = RSA1536PublicKey::new(&n_sha256, 0x10001).unwrap(); let msg = hex_decode("0000000000000000000000000000000000000000").unwrap(); let sig_sha256: [u8; 192] = hex_decode( "8d2611d4c79f6b2087ae8bc76610905c361b9fe0a6629388197b4293f9e14ecbeb377206e4c1db35cdc0ab163dc5c51e8a7370a059e9ee8014d18ef0937f7936879d7825c792180a4f10a0d46e0a954f093d703b82bd076dcec0b8a66fc3be9bdf79ce4550c453015dc1c7397ec1bfceed040a4d777915546b9cbcf1eeb13eb71ac49c235e69cb07c315d529442f4863d61b7d5caa5ce07820edf649a9342211a26f8280dab9c5dd11af0752168326f8e8d5e834ddba3bce063f011eccc8f46d", @@ -38,7 +38,7 @@ fn bench_rsa_1536(c: &mut Criterion) { 0xd7841125d38dd9f4, 0xb0ed9964c7b125da, 0x06d573f19163ae2a, 0xa7716c797d15afe5, 0xcf19e47fadf98cfd, 0xdc9306f2f3646bbc, 0x9c3c1865cf6beaf5, 0xd1060fe7c6d185f0, ]; - let pk_sha384 = Rsa1536PublicKey::new(&n_sha384, 0x10001).unwrap(); + let pk_sha384 = RSA1536PublicKey::new(&n_sha384, 0x10001).unwrap(); let sig_sha384: [u8; 192] = hex_decode( "58c4c42da5eee1b757b31e3362a95d75180c0fee472c431527ff5500fe0b5c1d59968d79e6e41650f013a6b3e37c5a1d79233b818ef76c4ed469a09607becdc58987e6a548610de14ff06899ef284778dd5329a27b85072e8ffd46b63a5e8f7602ddb9fc5a07224c49818fc8057581ea36da033f2b936f0761186c7fd82b474e87d47aa1b7ec610642d3bcb16c59bb70ac68b1f081a9c9248f069474d6ed9b29c669fc40a979cdfc2053e1a3c0cf40efa29c01785323995f1d8f3850c32bdf92", ) @@ -54,7 +54,7 @@ fn bench_rsa_1536(c: &mut Criterion) { 0xfe887a4a1fae6ca8, 0xa96a2bedc3e72738, 0xe2ad09578c749863, 0xffb63f097ed7b5c5, 0xcea5ba02d99f0807, 0x1cb9a9b7b769d6df, 0xfd4c711aef054e29, 0xd1f33c4d0c3b127c, ]; - let pk_sha512 = Rsa1536PublicKey::new(&n_sha512, 0x10001).unwrap(); + let pk_sha512 = RSA1536PublicKey::new(&n_sha512, 0x10001).unwrap(); let sig_sha512: [u8; 192] = hex_decode( "5259fe9566e1bd81952a805384b1657374f33550ee0895b57b7a0869a831270d3b3b2db8e295a4eb98d8eb036183b3d228ad22b8e493c7eb0f9ab00eeab2e086f10f8018a8daaff4858ae745a4d70881a166963c64403216422e18974aa456d8229ef2e43002e0390166630c7fabd14efaa974a9521a72a69e0b446971db077ce80f6dd95cf797b6ed276873bbf6b1ba6a79df8c917c2a3fbbc0e5347b0bb99eec6ad0b6bdb7bc9d3e0a7f6b7b623f2aa9dba1e940676ec5629d39778286f261", ) diff --git a/crypto/rsa/benches/rsa_2048_benches.rs b/crypto/rsa/benches/rsa_2048_benches.rs index f979d920..4f0c0ad0 100644 --- a/crypto/rsa/benches/rsa_2048_benches.rs +++ b/crypto/rsa/benches/rsa_2048_benches.rs @@ -10,14 +10,14 @@ use std::hint::black_box; use bouncycastle_rng::DefaultRNG; 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, - Rsa2048PrivateKey, Rsa2048PublicKey, + RSA2048PrivateKey, RSA2048PublicKey, 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() -> Rsa2048PrivateKey { +fn genuine_key() -> RSA2048PrivateKey { let p: [u64; 16] = [ 0x0ea36cfb3a5b18f1, 0x48a6e65332119129, 0x110ad9e7b48a1c93, 0x569156b90113e2e9, 0xe79813a575cfad9c, 0x69d659d143ec6f17, 0xe81e6bab5ddaa783, 0xbff1c5b80a69f788, @@ -48,13 +48,13 @@ fn genuine_key() -> Rsa2048PrivateKey { 0xe923e1097c0c562f, 0xc968b48a91c38b5b, 0x933e85179c0320b0, 0x7993d0445f758d51, 0x9bfc042ee0924b1b, 0x41f956d90fa8a793, 0xee7a87b6483a66ee, 0x2640fbfbcfefb163, ]; - Rsa2048PrivateKey::from_crt_components(&p, &q, &d_p, &d_q, &q_inv) + RSA2048PrivateKey::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 = Rsa2048PublicKey::new(sk.n(), 0x10001).unwrap(); + let pk = RSA2048PublicKey::new(sk.n(), 0x10001).unwrap(); let mut rng = DefaultRNG::default(); let sig_pkcs1_256 = RSASSA_PKCS1_v1_5_SHA256::sign(&sk, MSG, None).unwrap(); diff --git a/crypto/rsa/benches/rsa_3072_benches.rs b/crypto/rsa/benches/rsa_3072_benches.rs index fa873308..7d40145e 100644 --- a/crypto/rsa/benches/rsa_3072_benches.rs +++ b/crypto/rsa/benches/rsa_3072_benches.rs @@ -8,14 +8,14 @@ use std::hint::black_box; use bouncycastle_rng::DefaultRNG; 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, - Rsa3072PrivateKey, Rsa3072PublicKey, + RSA3072PrivateKey, RSA3072PublicKey, 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() -> Rsa3072PrivateKey { +fn genuine_key() -> RSA3072PrivateKey { let p: [u64; 24] = [ 0xb26d973345bc4c5f, 0x23251a1d29962ca9, 0x554fc3f23d6c9046, 0x89ffe73b1401e9b8, 0xe0b448b454670aca, 0xa73ea5c2413d1da2, 0xe9539bc7a8d3b351, 0x357984fc116af9cb, @@ -56,13 +56,13 @@ fn genuine_key() -> Rsa3072PrivateKey { 0xfe6c3600d9b8e9a9, 0x744fac4daabf5488, 0xfbee6ec24b75fbf0, 0x8be552c8be44f139, 0xfb0da96bd423759d, 0xb3443d93e7e8ca62, 0x36fe01b950885ecd, 0x214a1f73130e48b3, ]; - Rsa3072PrivateKey::from_crt_components(&p, &q, &d_p, &d_q, &q_inv) + RSA3072PrivateKey::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 = Rsa3072PublicKey::new(sk.n(), 0x10001).unwrap(); + let pk = RSA3072PublicKey::new(sk.n(), 0x10001).unwrap(); let mut rng = DefaultRNG::default(); let sig_pkcs1_256 = RSASSA_PKCS1_v1_5_SHA256::sign(&sk, MSG, None).unwrap(); diff --git a/crypto/rsa/benches/rsa_4096_benches.rs b/crypto/rsa/benches/rsa_4096_benches.rs index 23738191..1eb00c31 100644 --- a/crypto/rsa/benches/rsa_4096_benches.rs +++ b/crypto/rsa/benches/rsa_4096_benches.rs @@ -9,14 +9,14 @@ use std::hint::black_box; use bouncycastle_rng::DefaultRNG; 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, - Rsa4096PrivateKey, Rsa4096PublicKey, + RSA4096PrivateKey, RSA4096PublicKey, 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() -> Rsa4096PrivateKey { +fn genuine_key() -> RSA4096PrivateKey { let p: [u64; 32] = [ 0x5141acd4afd4771f, 0x5857742b7e4032dc, 0xb7a9b97fe5371396, 0x4b1783c5bc91a6dc, 0xaf5d0c912d97b728, 0xeb265a7f28b88976, 0x5e993302aa72f11d, 0xc007ad09d76ae22a, @@ -67,13 +67,13 @@ fn genuine_key() -> Rsa4096PrivateKey { 0x748d7b5d94cacd4d, 0xcf634f3a07cea4b7, 0x8dbcca51f4da4379, 0x80774236a54ec9dc, 0x6a1ef00ee582d3d1, 0xdecfb14ca1e80c8e, 0xc78af5f6c807cc99, 0x484ad86e79415ea3, ]; - Rsa4096PrivateKey::from_crt_components(&p, &q, &d_p, &d_q, &q_inv) + RSA4096PrivateKey::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 = Rsa4096PublicKey::new(sk.n(), 0x10001).unwrap(); + let pk = RSA4096PublicKey::new(sk.n(), 0x10001).unwrap(); let mut rng = DefaultRNG::default(); let sig_pkcs1_256 = RSASSA_PKCS1_v1_5_SHA256::sign(&sk, MSG, None).unwrap(); diff --git a/crypto/rsa/benches/rsa_8192_benches.rs b/crypto/rsa/benches/rsa_8192_benches.rs index b5742afd..36b6435c 100644 --- a/crypto/rsa/benches/rsa_8192_benches.rs +++ b/crypto/rsa/benches/rsa_8192_benches.rs @@ -9,13 +9,13 @@ use std::hint::black_box; use bouncycastle_rng::DefaultRNG; 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, Rsa8192PrivateKey, Rsa8192PublicKey, + RSA8192PrivateKey, RSA8192PublicKey, 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() -> Rsa8192PrivateKey { +fn genuine_key() -> RSA8192PrivateKey { let p: [u64; 64] = [ 0xa9a87892c469b1e5, 0x038c3f4efcb198ac, 0xed4f14df1b8a1e1f, 0xef2330d78ee73020, 0xd3093ddaf276904c, 0x94a438d69aeaff23, 0x48dbb3d700ad58ed, 0xbbd763b5346ff916, @@ -106,13 +106,13 @@ fn genuine_key() -> Rsa8192PrivateKey { 0xd1aac2fe108f98c0, 0x1e799537a42b3060, 0xdbcce6fc287e449b, 0x1985969e5afbc524, 0x61ba61f820f83597, 0x65c8523f0767bccc, 0xde04e1644a214f9a, 0x9748f8d853be7131, ]; - Rsa8192PrivateKey::from_crt_components(&p, &q, &d_p, &d_q, &q_inv) + RSA8192PrivateKey::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 = Rsa8192PublicKey::new(sk.n(), 0x10001).unwrap(); + let pk = RSA8192PublicKey::new(sk.n(), 0x10001).unwrap(); let mut rng = DefaultRNG::default(); let sig_pkcs1_256 = RSASSA_PKCS1_v1_5_SHA256::sign(&sk, MSG, None).unwrap(); diff --git a/crypto/rsa/src/keys.rs b/crypto/rsa/src/keys.rs index 98951a90..530b180d 100644 --- a/crypto/rsa/src/keys.rs +++ b/crypto/rsa/src/keys.rs @@ -8,7 +8,7 @@ //! `(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. //! -//! Each concrete modulus size's aliases of these types (`crate::rsa_2048::Rsa2048PrivateKey` and +//! Each concrete modulus size's aliases of these types (`crate::rsa_2048::RSA2048PrivateKey` and //! siblings) implement `bouncycastle_core`'s `SignaturePrivateKey`/`SignaturePublicKey` traits, //! in that size's module, with the byte layouts described on each type below; the generic types //! here only carry the layout's implementation (`encode_raw`/`from_bytes_raw`, crate-private), @@ -28,7 +28,7 @@ use core::fmt::{Display, Formatter}; /// # Encoding /// /// `SignaturePublicKey::encode`/`from_bytes` (implemented per size, e.g. for -/// `crate::rsa_2048::Rsa2048PublicKey`) use the raw layout `n || e`: `n` as `8 * L` big-endian +/// `crate::rsa_2048::RSA2048PublicKey`) use the raw layout `n || e`: `n` as `8 * L` big-endian /// bytes (RFC 8017 §4.1's I2OSP), then `e` as 4 big-endian bytes, `PK_LEN = 8 * L + 4` 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. @@ -134,7 +134,7 @@ impl Display for RsaPublicKey { /// # Encoding /// /// `SignaturePrivateKey::encode`/`from_bytes` (implemented per size, e.g. for -/// `crate::rsa_2048::Rsa2048PrivateKey`) use the raw layout `p || q || dP || dQ || qInv`, each +/// `crate::rsa_2048::RSA2048PrivateKey`) use the raw layout `p || q || dP || dQ || qInv`, each /// `8 * HALF` big-endian bytes, `SK_LEN = 40 * HALF` 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 diff --git a/crypto/rsa/src/lib.rs b/crypto/rsa/src/lib.rs index 69e01cd8..b37ad6b9 100644 --- a/crypto/rsa/src/lib.rs +++ b/crypto/rsa/src/lib.rs @@ -31,15 +31,15 @@ //! //! ``` //! use bouncycastle_core::traits::{SignaturePrivateKey, SignaturePublicKey, SignatureVerifier, Signer}; -//! use bouncycastle_rsa::rsa_2048::{RSASSA_PKCS1_v1_5_SHA256, RSASSA_PSS_SHA256, Rsa2048PrivateKey, Rsa2048PublicKey}; +//! use bouncycastle_rsa::rsa_2048::{RSASSA_PKCS1_v1_5_SHA256, RSASSA_PSS_SHA256, RSA2048PrivateKey, RSA2048PublicKey}; //! # // The same genuine RSA-2048 keypair as the next example; see there for its provenance. //! # const P: [u64; 16] = [0x0ea36cfb3a5b18f1, 0x48a6e65332119129, 0x110ad9e7b48a1c93, 0x569156b90113e2e9, 0xe79813a575cfad9c, 0x69d659d143ec6f17, 0xe81e6bab5ddaa783, 0xbff1c5b80a69f788, 0x978f6c35814f50ee, 0xe6a289ad4cfbf78f, 0x34d5681e5809d415, 0xbb028bda42eeb5d2, 0x41c56e4de086b0d5, 0x58b8d1e24f3b55d0, 0xfb5248247d98cb7d, 0xdc431050f782e894]; //! # const Q: [u64; 16] = [0x669f140cfbc20f25, 0xb97bb03677207d95, 0xfd4e06f3ed7299d4, 0x160f90536abc9492, 0xf5b131f39098f7bc, 0xae8d72c57088d7ab, 0x89b94fbde542aba9, 0x3d3f9880ec47d5e0, 0x1378a6868af3b7a0, 0x5544070beb057c94, 0x16611debc472fac4, 0xe500ffb79f5b8868, 0x308a5e32196603b2, 0xea5fb19eb4eabc38, 0x122273ae3222b598, 0xbd1a81e7977f9898]; //! # const D_P: [u64; 16] = [0x209f33f09515d7c1, 0xb4a9b37656917205, 0x276933bb07e4efb9, 0x8c14019808e00414, 0x289f96da220711e5, 0xfbbd2923d31532fe, 0xc06b414e61c0e1e7, 0x4c23c4588488961d, 0x4dc48ae34514759c, 0x9c786961ae3e2c35, 0x497e8d9c650688e0, 0x18bf08472612dbe5, 0x8885fb161870ee12, 0xf21d7c1479d99d47, 0x9121d91952ffd1c7, 0xa94b528b28f29159]; //! # const D_Q: [u64; 16] = [0xf7597ffb68011d8d, 0x7b3cc538c4bab8c9, 0xa8fa480a81a925af, 0x6d6ede7251a383bf, 0x8a63f788ce3a0f85, 0x0b920502eb478bc9, 0x7e37e755edfe70d9, 0x9cf9948422a16555, 0x0d6d9ea1f2ef71fd, 0xf7efa32ea0cb6e00, 0x0629b114ca7f780f, 0xcf51176359654348, 0x540cdcbd4ad35435, 0x31c02ff1a2bc437c, 0xff2503df78bafed5, 0x3af0e72a933aef09]; //! # const Q_INV: [u64; 16] = [0x552fe4bfce945f7b, 0x67e50c999c67247b, 0xfb54ef17be3b2853, 0x241f5921b5ad3983, 0x02de5eccd143cf31, 0x74e45f6fcc60f216, 0xafa5428a74f12708, 0x88d42294b6a2759b, 0xe923e1097c0c562f, 0xc968b48a91c38b5b, 0x933e85179c0320b0, 0x7993d0445f758d51, 0x9bfc042ee0924b1b, 0x41f956d90fa8a793, 0xee7a87b6483a66ee, 0x2640fbfbcfefb163]; -//! let sk = Rsa2048PrivateKey::from_crt_components(&P, &Q, &D_P, &D_Q, &Q_INV)?; -//! let pk = Rsa2048PublicKey::new(sk.n(), 0x10001)?; +//! let sk = RSA2048PrivateKey::from_crt_components(&P, &Q, &D_P, &D_Q, &Q_INV)?; +//! let pk = RSA2048PublicKey::new(sk.n(), 0x10001)?; //! //! // One-shot. RSA has no context string, so `ctx` is `None` (a `Some` is accepted and ignored). //! let signature = RSASSA_PKCS1_v1_5_SHA256::sign(&sk, b"the message to sign", None)?; @@ -86,9 +86,9 @@ //! RSASSA_PSS_SHA256::verify(&pk, b"the message to sign", None, &sig_d)?; //! //! // Keys round-trip through the traits' raw fixed-width encoding (see `keys`'s docs). -//! let pk_again = Rsa2048PublicKey::from_bytes(&pk.encode())?; +//! let pk_again = RSA2048PublicKey::from_bytes(&pk.encode())?; //! assert_eq!(pk_again, pk); -//! let sk_again = Rsa2048PrivateKey::from_bytes(&sk.encode())?; +//! let sk_again = RSA2048PrivateKey::from_bytes(&sk.encode())?; //! assert_eq!(sk_again, sk); //! # Ok::<(), bouncycastle_core::errors::SignatureError>(()) //! ``` @@ -100,11 +100,11 @@ //! //! ``` //! use bouncycastle_core::traits::SignatureVerifier; -//! use bouncycastle_rsa::rsa_1024::{RSASSA_PKCS1_v1_5_SHA256, Rsa1024PublicKey}; +//! use bouncycastle_rsa::rsa_1024::{RSASSA_PKCS1_v1_5_SHA256, RSA1024PublicKey}; //! # 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 = Rsa1024PublicKey::new(&N, 0x10001)?; +//! let pk = RSA1024PublicKey::new(&N, 0x10001)?; //! RSASSA_PKCS1_v1_5_SHA256::verify(&pk, &msg, None, &sig)?; //! # Ok::<(), bouncycastle_core::errors::SignatureError>(()) //! ``` diff --git a/crypto/rsa/src/rsa_1024.rs b/crypto/rsa/src/rsa_1024.rs index 0bc22535..372e9ae3 100644 --- a/crypto/rsa/src/rsa_1024.rs +++ b/crypto/rsa/src/rsa_1024.rs @@ -1,4 +1,4 @@ -//! RSA-1024: verification only. `L = 16` (1024 bits). There is no `Rsa1024PrivateKey` and no +//! RSA-1024: verification only. `L = 16` (1024 bits). There is no `RSA1024PrivateKey` and no //! signing function -- per this crate's `# Scope` (see `src/lib.rs`), a 1024-bit modulus is for //! verifying signatures made elsewhere (legacy interoperability), not for producing new ones, and //! that is enforced by the absent type rather than a runtime check. @@ -34,15 +34,15 @@ use bouncycastle_core::traits::SignaturePublicKey; use bouncycastle_sha2::{SHA256, SHA384}; /// An RSA-1024 public key. -pub type Rsa1024PublicKey = RsaPublicKey<16>; +pub type RSA1024PublicKey = RsaPublicKey<16>; -/// Encoded length of an [`Rsa1024PublicKey`] under [`SignaturePublicKey`]: 128 + 4 bytes (see +/// Encoded length of an [`RSA1024PublicKey`] under [`SignaturePublicKey`]: 128 + 4 bytes (see /// [`RsaPublicKey`]'s `# Encoding`). pub const PK_LEN: usize = 132; /// Signature length: `k`, the modulus length in octets (RFC 8017 §8.2.1 step 2.c). pub const SIG_LEN: usize = 128; -impl SignaturePublicKey for Rsa1024PublicKey { +impl SignaturePublicKey for RSA1024PublicKey { fn encode(&self) -> [u8; PK_LEN] { self.encode_raw::<128, PK_LEN>() } diff --git a/crypto/rsa/src/rsa_1536.rs b/crypto/rsa/src/rsa_1536.rs index e8c4dff1..6771d752 100644 --- a/crypto/rsa/src/rsa_1536.rs +++ b/crypto/rsa/src/rsa_1536.rs @@ -1,5 +1,5 @@ //! RSA-1536: verification only. `L = 24` (1536 bits). As with [`crate::rsa_1024`], there is no -//! `Rsa1536PrivateKey` and no signing function -- see that module's docs and this crate's +//! `RSA1536PrivateKey` and no signing function -- see that module's docs and this crate's //! `# Scope` for why. //! //! Only PKCS#1 v1.5 is wired up: Wycheproof has no PSS vectors at 1536 bits (nor, realistically, @@ -17,15 +17,15 @@ use bouncycastle_core::traits::SignaturePublicKey; use bouncycastle_sha2::{SHA256, SHA384, SHA512}; /// An RSA-1536 public key. -pub type Rsa1536PublicKey = RsaPublicKey<24>; +pub type RSA1536PublicKey = RsaPublicKey<24>; -/// Encoded length of an [`Rsa1536PublicKey`] under [`SignaturePublicKey`]: 192 + 4 bytes (see +/// Encoded length of an [`RSA1536PublicKey`] under [`SignaturePublicKey`]: 192 + 4 bytes (see /// [`RsaPublicKey`]'s `# Encoding`). pub const PK_LEN: usize = 196; /// Signature length: `k`, the modulus length in octets (RFC 8017 §8.2.1 step 2.c). pub const SIG_LEN: usize = 192; -impl SignaturePublicKey for Rsa1536PublicKey { +impl SignaturePublicKey for RSA1536PublicKey { fn encode(&self) -> [u8; PK_LEN] { self.encode_raw::<192, PK_LEN>() } diff --git a/crypto/rsa/src/rsa_2048.rs b/crypto/rsa/src/rsa_2048.rs index d87e5fe7..880a7764 100644 --- a/crypto/rsa/src/rsa_2048.rs +++ b/crypto/rsa/src/rsa_2048.rs @@ -23,20 +23,20 @@ use bouncycastle_sha2::{SHA256, SHA384, SHA512}; use bouncycastle_sha3::SHAKE128; /// An RSA-2048 private key (`p`, `q` each 1024 bits). -pub type Rsa2048PrivateKey = RsaPrivateKey<32, 16>; +pub type RSA2048PrivateKey = RsaPrivateKey<32, 16>; /// An RSA-2048 public key. -pub type Rsa2048PublicKey = RsaPublicKey<32>; +pub type RSA2048PublicKey = RsaPublicKey<32>; -/// Encoded length of an [`Rsa2048PrivateKey`] under [`SignaturePrivateKey`]: `p || q || dP || dQ +/// Encoded length of an [`RSA2048PrivateKey`] under [`SignaturePrivateKey`]: `p || q || dP || dQ /// || qInv`, five 128-byte values (see [`RsaPrivateKey`]'s `# Encoding`). pub const SK_LEN: usize = 640; -/// Encoded length of an [`Rsa2048PublicKey`] under [`SignaturePublicKey`]: `n || e`, 256 + 4 +/// Encoded length of an [`RSA2048PublicKey`] under [`SignaturePublicKey`]: `n || e`, 256 + 4 /// bytes (see [`RsaPublicKey`]'s `# Encoding`). pub const PK_LEN: usize = 260; /// Signature length: `k`, the modulus length in octets (RFC 8017 §8.1.1/§8.2.1 step 2.c). pub const SIG_LEN: usize = 256; -impl SignaturePrivateKey for Rsa2048PrivateKey { +impl SignaturePrivateKey for RSA2048PrivateKey { fn encode(&self) -> [u8; SK_LEN] { self.encode_raw::<128, SK_LEN>() } @@ -54,7 +54,7 @@ impl SignaturePrivateKey for Rsa2048PrivateKey { } } -impl SignaturePublicKey for Rsa2048PublicKey { +impl SignaturePublicKey for RSA2048PublicKey { fn encode(&self) -> [u8; PK_LEN] { self.encode_raw::<256, PK_LEN>() } diff --git a/crypto/rsa/src/rsa_3072.rs b/crypto/rsa/src/rsa_3072.rs index d0399e78..1423746b 100644 --- a/crypto/rsa/src/rsa_3072.rs +++ b/crypto/rsa/src/rsa_3072.rs @@ -11,20 +11,20 @@ use bouncycastle_sha2::{SHA256, SHA384, SHA512}; use bouncycastle_sha3::SHAKE128; /// An RSA-3072 private key (`p`, `q` each 1536 bits). -pub type Rsa3072PrivateKey = RsaPrivateKey<48, 24>; +pub type RSA3072PrivateKey = RsaPrivateKey<48, 24>; /// An RSA-3072 public key. -pub type Rsa3072PublicKey = RsaPublicKey<48>; +pub type RSA3072PublicKey = RsaPublicKey<48>; -/// Encoded length of an [`Rsa3072PrivateKey`] under [`SignaturePrivateKey`]: five 192-byte +/// Encoded length of an [`RSA3072PrivateKey`] under [`SignaturePrivateKey`]: five 192-byte /// values (see [`RsaPrivateKey`]'s `# Encoding`). pub const SK_LEN: usize = 960; -/// Encoded length of an [`Rsa3072PublicKey`] under [`SignaturePublicKey`]: 384 + 4 bytes (see +/// Encoded length of an [`RSA3072PublicKey`] under [`SignaturePublicKey`]: 384 + 4 bytes (see /// [`RsaPublicKey`]'s `# Encoding`). pub const PK_LEN: usize = 388; /// Signature length: `k`, the modulus length in octets (RFC 8017 §8.1.1/§8.2.1 step 2.c). pub const SIG_LEN: usize = 384; -impl SignaturePrivateKey for Rsa3072PrivateKey { +impl SignaturePrivateKey for RSA3072PrivateKey { fn encode(&self) -> [u8; SK_LEN] { self.encode_raw::<192, SK_LEN>() } @@ -42,7 +42,7 @@ impl SignaturePrivateKey for Rsa3072PrivateKey { } } -impl SignaturePublicKey for Rsa3072PublicKey { +impl SignaturePublicKey for RSA3072PublicKey { fn encode(&self) -> [u8; PK_LEN] { self.encode_raw::<384, PK_LEN>() } diff --git a/crypto/rsa/src/rsa_4096.rs b/crypto/rsa/src/rsa_4096.rs index 75c8c240..066576b5 100644 --- a/crypto/rsa/src/rsa_4096.rs +++ b/crypto/rsa/src/rsa_4096.rs @@ -11,20 +11,20 @@ use bouncycastle_sha2::{SHA256, SHA384, SHA512}; use bouncycastle_sha3::SHAKE256; /// An RSA-4096 private key (`p`, `q` each 2048 bits). -pub type Rsa4096PrivateKey = RsaPrivateKey<64, 32>; +pub type RSA4096PrivateKey = RsaPrivateKey<64, 32>; /// An RSA-4096 public key. -pub type Rsa4096PublicKey = RsaPublicKey<64>; +pub type RSA4096PublicKey = RsaPublicKey<64>; -/// Encoded length of an [`Rsa4096PrivateKey`] under [`SignaturePrivateKey`]: five 256-byte +/// Encoded length of an [`RSA4096PrivateKey`] under [`SignaturePrivateKey`]: five 256-byte /// values (see [`RsaPrivateKey`]'s `# Encoding`). pub const SK_LEN: usize = 1280; -/// Encoded length of an [`Rsa4096PublicKey`] under [`SignaturePublicKey`]: 512 + 4 bytes (see +/// Encoded length of an [`RSA4096PublicKey`] under [`SignaturePublicKey`]: 512 + 4 bytes (see /// [`RsaPublicKey`]'s `# Encoding`). pub const PK_LEN: usize = 516; /// Signature length: `k`, the modulus length in octets (RFC 8017 §8.1.1/§8.2.1 step 2.c). pub const SIG_LEN: usize = 512; -impl SignaturePrivateKey for Rsa4096PrivateKey { +impl SignaturePrivateKey for RSA4096PrivateKey { fn encode(&self) -> [u8; SK_LEN] { self.encode_raw::<256, SK_LEN>() } @@ -42,7 +42,7 @@ impl SignaturePrivateKey for Rsa4096PrivateKey { } } -impl SignaturePublicKey for Rsa4096PublicKey { +impl SignaturePublicKey for RSA4096PublicKey { fn encode(&self) -> [u8; PK_LEN] { self.encode_raw::<512, PK_LEN>() } diff --git a/crypto/rsa/src/rsa_8192.rs b/crypto/rsa/src/rsa_8192.rs index ca8ddc0f..60e21907 100644 --- a/crypto/rsa/src/rsa_8192.rs +++ b/crypto/rsa/src/rsa_8192.rs @@ -9,20 +9,20 @@ use bouncycastle_core::traits::{SignaturePrivateKey, SignaturePublicKey}; use bouncycastle_sha2::{SHA256, SHA384, SHA512}; /// An RSA-8192 private key (`p`, `q` each 4096 bits). -pub type Rsa8192PrivateKey = RsaPrivateKey<128, 64>; +pub type RSA8192PrivateKey = RsaPrivateKey<128, 64>; /// An RSA-8192 public key. -pub type Rsa8192PublicKey = RsaPublicKey<128>; +pub type RSA8192PublicKey = RsaPublicKey<128>; -/// Encoded length of an [`Rsa8192PrivateKey`] under [`SignaturePrivateKey`]: five 512-byte +/// Encoded length of an [`RSA8192PrivateKey`] under [`SignaturePrivateKey`]: five 512-byte /// values (see [`RsaPrivateKey`]'s `# Encoding`). pub const SK_LEN: usize = 2560; -/// Encoded length of an [`Rsa8192PublicKey`] under [`SignaturePublicKey`]: 1024 + 4 bytes (see +/// Encoded length of an [`RSA8192PublicKey`] under [`SignaturePublicKey`]: 1024 + 4 bytes (see /// [`RsaPublicKey`]'s `# Encoding`). pub const PK_LEN: usize = 1028; /// Signature length: `k`, the modulus length in octets (RFC 8017 §8.1.1/§8.2.1 step 2.c). pub const SIG_LEN: usize = 1024; -impl SignaturePrivateKey for Rsa8192PrivateKey { +impl SignaturePrivateKey for RSA8192PrivateKey { fn encode(&self) -> [u8; SK_LEN] { self.encode_raw::<512, SK_LEN>() } @@ -40,7 +40,7 @@ impl SignaturePrivateKey for Rsa8192PrivateKey { } } -impl SignaturePublicKey for Rsa8192PublicKey { +impl SignaturePublicKey for RSA8192PublicKey { fn encode(&self) -> [u8; PK_LEN] { self.encode_raw::<1024, PK_LEN>() } diff --git a/crypto/rsa/tests/keys_tests.rs b/crypto/rsa/tests/keys_tests.rs index 6fbd8ef4..dbbd123e 100644 --- a/crypto/rsa/tests/keys_tests.rs +++ b/crypto/rsa/tests/keys_tests.rs @@ -1,6 +1,6 @@ //! Validation tests for [`bouncycastle_rsa::keys`]'s public API, including the //! `SignaturePrivateKey`/`SignaturePublicKey` impls `rsa_2048` gives its aliases of these types -//! (`RsaPrivateKey<32, 16>` *is* `Rsa2048PrivateKey`, so the traits' methods resolve here once +//! (`RsaPrivateKey<32, 16>` *is* `RSA2048PrivateKey`, 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. diff --git a/crypto/rsa/tests/rsa_1024_tests.rs b/crypto/rsa/tests/rsa_1024_tests.rs index 267f25f4..e9e5d946 100644 --- a/crypto/rsa/tests/rsa_1024_tests.rs +++ b/crypto/rsa/tests/rsa_1024_tests.rs @@ -10,7 +10,7 @@ use bouncycastle_core::errors::SignatureError; use bouncycastle_core::traits::{SignaturePublicKey, SignatureVerifier}; use bouncycastle_hex::decode as hex_decode; use bouncycastle_rsa::rsa_1024::{ - PK_LEN, RSASSA_PKCS1_v1_5_SHA256, RSASSA_PKCS1_v1_5_SHA384, Rsa1024PublicKey, + PK_LEN, RSA1024PublicKey, RSASSA_PKCS1_v1_5_SHA256, RSASSA_PKCS1_v1_5_SHA384, }; use serde_json::Value; use std::fs; @@ -49,7 +49,7 @@ fn limbs_from_hex(hex: &str) -> [u64; L] { fn run_sig_gen_group_as_verify_vectors( sha: &str, - verify: impl Fn(&Rsa1024PublicKey, &[u8], &[u8; 128]) -> bool, + verify: impl Fn(&RSA1024PublicKey, &[u8], &[u8; 128]) -> bool, ) { let doc: Value = serde_json::from_str(&get_test_data("rsa_pkcs1_1024_sig_gen_test.json")).unwrap(); @@ -63,7 +63,7 @@ fn run_sig_gen_group_as_verify_vectors( 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 = Rsa1024PublicKey::new(&n, e).expect("group public key must be valid"); + let pk = RSA1024PublicKey::new(&n, e).expect("group public key must be valid"); let mut num_tests = 0usize; for test in group["tests"].as_array().unwrap() { @@ -93,7 +93,7 @@ fn pkcs1_v1_5_sha384_accepts_genuine_sig_gen_signatures() { fn run_sig_gen_group_rejects_wrong_message( sha: &str, - verify: impl Fn(&Rsa1024PublicKey, &[u8], &[u8; 128]) -> bool, + verify: impl Fn(&RSA1024PublicKey, &[u8], &[u8; 128]) -> bool, ) { let doc: Value = serde_json::from_str(&get_test_data("rsa_pkcs1_1024_sig_gen_test.json")).unwrap(); @@ -106,7 +106,7 @@ fn run_sig_gen_group_rejects_wrong_message( 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 = Rsa1024PublicKey::new(&n, e).unwrap(); + let pk = RSA1024PublicKey::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(); @@ -157,19 +157,19 @@ fn public_key_trait_encoding_round_trips_and_rejects_wrong_lengths() { 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 = Rsa1024PublicKey::new(&n, e).unwrap(); + let pk = RSA1024PublicKey::new(&n, e).unwrap(); let bytes = pk.encode(); assert_eq!(bytes.len(), PK_LEN); - assert_eq!(Rsa1024PublicKey::from_bytes(&bytes).unwrap(), pk); + assert_eq!(RSA1024PublicKey::from_bytes(&bytes).unwrap(), pk); assert!(matches!( - Rsa1024PublicKey::from_bytes(&bytes[..PK_LEN - 1]), + RSA1024PublicKey::from_bytes(&bytes[..PK_LEN - 1]), Err(SignatureError::DecodingError(_)) )); let mut too_long = bytes.to_vec(); too_long.push(0); assert!(matches!( - Rsa1024PublicKey::from_bytes(&too_long), + RSA1024PublicKey::from_bytes(&too_long), Err(SignatureError::DecodingError(_)) )); } diff --git a/crypto/rsa/tests/rsa_1536_tests.rs b/crypto/rsa/tests/rsa_1536_tests.rs index ca9a69e8..57eb4f0b 100644 --- a/crypto/rsa/tests/rsa_1536_tests.rs +++ b/crypto/rsa/tests/rsa_1536_tests.rs @@ -8,8 +8,8 @@ use bouncycastle_core::errors::SignatureError; use bouncycastle_core::traits::{SignaturePublicKey, SignatureVerifier}; use bouncycastle_hex::decode as hex_decode; use bouncycastle_rsa::rsa_1536::{ - PK_LEN, RSASSA_PKCS1_v1_5_SHA256, RSASSA_PKCS1_v1_5_SHA384, RSASSA_PKCS1_v1_5_SHA512, - Rsa1536PublicKey, + PK_LEN, RSA1536PublicKey, RSASSA_PKCS1_v1_5_SHA256, RSASSA_PKCS1_v1_5_SHA384, + RSASSA_PKCS1_v1_5_SHA512, }; use serde_json::Value; use std::fs; @@ -48,7 +48,7 @@ fn limbs_from_hex(hex: &str) -> [u64; L] { fn run_sig_gen_group_as_verify_vectors( sha: &str, - verify: impl Fn(&Rsa1536PublicKey, &[u8], &[u8; 192]) -> bool, + verify: impl Fn(&RSA1536PublicKey, &[u8], &[u8; 192]) -> bool, ) { let doc: Value = serde_json::from_str(&get_test_data("rsa_pkcs1_1536_sig_gen_test.json")).unwrap(); @@ -62,7 +62,7 @@ fn run_sig_gen_group_as_verify_vectors( 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 = Rsa1536PublicKey::new(&n, e).expect("group public key must be valid"); + let pk = RSA1536PublicKey::new(&n, e).expect("group public key must be valid"); let mut num_tests = 0usize; for test in group["tests"].as_array().unwrap() { @@ -99,7 +99,7 @@ fn pkcs1_v1_5_sha512_accepts_genuine_sig_gen_signatures() { fn run_sig_gen_group_rejects_wrong_message( sha: &str, - verify: impl Fn(&Rsa1536PublicKey, &[u8], &[u8; 192]) -> bool, + verify: impl Fn(&RSA1536PublicKey, &[u8], &[u8; 192]) -> bool, ) { let doc: Value = serde_json::from_str(&get_test_data("rsa_pkcs1_1536_sig_gen_test.json")).unwrap(); @@ -107,7 +107,7 @@ fn run_sig_gen_group_rejects_wrong_message( 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 = Rsa1536PublicKey::new(&n, e).unwrap(); + let pk = RSA1536PublicKey::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(); @@ -161,19 +161,19 @@ fn public_key_trait_encoding_round_trips_and_rejects_wrong_lengths() { 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 = Rsa1536PublicKey::new(&n, e).unwrap(); + let pk = RSA1536PublicKey::new(&n, e).unwrap(); let bytes = pk.encode(); assert_eq!(bytes.len(), PK_LEN); - assert_eq!(Rsa1536PublicKey::from_bytes(&bytes).unwrap(), pk); + assert_eq!(RSA1536PublicKey::from_bytes(&bytes).unwrap(), pk); assert!(matches!( - Rsa1536PublicKey::from_bytes(&bytes[..PK_LEN - 1]), + RSA1536PublicKey::from_bytes(&bytes[..PK_LEN - 1]), Err(SignatureError::DecodingError(_)) )); let mut too_long = bytes.to_vec(); too_long.push(0); assert!(matches!( - Rsa1536PublicKey::from_bytes(&too_long), + RSA1536PublicKey::from_bytes(&too_long), Err(SignatureError::DecodingError(_)) )); } 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 index ff4fb121..70fea371 100644 --- 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 @@ -18,8 +18,8 @@ use bouncycastle_core::traits::{SignatureVerifier, Signer}; use bouncycastle_core_test_framework::signature::TestFrameworkSignature; use bouncycastle_hex::decode as hex_decode; use bouncycastle_rsa::rsa_2048::{ - PK_LEN, RSASSA_PKCS1_v1_5_SHA384, RSASSA_PKCS1_v1_5_SHA512, Rsa2048PrivateKey, - Rsa2048PublicKey, SIG_LEN, SK_LEN, + PK_LEN, RSA2048PrivateKey, RSA2048PublicKey, RSASSA_PKCS1_v1_5_SHA384, + RSASSA_PKCS1_v1_5_SHA512, SIG_LEN, SK_LEN, }; use serde_json::Value; use std::fs; @@ -59,7 +59,7 @@ fn limbs_from_hex(hex: &str) -> [u64; L] { /// 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() -> Rsa2048PrivateKey { +fn genuine_key() -> RSA2048PrivateKey { let p: [u64; 16] = [ 0x0ea36cfb3a5b18f1, 0x48a6e65332119129, 0x110ad9e7b48a1c93, 0x569156b90113e2e9, 0xe79813a575cfad9c, 0x69d659d143ec6f17, 0xe81e6bab5ddaa783, 0xbff1c5b80a69f788, @@ -90,14 +90,14 @@ fn genuine_key() -> Rsa2048PrivateKey { 0xe923e1097c0c562f, 0xc968b48a91c38b5b, 0x933e85179c0320b0, 0x7993d0445f758d51, 0x9bfc042ee0924b1b, 0x41f956d90fa8a793, 0xee7a87b6483a66ee, 0x2640fbfbcfefb163, ]; - Rsa2048PrivateKey::from_crt_components(&p, &q, &d_p, &d_q, &q_inv) + RSA2048PrivateKey::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 = Rsa2048PublicKey::new(sk.n(), 0x10001).unwrap(); + let pk = RSA2048PublicKey::new(sk.n(), 0x10001).unwrap(); let sig = RSASSA_PKCS1_v1_5_SHA384::sign(&sk, b"hello", None).expect("signing must succeed"); RSASSA_PKCS1_v1_5_SHA384::verify(&pk, b"hello", None, &sig).expect("must verify"); assert!(RSASSA_PKCS1_v1_5_SHA384::verify(&pk, b"goodbye", None, &sig).is_err()); @@ -106,7 +106,7 @@ fn pkcs1_v1_5_sha384_round_trips() { #[test] fn pkcs1_v1_5_sha512_round_trips() { let sk = genuine_key(); - let pk = Rsa2048PublicKey::new(sk.n(), 0x10001).unwrap(); + let pk = RSA2048PublicKey::new(sk.n(), 0x10001).unwrap(); let sig = RSASSA_PKCS1_v1_5_SHA512::sign(&sk, b"hello", None).expect("signing must succeed"); RSASSA_PKCS1_v1_5_SHA512::verify(&pk, b"hello", None, &sig).expect("must verify"); assert!(RSASSA_PKCS1_v1_5_SHA512::verify(&pk, b"goodbye", None, &sig).is_err()); @@ -114,7 +114,7 @@ fn pkcs1_v1_5_sha512_round_trips() { fn run_verify_vectors( filename: &str, - verify: impl Fn(&Rsa2048PublicKey, &[u8], &[u8; 256]) -> bool, + verify: impl Fn(&RSA2048PublicKey, &[u8], &[u8; 256]) -> bool, expected_sha: &str, expected_num_tests: usize, expected_num_valid: usize, @@ -132,7 +132,7 @@ fn run_verify_vectors( 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 = Rsa2048PublicKey::new(&n, e).expect("group public key must be valid"); + let pk = RSA2048PublicKey::new(&n, e).expect("group public key must be valid"); for test in group["tests"].as_array().unwrap() { num_tests += 1; @@ -204,9 +204,9 @@ fn rsa_signature_sha512_wycheproof_vectors() { // ---- bouncycastle_core trait conformance ------------------------------------------------------ -fn fixed_keypair() -> Result<(Rsa2048PublicKey, Rsa2048PrivateKey), SignatureError> { +fn fixed_keypair() -> Result<(RSA2048PublicKey, RSA2048PrivateKey), SignatureError> { let sk = genuine_key(); - let pk = Rsa2048PublicKey::new(sk.n(), 0x10001)?; + let pk = RSA2048PublicKey::new(sk.n(), 0x10001)?; Ok((pk, sk)) } @@ -217,8 +217,8 @@ fn fixed_keypair() -> Result<(Rsa2048PublicKey, Rsa2048PrivateKey), SignatureErr fn pkcs1_v1_5_sha384_sha512_trait_conformance_suite() { let framework = TestFrameworkSignature::new(true, false); framework.test_signature::< - Rsa2048PublicKey, - Rsa2048PrivateKey, + RSA2048PublicKey, + RSA2048PrivateKey, RSASSA_PKCS1_v1_5_SHA384, RSASSA_PKCS1_v1_5_SHA384, PK_LEN, @@ -226,8 +226,8 @@ fn pkcs1_v1_5_sha384_sha512_trait_conformance_suite() { SIG_LEN, >(fixed_keypair, false); framework.test_signature::< - Rsa2048PublicKey, - Rsa2048PrivateKey, + RSA2048PublicKey, + RSA2048PrivateKey, RSASSA_PKCS1_v1_5_SHA512, RSASSA_PKCS1_v1_5_SHA512, PK_LEN, diff --git a/crypto/rsa/tests/rsa_2048_pkcs1_v1_5_tests.rs b/crypto/rsa/tests/rsa_2048_pkcs1_v1_5_tests.rs index a16b4df6..78bc53bb 100644 --- a/crypto/rsa/tests/rsa_2048_pkcs1_v1_5_tests.rs +++ b/crypto/rsa/tests/rsa_2048_pkcs1_v1_5_tests.rs @@ -38,7 +38,7 @@ use bouncycastle_core_test_framework::signature::{ }; use bouncycastle_hex::decode as hex_decode; use bouncycastle_rsa::rsa_2048::{ - PK_LEN, RSASSA_PKCS1_v1_5_SHA256, Rsa2048PrivateKey, Rsa2048PublicKey, SIG_LEN, SK_LEN, + PK_LEN, RSA2048PrivateKey, RSA2048PublicKey, RSASSA_PKCS1_v1_5_SHA256, SIG_LEN, SK_LEN, }; use bouncycastle_rsa::rsassa_pkcs1_v1_5; use bouncycastle_sha2::SHA256; @@ -81,7 +81,7 @@ fn limbs_from_hex(hex: &str) -> [u64; L] { limbs } -fn wycheproof_key() -> Rsa2048PrivateKey { +fn wycheproof_key() -> RSA2048PrivateKey { // 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 @@ -117,7 +117,7 @@ fn wycheproof_key() -> Rsa2048PrivateKey { 0xe923e1097c0c562f, 0xc968b48a91c38b5b, 0x933e85179c0320b0, 0x7993d0445f758d51, 0x9bfc042ee0924b1b, 0x41f956d90fa8a793, 0xee7a87b6483a66ee, 0x2640fbfbcfefb163, ]; - Rsa2048PrivateKey::from_crt_components(&p, &q, &d_p, &d_q, &q_inv) + RSA2048PrivateKey::from_crt_components(&p, &q, &d_p, &d_q, &q_inv) .expect("recovered CRT components must be accepted") } @@ -158,9 +158,9 @@ fn pkcs1_v1_5_sig_gen_2048_sha256() { /// 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<(Rsa2048PublicKey, Rsa2048PrivateKey), SignatureError> { +fn fixed_keypair() -> Result<(RSA2048PublicKey, RSA2048PrivateKey), SignatureError> { let sk = wycheproof_key(); - let pk = Rsa2048PublicKey::new(sk.n(), 0x10001)?; + let pk = RSA2048PublicKey::new(sk.n(), 0x10001)?; Ok((pk, sk)) } @@ -172,8 +172,8 @@ fn fixed_keypair() -> Result<(Rsa2048PublicKey, Rsa2048PrivateKey), SignatureErr #[test] fn pkcs1_v1_5_sha256_trait_conformance_suite() { TestFrameworkSignature::new(true, false).test_signature::< - Rsa2048PublicKey, - Rsa2048PrivateKey, + RSA2048PublicKey, + RSA2048PrivateKey, RSASSA_PKCS1_v1_5_SHA256, RSASSA_PKCS1_v1_5_SHA256, PK_LEN, @@ -185,7 +185,7 @@ fn pkcs1_v1_5_sha256_trait_conformance_suite() { #[test] fn key_trait_boundary_conditions() { TestFrameworkSignatureKeys::new() - .test_keys::(fixed_keypair); + .test_keys::(fixed_keypair); } /// Streamed and one-shot signing are one computation: PKCS#1 v1.5 is deterministic, so the @@ -257,7 +257,7 @@ fn rsa_signature_sha256_all_groups() { 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 = Rsa2048PublicKey::new(&n, e).unwrap(); + let pk = RSA2048PublicKey::new(&n, e).unwrap(); for test in group["tests"].as_array().unwrap() { num_tests += 1; diff --git a/crypto/rsa/tests/rsa_2048_pss_sha384_sha512_tests.rs b/crypto/rsa/tests/rsa_2048_pss_sha384_sha512_tests.rs index 1fc199bb..3e61843f 100644 --- a/crypto/rsa/tests/rsa_2048_pss_sha384_sha512_tests.rs +++ b/crypto/rsa/tests/rsa_2048_pss_sha384_sha512_tests.rs @@ -12,7 +12,7 @@ use bouncycastle_core_test_framework::signature::TestFrameworkSignature; use bouncycastle_hex::decode as hex_decode; use bouncycastle_rng::DefaultRNG; use bouncycastle_rsa::rsa_2048::{ - PK_LEN, RSASSA_PSS_SHA384, RSASSA_PSS_SHA512, Rsa2048PrivateKey, Rsa2048PublicKey, SIG_LEN, + PK_LEN, RSA2048PrivateKey, RSA2048PublicKey, RSASSA_PSS_SHA384, RSASSA_PSS_SHA512, SIG_LEN, SK_LEN, }; use serde_json::Value; @@ -63,7 +63,7 @@ fn limbs_from_hex(hex: &str) -> [u64; L] { /// 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() -> Rsa2048PrivateKey { +fn genuine_key() -> RSA2048PrivateKey { let p: [u64; 16] = [ 0x0ea36cfb3a5b18f1, 0x48a6e65332119129, 0x110ad9e7b48a1c93, 0x569156b90113e2e9, 0xe79813a575cfad9c, 0x69d659d143ec6f17, 0xe81e6bab5ddaa783, 0xbff1c5b80a69f788, @@ -94,14 +94,14 @@ fn genuine_key() -> Rsa2048PrivateKey { 0xe923e1097c0c562f, 0xc968b48a91c38b5b, 0x933e85179c0320b0, 0x7993d0445f758d51, 0x9bfc042ee0924b1b, 0x41f956d90fa8a793, 0xee7a87b6483a66ee, 0x2640fbfbcfefb163, ]; - Rsa2048PrivateKey::from_crt_components(&p, &q, &d_p, &d_q, &q_inv) + RSA2048PrivateKey::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 = Rsa2048PublicKey::new(sk.n(), 0x10001).unwrap(); + let pk = RSA2048PublicKey::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"); @@ -112,7 +112,7 @@ fn pss_sha384_fixed_salt_round_trips() { #[test] fn pss_sha384_rng_produces_fresh_salts_that_both_verify() { let sk = genuine_key(); - let pk = Rsa2048PublicKey::new(sk.n(), 0x10001).unwrap(); + let pk = RSA2048PublicKey::new(sk.n(), 0x10001).unwrap(); let mut rng = DefaultRNG::default(); let sig_a = RSASSA_PSS_SHA384::sign_randomized(&sk, b"hello", &mut rng).expect("signing must succeed"); @@ -126,7 +126,7 @@ fn pss_sha384_rng_produces_fresh_salts_that_both_verify() { #[test] fn pss_sha512_fixed_salt_round_trips() { let sk = genuine_key(); - let pk = Rsa2048PublicKey::new(sk.n(), 0x10001).unwrap(); + let pk = RSA2048PublicKey::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"); @@ -137,7 +137,7 @@ fn pss_sha512_fixed_salt_round_trips() { #[test] fn pss_sha512_rng_produces_fresh_salts_that_both_verify() { let sk = genuine_key(); - let pk = Rsa2048PublicKey::new(sk.n(), 0x10001).unwrap(); + let pk = RSA2048PublicKey::new(sk.n(), 0x10001).unwrap(); let mut rng = DefaultRNG::default(); let sig_a = RSASSA_PSS_SHA512::sign_randomized(&sk, b"hello", &mut rng).expect("signing must succeed"); @@ -164,7 +164,7 @@ fn rsa_pss_sha384_mgf1_48_wycheproof_vectors() { 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 = Rsa2048PublicKey::new(&n, e).expect("group public key must be valid"); + let pk = RSA2048PublicKey::new(&n, e).expect("group public key must be valid"); for test in group["tests"].as_array().unwrap() { num_tests += 1; @@ -200,9 +200,9 @@ fn rsa_pss_sha384_mgf1_48_wycheproof_vectors() { // ---- bouncycastle_core trait conformance ------------------------------------------------------ -fn fixed_keypair() -> Result<(Rsa2048PublicKey, Rsa2048PrivateKey), SignatureError> { +fn fixed_keypair() -> Result<(RSA2048PublicKey, RSA2048PrivateKey), SignatureError> { let sk = genuine_key(); - let pk = Rsa2048PublicKey::new(sk.n(), 0x10001)?; + let pk = RSA2048PublicKey::new(sk.n(), 0x10001)?; Ok((pk, sk)) } @@ -212,8 +212,8 @@ fn fixed_keypair() -> Result<(Rsa2048PublicKey, Rsa2048PrivateKey), SignatureErr fn pss_sha384_sha512_trait_conformance_suite() { let framework = TestFrameworkSignature::new(false, false); framework.test_signature::< - Rsa2048PublicKey, - Rsa2048PrivateKey, + RSA2048PublicKey, + RSA2048PrivateKey, RSASSA_PSS_SHA384, RSASSA_PSS_SHA384, PK_LEN, @@ -221,8 +221,8 @@ fn pss_sha384_sha512_trait_conformance_suite() { SIG_LEN, >(fixed_keypair, false); framework.test_signature::< - Rsa2048PublicKey, - Rsa2048PrivateKey, + RSA2048PublicKey, + RSA2048PrivateKey, RSASSA_PSS_SHA512, RSASSA_PSS_SHA512, PK_LEN, diff --git a/crypto/rsa/tests/rsa_2048_pss_shake128_tests.rs b/crypto/rsa/tests/rsa_2048_pss_shake128_tests.rs index 4bac4edc..32d582e6 100644 --- a/crypto/rsa/tests/rsa_2048_pss_shake128_tests.rs +++ b/crypto/rsa/tests/rsa_2048_pss_shake128_tests.rs @@ -11,7 +11,7 @@ use bouncycastle_core_test_framework::signature::TestFrameworkSignature; use bouncycastle_hex::decode as hex_decode; use bouncycastle_rng::DefaultRNG; use bouncycastle_rsa::rsa_2048::{ - PK_LEN, RSASSA_PSS_SHAKE128, Rsa2048PrivateKey, Rsa2048PublicKey, SIG_LEN, SK_LEN, + PK_LEN, RSA2048PrivateKey, RSA2048PublicKey, RSASSA_PSS_SHAKE128, SIG_LEN, SK_LEN, }; use bouncycastle_rsa::rsassa_pss_shake; use bouncycastle_sha3::SHAKE128; @@ -64,7 +64,7 @@ fn limbs_from_hex(hex: &str) -> [u64; L] { /// 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() -> Rsa2048PrivateKey { +fn genuine_key() -> RSA2048PrivateKey { let p: [u64; 16] = [ 0x0ea36cfb3a5b18f1, 0x48a6e65332119129, 0x110ad9e7b48a1c93, 0x569156b90113e2e9, 0xe79813a575cfad9c, 0x69d659d143ec6f17, 0xe81e6bab5ddaa783, 0xbff1c5b80a69f788, @@ -95,14 +95,14 @@ fn genuine_key() -> Rsa2048PrivateKey { 0xe923e1097c0c562f, 0xc968b48a91c38b5b, 0x933e85179c0320b0, 0x7993d0445f758d51, 0x9bfc042ee0924b1b, 0x41f956d90fa8a793, 0xee7a87b6483a66ee, 0x2640fbfbcfefb163, ]; - Rsa2048PrivateKey::from_crt_components(&p, &q, &d_p, &d_q, &q_inv) + RSA2048PrivateKey::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 = Rsa2048PublicKey::new(sk.n(), 0x10001).unwrap(); + let pk = RSA2048PublicKey::new(sk.n(), 0x10001).unwrap(); let salt = [0x42u8; 32]; let sig = sign_with_salt!(RSASSA_PSS_SHAKE128, &sk, b"the message to sign", salt) @@ -119,7 +119,7 @@ fn pss_shake128_sign_with_fixed_salt_round_trips() { #[test] fn pss_shake128_sign_with_rng_produces_fresh_salts_that_both_verify() { let sk = genuine_key(); - let pk = Rsa2048PublicKey::new(sk.n(), 0x10001).unwrap(); + let pk = RSA2048PublicKey::new(sk.n(), 0x10001).unwrap(); let mut rng = DefaultRNG::default(); let sig_a = RSASSA_PSS_SHAKE128::sign_randomized(&sk, b"hello", &mut rng) @@ -147,7 +147,7 @@ fn rsa_pss_2048_shake128_wycheproof_vectors() { 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 = Rsa2048PublicKey::new(&n, e).expect("group public key must be valid"); + let pk = RSA2048PublicKey::new(&n, e).expect("group public key must be valid"); for test in group["tests"].as_array().unwrap() { num_tests += 1; @@ -183,9 +183,9 @@ fn rsa_pss_2048_shake128_wycheproof_vectors() { // ---- bouncycastle_core trait conformance ------------------------------------------------------ -fn fixed_keypair() -> Result<(Rsa2048PublicKey, Rsa2048PrivateKey), SignatureError> { +fn fixed_keypair() -> Result<(RSA2048PublicKey, RSA2048PrivateKey), SignatureError> { let sk = genuine_key(); - let pk = Rsa2048PublicKey::new(sk.n(), 0x10001)?; + let pk = RSA2048PublicKey::new(sk.n(), 0x10001)?; Ok((pk, sk)) } @@ -195,8 +195,8 @@ fn fixed_keypair() -> Result<(Rsa2048PublicKey, Rsa2048PrivateKey), SignatureErr #[test] fn pss_shake128_trait_conformance_suite() { TestFrameworkSignature::new(false, false).test_signature::< - Rsa2048PublicKey, - Rsa2048PrivateKey, + RSA2048PublicKey, + RSA2048PrivateKey, RSASSA_PSS_SHAKE128, RSASSA_PSS_SHAKE128, PK_LEN, diff --git a/crypto/rsa/tests/rsa_2048_pss_tests.rs b/crypto/rsa/tests/rsa_2048_pss_tests.rs index afe1be0a..a55375f4 100644 --- a/crypto/rsa/tests/rsa_2048_pss_tests.rs +++ b/crypto/rsa/tests/rsa_2048_pss_tests.rs @@ -16,7 +16,7 @@ use bouncycastle_core_test_framework::signature::TestFrameworkSignature; use bouncycastle_hex::decode as hex_decode; use bouncycastle_rng::DefaultRNG; use bouncycastle_rsa::rsa_2048::{ - PK_LEN, RSASSA_PSS_SHA256, Rsa2048PrivateKey, Rsa2048PublicKey, SIG_LEN, SK_LEN, + PK_LEN, RSA2048PrivateKey, RSA2048PublicKey, RSASSA_PSS_SHA256, SIG_LEN, SK_LEN, }; use bouncycastle_rsa::rsassa_pss; use bouncycastle_sha2::SHA256; @@ -69,7 +69,7 @@ fn limbs_from_hex(hex: &str) -> [u64; L] { /// 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() -> Rsa2048PrivateKey { +fn wycheproof_key() -> RSA2048PrivateKey { let p: [u64; 16] = [ 0x0ea36cfb3a5b18f1, 0x48a6e65332119129, 0x110ad9e7b48a1c93, 0x569156b90113e2e9, 0xe79813a575cfad9c, 0x69d659d143ec6f17, 0xe81e6bab5ddaa783, 0xbff1c5b80a69f788, @@ -100,14 +100,14 @@ fn wycheproof_key() -> Rsa2048PrivateKey { 0xe923e1097c0c562f, 0xc968b48a91c38b5b, 0x933e85179c0320b0, 0x7993d0445f758d51, 0x9bfc042ee0924b1b, 0x41f956d90fa8a793, 0xee7a87b6483a66ee, 0x2640fbfbcfefb163, ]; - Rsa2048PrivateKey::from_crt_components(&p, &q, &d_p, &d_q, &q_inv) + RSA2048PrivateKey::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 = Rsa2048PublicKey::new(sk.n(), 0x10001).unwrap(); + let pk = RSA2048PublicKey::new(sk.n(), 0x10001).unwrap(); let salt = [0x42u8; 32]; let sig = sign_with_salt!(RSASSA_PSS_SHA256, &sk, b"the message to sign", salt) @@ -124,7 +124,7 @@ fn pss_sign_with_fixed_salt_round_trips() { #[test] fn pss_sign_with_rng_produces_fresh_salts_that_both_verify() { let sk = wycheproof_key(); - let pk = Rsa2048PublicKey::new(sk.n(), 0x10001).unwrap(); + let pk = RSA2048PublicKey::new(sk.n(), 0x10001).unwrap(); let mut rng = DefaultRNG::default(); let sig_a = @@ -152,7 +152,7 @@ fn rsa_pss_sha256_mgf1_32_wycheproof_vectors() { 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 = Rsa2048PublicKey::new(&n, e).expect("group public key must be valid"); + let pk = RSA2048PublicKey::new(&n, e).expect("group public key must be valid"); for test in group["tests"].as_array().unwrap() { num_tests += 1; @@ -188,9 +188,9 @@ fn rsa_pss_sha256_mgf1_32_wycheproof_vectors() { // ---- bouncycastle_core trait conformance ------------------------------------------------------ -fn fixed_keypair() -> Result<(Rsa2048PublicKey, Rsa2048PrivateKey), SignatureError> { +fn fixed_keypair() -> Result<(RSA2048PublicKey, RSA2048PrivateKey), SignatureError> { let sk = wycheproof_key(); - let pk = Rsa2048PublicKey::new(sk.n(), 0x10001)?; + let pk = RSA2048PublicKey::new(sk.n(), 0x10001)?; Ok((pk, sk)) } @@ -200,8 +200,8 @@ fn fixed_keypair() -> Result<(Rsa2048PublicKey, Rsa2048PrivateKey), SignatureErr #[test] fn pss_sha256_trait_conformance_suite() { TestFrameworkSignature::new(false, false).test_signature::< - Rsa2048PublicKey, - Rsa2048PrivateKey, + RSA2048PublicKey, + RSA2048PrivateKey, RSASSA_PSS_SHA256, RSASSA_PSS_SHA256, PK_LEN, diff --git a/crypto/rsa/tests/rsa_3072_pss_shake128_tests.rs b/crypto/rsa/tests/rsa_3072_pss_shake128_tests.rs index 8ad96a0c..5bf0b754 100644 --- a/crypto/rsa/tests/rsa_3072_pss_shake128_tests.rs +++ b/crypto/rsa/tests/rsa_3072_pss_shake128_tests.rs @@ -9,7 +9,7 @@ use bouncycastle_core_test_framework::signature::TestFrameworkSignature; use bouncycastle_hex::decode as hex_decode; use bouncycastle_rng::DefaultRNG; use bouncycastle_rsa::rsa_3072::{ - PK_LEN, RSASSA_PSS_SHAKE128, Rsa3072PrivateKey, Rsa3072PublicKey, SIG_LEN, SK_LEN, + PK_LEN, RSA3072PrivateKey, RSA3072PublicKey, RSASSA_PSS_SHAKE128, SIG_LEN, SK_LEN, }; use serde_json::Value; use std::fs; @@ -60,7 +60,7 @@ fn limbs_from_hex(hex: &str) -> [u64; L] { /// 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() -> Rsa3072PrivateKey { +fn genuine_key() -> RSA3072PrivateKey { let p: [u64; 24] = [ 0xb26d973345bc4c5f, 0x23251a1d29962ca9, 0x554fc3f23d6c9046, 0x89ffe73b1401e9b8, 0xe0b448b454670aca, 0xa73ea5c2413d1da2, 0xe9539bc7a8d3b351, 0x357984fc116af9cb, @@ -101,14 +101,14 @@ fn genuine_key() -> Rsa3072PrivateKey { 0xfe6c3600d9b8e9a9, 0x744fac4daabf5488, 0xfbee6ec24b75fbf0, 0x8be552c8be44f139, 0xfb0da96bd423759d, 0xb3443d93e7e8ca62, 0x36fe01b950885ecd, 0x214a1f73130e48b3, ]; - Rsa3072PrivateKey::from_crt_components(&p, &q, &d_p, &d_q, &q_inv) + RSA3072PrivateKey::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 = Rsa3072PublicKey::new(sk.n(), 0x10001).unwrap(); + let pk = RSA3072PublicKey::new(sk.n(), 0x10001).unwrap(); let salt = [0x42u8; 32]; let sig = sign_with_salt!(RSASSA_PSS_SHAKE128, &sk, b"the message to sign", salt) @@ -124,7 +124,7 @@ fn pss_shake128_sign_with_fixed_salt_round_trips() { #[test] fn pss_shake128_sign_with_rng_produces_fresh_salts_that_both_verify() { let sk = genuine_key(); - let pk = Rsa3072PublicKey::new(sk.n(), 0x10001).unwrap(); + let pk = RSA3072PublicKey::new(sk.n(), 0x10001).unwrap(); let mut rng = DefaultRNG::default(); let sig_a = RSASSA_PSS_SHAKE128::sign_randomized(&sk, b"hello", &mut rng) @@ -152,7 +152,7 @@ fn rsa_pss_3072_shake128_wycheproof_vectors() { 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 = Rsa3072PublicKey::new(&n, e).expect("group public key must be valid"); + let pk = RSA3072PublicKey::new(&n, e).expect("group public key must be valid"); for test in group["tests"].as_array().unwrap() { num_tests += 1; @@ -188,17 +188,17 @@ fn rsa_pss_3072_shake128_wycheproof_vectors() { // ---- bouncycastle_core trait conformance ------------------------------------------------------ -fn fixed_keypair() -> Result<(Rsa3072PublicKey, Rsa3072PrivateKey), SignatureError> { +fn fixed_keypair() -> Result<(RSA3072PublicKey, RSA3072PrivateKey), SignatureError> { let sk = genuine_key(); - let pk = Rsa3072PublicKey::new(sk.n(), 0x10001)?; + let pk = RSA3072PublicKey::new(sk.n(), 0x10001)?; Ok((pk, sk)) } #[test] fn pss_shake128_trait_conformance_suite() { TestFrameworkSignature::new(false, false).test_signature::< - Rsa3072PublicKey, - Rsa3072PrivateKey, + RSA3072PublicKey, + RSA3072PrivateKey, RSASSA_PSS_SHAKE128, RSASSA_PSS_SHAKE128, PK_LEN, diff --git a/crypto/rsa/tests/rsa_3072_tests.rs b/crypto/rsa/tests/rsa_3072_tests.rs index 0106303d..92ca507f 100644 --- a/crypto/rsa/tests/rsa_3072_tests.rs +++ b/crypto/rsa/tests/rsa_3072_tests.rs @@ -18,9 +18,9 @@ use bouncycastle_core_test_framework::signature::{ use bouncycastle_hex::decode as hex_decode; use bouncycastle_rng::DefaultRNG; 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, Rsa3072PrivateKey, Rsa3072PublicKey, - SIG_LEN, SK_LEN, + PK_LEN, RSA3072PrivateKey, RSA3072PublicKey, 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; @@ -68,7 +68,7 @@ fn limbs_from_hex(hex: &str) -> [u64; L] { limbs } -fn genuine_key() -> Rsa3072PrivateKey { +fn genuine_key() -> RSA3072PrivateKey { let p: [u64; 24] = [ 0xb26d973345bc4c5f, 0x23251a1d29962ca9, 0x554fc3f23d6c9046, 0x89ffe73b1401e9b8, 0xe0b448b454670aca, 0xa73ea5c2413d1da2, 0xe9539bc7a8d3b351, 0x357984fc116af9cb, @@ -109,7 +109,7 @@ fn genuine_key() -> Rsa3072PrivateKey { 0xfe6c3600d9b8e9a9, 0x744fac4daabf5488, 0xfbee6ec24b75fbf0, 0x8be552c8be44f139, 0xfb0da96bd423759d, 0xb3443d93e7e8ca62, 0x36fe01b950885ecd, 0x214a1f73130e48b3, ]; - Rsa3072PrivateKey::from_crt_components(&p, &q, &d_p, &d_q, &q_inv) + RSA3072PrivateKey::from_crt_components(&p, &q, &d_p, &d_q, &q_inv) .expect("recovered CRT components must be accepted") } @@ -142,7 +142,7 @@ fn pkcs1_v1_5_sig_gen_3072_sha256() { #[test] fn pkcs1_v1_5_sha384_and_sha512_round_trip() { let sk = genuine_key(); - let pk = Rsa3072PublicKey::new(sk.n(), 0x10001).unwrap(); + let pk = RSA3072PublicKey::new(sk.n(), 0x10001).unwrap(); let sig384 = RSASSA_PKCS1_v1_5_SHA384::sign(&sk, b"hello", None).unwrap(); RSASSA_PKCS1_v1_5_SHA384::verify(&pk, b"hello", None, &sig384).unwrap(); let sig512 = RSASSA_PKCS1_v1_5_SHA512::sign(&sk, b"hello", None).unwrap(); @@ -160,7 +160,7 @@ fn pkcs1_v1_5_sha384_and_sha512_round_trip() { #[test] fn pss_sha256_fixed_salt_round_trips() { let sk = genuine_key(); - let pk = Rsa3072PublicKey::new(sk.n(), 0x10001).unwrap(); + let pk = RSA3072PublicKey::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"); @@ -171,7 +171,7 @@ fn pss_sha256_fixed_salt_round_trips() { #[test] fn pss_sha256_rng_produces_fresh_salts_that_both_verify() { let sk = genuine_key(); - let pk = Rsa3072PublicKey::new(sk.n(), 0x10001).unwrap(); + let pk = RSA3072PublicKey::new(sk.n(), 0x10001).unwrap(); let mut rng = DefaultRNG::default(); let sig_a = RSASSA_PSS_SHA256::sign_randomized(&sk, b"hello", &mut rng).expect("signing must succeed"); @@ -185,7 +185,7 @@ fn pss_sha256_rng_produces_fresh_salts_that_both_verify() { #[test] fn pss_sha384_fixed_salt_round_trips() { let sk = genuine_key(); - let pk = Rsa3072PublicKey::new(sk.n(), 0x10001).unwrap(); + let pk = RSA3072PublicKey::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"); @@ -196,7 +196,7 @@ fn pss_sha384_fixed_salt_round_trips() { #[test] fn pss_sha384_rng_produces_fresh_salts_that_both_verify() { let sk = genuine_key(); - let pk = Rsa3072PublicKey::new(sk.n(), 0x10001).unwrap(); + let pk = RSA3072PublicKey::new(sk.n(), 0x10001).unwrap(); let mut rng = DefaultRNG::default(); let sig_a = RSASSA_PSS_SHA384::sign_randomized(&sk, b"hello", &mut rng).expect("signing must succeed"); @@ -210,7 +210,7 @@ fn pss_sha384_rng_produces_fresh_salts_that_both_verify() { #[test] fn pss_sha512_fixed_salt_round_trips() { let sk = genuine_key(); - let pk = Rsa3072PublicKey::new(sk.n(), 0x10001).unwrap(); + let pk = RSA3072PublicKey::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"); @@ -221,7 +221,7 @@ fn pss_sha512_fixed_salt_round_trips() { #[test] fn pss_sha512_rng_produces_fresh_salts_that_both_verify() { let sk = genuine_key(); - let pk = Rsa3072PublicKey::new(sk.n(), 0x10001).unwrap(); + let pk = RSA3072PublicKey::new(sk.n(), 0x10001).unwrap(); let mut rng = DefaultRNG::default(); let sig_a = RSASSA_PSS_SHA512::sign_randomized(&sk, b"hello", &mut rng).expect("signing must succeed"); @@ -234,7 +234,7 @@ fn pss_sha512_rng_produces_fresh_salts_that_both_verify() { fn run_pkcs1_v1_5_verify_vectors( filename: &str, - verify: impl Fn(&Rsa3072PublicKey, &[u8], &[u8; 384]) -> bool, + verify: impl Fn(&RSA3072PublicKey, &[u8], &[u8; 384]) -> bool, expected_sha: &str, expected_valid: usize, expected_invalid: usize, @@ -249,7 +249,7 @@ fn run_pkcs1_v1_5_verify_vectors( 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 = Rsa3072PublicKey::new(&n, e).unwrap(); + let pk = RSA3072PublicKey::new(&n, e).unwrap(); for test in group["tests"].as_array().unwrap() { let tc_id = test["tcId"].as_u64().unwrap(); @@ -341,7 +341,7 @@ fn rsa_pss_3072_sha256_mgf1_32_wycheproof_vectors() { 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 = Rsa3072PublicKey::new(&n, e).unwrap(); + let pk = RSA3072PublicKey::new(&n, e).unwrap(); for test in group["tests"].as_array().unwrap() { let tc_id = test["tcId"].as_u64().unwrap(); @@ -372,9 +372,9 @@ fn rsa_pss_3072_sha256_mgf1_32_wycheproof_vectors() { // ---- bouncycastle_core trait conformance ------------------------------------------------------ -fn fixed_keypair() -> Result<(Rsa3072PublicKey, Rsa3072PrivateKey), SignatureError> { +fn fixed_keypair() -> Result<(RSA3072PublicKey, RSA3072PrivateKey), SignatureError> { let sk = genuine_key(); - let pk = Rsa3072PublicKey::new(sk.n(), 0x10001)?; + let pk = RSA3072PublicKey::new(sk.n(), 0x10001)?; Ok((pk, sk)) } @@ -384,8 +384,8 @@ fn fixed_keypair() -> Result<(Rsa3072PublicKey, Rsa3072PrivateKey), SignatureErr fn pkcs1_v1_5_trait_conformance_suites() { let framework = TestFrameworkSignature::new(true, false); framework.test_signature::< - Rsa3072PublicKey, - Rsa3072PrivateKey, + RSA3072PublicKey, + RSA3072PrivateKey, RSASSA_PKCS1_v1_5_SHA256, RSASSA_PKCS1_v1_5_SHA256, PK_LEN, @@ -393,8 +393,8 @@ fn pkcs1_v1_5_trait_conformance_suites() { SIG_LEN, >(fixed_keypair, false); framework.test_signature::< - Rsa3072PublicKey, - Rsa3072PrivateKey, + RSA3072PublicKey, + RSA3072PrivateKey, RSASSA_PKCS1_v1_5_SHA384, RSASSA_PKCS1_v1_5_SHA384, PK_LEN, @@ -402,8 +402,8 @@ fn pkcs1_v1_5_trait_conformance_suites() { SIG_LEN, >(fixed_keypair, false); framework.test_signature::< - Rsa3072PublicKey, - Rsa3072PrivateKey, + RSA3072PublicKey, + RSA3072PrivateKey, RSASSA_PKCS1_v1_5_SHA512, RSASSA_PKCS1_v1_5_SHA512, PK_LEN, @@ -416,8 +416,8 @@ fn pkcs1_v1_5_trait_conformance_suites() { fn pss_trait_conformance_suites() { let framework = TestFrameworkSignature::new(false, false); framework.test_signature::< - Rsa3072PublicKey, - Rsa3072PrivateKey, + RSA3072PublicKey, + RSA3072PrivateKey, RSASSA_PSS_SHA256, RSASSA_PSS_SHA256, PK_LEN, @@ -425,8 +425,8 @@ fn pss_trait_conformance_suites() { SIG_LEN, >(fixed_keypair, false); framework.test_signature::< - Rsa3072PublicKey, - Rsa3072PrivateKey, + RSA3072PublicKey, + RSA3072PrivateKey, RSASSA_PSS_SHA384, RSASSA_PSS_SHA384, PK_LEN, @@ -434,8 +434,8 @@ fn pss_trait_conformance_suites() { SIG_LEN, >(fixed_keypair, false); framework.test_signature::< - Rsa3072PublicKey, - Rsa3072PrivateKey, + RSA3072PublicKey, + RSA3072PrivateKey, RSASSA_PSS_SHA512, RSASSA_PSS_SHA512, PK_LEN, @@ -447,5 +447,5 @@ fn pss_trait_conformance_suites() { #[test] fn key_trait_boundary_conditions() { TestFrameworkSignatureKeys::new() - .test_keys::(fixed_keypair); + .test_keys::(fixed_keypair); } diff --git a/crypto/rsa/tests/rsa_4096_pss_shake256_tests.rs b/crypto/rsa/tests/rsa_4096_pss_shake256_tests.rs index 0270d366..bc847896 100644 --- a/crypto/rsa/tests/rsa_4096_pss_shake256_tests.rs +++ b/crypto/rsa/tests/rsa_4096_pss_shake256_tests.rs @@ -6,7 +6,7 @@ use bouncycastle_core::traits::{SignatureVerifier, Signer}; use bouncycastle_hex::decode as hex_decode; use bouncycastle_rng::DefaultRNG; -use bouncycastle_rsa::rsa_4096::{RSASSA_PSS_SHAKE256, Rsa4096PrivateKey, Rsa4096PublicKey}; +use bouncycastle_rsa::rsa_4096::{RSA4096PrivateKey, RSA4096PublicKey, RSASSA_PSS_SHAKE256}; use serde_json::Value; use std::fs; use std::path::Path; @@ -56,7 +56,7 @@ fn limbs_from_hex(hex: &str) -> [u64; L] { /// 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() -> Rsa4096PrivateKey { +fn genuine_key() -> RSA4096PrivateKey { let p: [u64; 32] = [ 0x5141acd4afd4771f, 0x5857742b7e4032dc, 0xb7a9b97fe5371396, 0x4b1783c5bc91a6dc, 0xaf5d0c912d97b728, 0xeb265a7f28b88976, 0x5e993302aa72f11d, 0xc007ad09d76ae22a, @@ -107,14 +107,14 @@ fn genuine_key() -> Rsa4096PrivateKey { 0x748d7b5d94cacd4d, 0xcf634f3a07cea4b7, 0x8dbcca51f4da4379, 0x80774236a54ec9dc, 0x6a1ef00ee582d3d1, 0xdecfb14ca1e80c8e, 0xc78af5f6c807cc99, 0x484ad86e79415ea3, ]; - Rsa4096PrivateKey::from_crt_components(&p, &q, &d_p, &d_q, &q_inv) + RSA4096PrivateKey::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 = Rsa4096PublicKey::new(sk.n(), 0x10001).unwrap(); + let pk = RSA4096PublicKey::new(sk.n(), 0x10001).unwrap(); let salt = [0x42u8; 64]; let sig = sign_with_salt!(RSASSA_PSS_SHAKE256, &sk, b"the message to sign", salt) @@ -130,7 +130,7 @@ fn pss_shake256_sign_with_fixed_salt_round_trips() { #[test] fn pss_shake256_sign_with_rng_produces_fresh_salts_that_both_verify() { let sk = genuine_key(); - let pk = Rsa4096PublicKey::new(sk.n(), 0x10001).unwrap(); + let pk = RSA4096PublicKey::new(sk.n(), 0x10001).unwrap(); let mut rng = DefaultRNG::default(); let sig_a = RSASSA_PSS_SHAKE256::sign_randomized(&sk, b"hello", &mut rng) @@ -158,7 +158,7 @@ fn rsa_pss_4096_shake256_wycheproof_vectors() { 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 = Rsa4096PublicKey::new(&n, e).expect("group public key must be valid"); + let pk = RSA4096PublicKey::new(&n, e).expect("group public key must be valid"); for test in group["tests"].as_array().unwrap() { num_tests += 1; @@ -200,7 +200,7 @@ fn rsa_pss_4096_shake256_wycheproof_vectors() { #[test] fn pss_shake256_trait_round_trips() { let sk = genuine_key(); - let pk = Rsa4096PublicKey::new(sk.n(), 0x10001).unwrap(); + let pk = RSA4096PublicKey::new(sk.n(), 0x10001).unwrap(); let msg = b"PSS-SHAKE256 at RSA-4096, both APIs"; let from_trait = RSASSA_PSS_SHAKE256::sign(&sk, msg, None).unwrap(); RSASSA_PSS_SHAKE256::verify(&pk, msg, None, &from_trait).unwrap(); diff --git a/crypto/rsa/tests/rsa_4096_tests.rs b/crypto/rsa/tests/rsa_4096_tests.rs index dffb66be..475b9dce 100644 --- a/crypto/rsa/tests/rsa_4096_tests.rs +++ b/crypto/rsa/tests/rsa_4096_tests.rs @@ -19,9 +19,9 @@ use bouncycastle_core_test_framework::signature::{ use bouncycastle_hex::decode as hex_decode; use bouncycastle_rng::DefaultRNG; 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, Rsa4096PrivateKey, Rsa4096PublicKey, - SIG_LEN, SK_LEN, + PK_LEN, RSA4096PrivateKey, RSA4096PublicKey, 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; @@ -69,7 +69,7 @@ fn limbs_from_hex(hex: &str) -> [u64; L] { limbs } -fn genuine_key() -> Rsa4096PrivateKey { +fn genuine_key() -> RSA4096PrivateKey { let p: [u64; 32] = [ 0x5141acd4afd4771f, 0x5857742b7e4032dc, 0xb7a9b97fe5371396, 0x4b1783c5bc91a6dc, 0xaf5d0c912d97b728, 0xeb265a7f28b88976, 0x5e993302aa72f11d, 0xc007ad09d76ae22a, @@ -120,7 +120,7 @@ fn genuine_key() -> Rsa4096PrivateKey { 0x748d7b5d94cacd4d, 0xcf634f3a07cea4b7, 0x8dbcca51f4da4379, 0x80774236a54ec9dc, 0x6a1ef00ee582d3d1, 0xdecfb14ca1e80c8e, 0xc78af5f6c807cc99, 0x484ad86e79415ea3, ]; - Rsa4096PrivateKey::from_crt_components(&p, &q, &d_p, &d_q, &q_inv) + RSA4096PrivateKey::from_crt_components(&p, &q, &d_p, &d_q, &q_inv) .expect("recovered CRT components must be accepted") } @@ -157,7 +157,7 @@ fn pkcs1_v1_5_sig_gen_4096_sha256() { #[test] fn pkcs1_v1_5_sha384_and_sha512_round_trip() { let sk = genuine_key(); - let pk = Rsa4096PublicKey::new(sk.n(), 0x10001).unwrap(); + let pk = RSA4096PublicKey::new(sk.n(), 0x10001).unwrap(); let sig384 = RSASSA_PKCS1_v1_5_SHA384::sign(&sk, b"hello", None).unwrap(); RSASSA_PKCS1_v1_5_SHA384::verify(&pk, b"hello", None, &sig384).unwrap(); let sig512 = RSASSA_PKCS1_v1_5_SHA512::sign(&sk, b"hello", None).unwrap(); @@ -166,7 +166,7 @@ fn pkcs1_v1_5_sha384_and_sha512_round_trip() { fn run_pkcs1_v1_5_verify_vectors( filename: &str, - verify: impl Fn(&Rsa4096PublicKey, &[u8], &[u8; 512]) -> bool, + verify: impl Fn(&RSA4096PublicKey, &[u8], &[u8; 512]) -> bool, expected_sha: &str, expected_valid: usize, expected_invalid: usize, @@ -181,7 +181,7 @@ fn run_pkcs1_v1_5_verify_vectors( 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 = Rsa4096PublicKey::new(&n, e).unwrap(); + let pk = RSA4096PublicKey::new(&n, e).unwrap(); for test in group["tests"].as_array().unwrap() { let tc_id = test["tcId"].as_u64().unwrap(); @@ -254,7 +254,7 @@ fn rsa_signature_4096_sha512_wycheproof_vectors() { fn run_pss_verify_vectors( filename: &str, - verify: impl Fn(&Rsa4096PublicKey, &[u8], &[u8; 512]) -> bool, + verify: impl Fn(&RSA4096PublicKey, &[u8], &[u8; 512]) -> bool, expected_sha: &str, expected_slen: u64, expected_valid: usize, @@ -271,7 +271,7 @@ fn run_pss_verify_vectors( 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 = Rsa4096PublicKey::new(&n, e).unwrap(); + let pk = RSA4096PublicKey::new(&n, e).unwrap(); for test in group["tests"].as_array().unwrap() { let tc_id = test["tcId"].as_u64().unwrap(); @@ -345,7 +345,7 @@ fn rsa_pss_4096_sha512_mgf1_64_wycheproof_vectors() { #[test] fn pss_sha256_fixed_salt_round_trips() { let sk = genuine_key(); - let pk = Rsa4096PublicKey::new(sk.n(), 0x10001).unwrap(); + let pk = RSA4096PublicKey::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"); @@ -356,7 +356,7 @@ fn pss_sha256_fixed_salt_round_trips() { #[test] fn pss_sha256_rng_produces_fresh_salts_that_both_verify() { let sk = genuine_key(); - let pk = Rsa4096PublicKey::new(sk.n(), 0x10001).unwrap(); + let pk = RSA4096PublicKey::new(sk.n(), 0x10001).unwrap(); let mut rng = DefaultRNG::default(); let sig_a = RSASSA_PSS_SHA256::sign_randomized(&sk, b"hello", &mut rng).expect("signing must succeed"); @@ -370,7 +370,7 @@ fn pss_sha256_rng_produces_fresh_salts_that_both_verify() { #[test] fn pss_sha384_fixed_salt_round_trips() { let sk = genuine_key(); - let pk = Rsa4096PublicKey::new(sk.n(), 0x10001).unwrap(); + let pk = RSA4096PublicKey::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"); @@ -381,7 +381,7 @@ fn pss_sha384_fixed_salt_round_trips() { #[test] fn pss_sha384_rng_produces_fresh_salts_that_both_verify() { let sk = genuine_key(); - let pk = Rsa4096PublicKey::new(sk.n(), 0x10001).unwrap(); + let pk = RSA4096PublicKey::new(sk.n(), 0x10001).unwrap(); let mut rng = DefaultRNG::default(); let sig_a = RSASSA_PSS_SHA384::sign_randomized(&sk, b"hello", &mut rng).expect("signing must succeed"); @@ -395,7 +395,7 @@ fn pss_sha384_rng_produces_fresh_salts_that_both_verify() { #[test] fn pss_sha512_fixed_salt_round_trips() { let sk = genuine_key(); - let pk = Rsa4096PublicKey::new(sk.n(), 0x10001).unwrap(); + let pk = RSA4096PublicKey::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"); @@ -406,7 +406,7 @@ fn pss_sha512_fixed_salt_round_trips() { #[test] fn pss_sha512_rng_produces_fresh_salts_that_both_verify() { let sk = genuine_key(); - let pk = Rsa4096PublicKey::new(sk.n(), 0x10001).unwrap(); + let pk = RSA4096PublicKey::new(sk.n(), 0x10001).unwrap(); let mut rng = DefaultRNG::default(); let sig_a = RSASSA_PSS_SHA512::sign_randomized(&sk, b"hello", &mut rng).expect("signing must succeed"); @@ -419,9 +419,9 @@ fn pss_sha512_rng_produces_fresh_salts_that_both_verify() { // ---- bouncycastle_core trait conformance ------------------------------------------------------ -fn fixed_keypair() -> Result<(Rsa4096PublicKey, Rsa4096PrivateKey), SignatureError> { +fn fixed_keypair() -> Result<(RSA4096PublicKey, RSA4096PrivateKey), SignatureError> { let sk = genuine_key(); - let pk = Rsa4096PublicKey::new(sk.n(), 0x10001)?; + let pk = RSA4096PublicKey::new(sk.n(), 0x10001)?; Ok((pk, sk)) } @@ -433,8 +433,8 @@ fn fixed_keypair() -> Result<(Rsa4096PublicKey, Rsa4096PrivateKey), SignatureErr #[test] fn sha256_trait_conformance_suites() { TestFrameworkSignature::new(true, false).test_signature::< - Rsa4096PublicKey, - Rsa4096PrivateKey, + RSA4096PublicKey, + RSA4096PrivateKey, RSASSA_PKCS1_v1_5_SHA256, RSASSA_PKCS1_v1_5_SHA256, PK_LEN, @@ -442,8 +442,8 @@ fn sha256_trait_conformance_suites() { SIG_LEN, >(fixed_keypair, false); TestFrameworkSignature::new(false, false).test_signature::< - Rsa4096PublicKey, - Rsa4096PrivateKey, + RSA4096PublicKey, + RSA4096PrivateKey, RSASSA_PSS_SHA256, RSASSA_PSS_SHA256, PK_LEN, @@ -455,15 +455,15 @@ fn sha256_trait_conformance_suites() { #[test] fn key_trait_boundary_conditions() { TestFrameworkSignatureKeys::new() - .test_keys::(fixed_keypair); + .test_keys::(fixed_keypair); } /// Sign one-shot and streamed, verify both, and reject a different message -- what a wrong width /// constant in this size's aliases would break. -fn trait_round_trip(pk: &Rsa4096PublicKey, sk: &Rsa4096PrivateKey) +fn trait_round_trip(pk: &RSA4096PublicKey, sk: &RSA4096PrivateKey) where - S: Signer - + SignatureVerifier, + S: Signer + + SignatureVerifier, { let msg = b"RSA-4096 trait round trip"; let sig = S::sign(sk, msg, None).unwrap(); diff --git a/crypto/rsa/tests/rsa_8192_tests.rs b/crypto/rsa/tests/rsa_8192_tests.rs index c39e744d..264ad71e 100644 --- a/crypto/rsa/tests/rsa_8192_tests.rs +++ b/crypto/rsa/tests/rsa_8192_tests.rs @@ -28,9 +28,9 @@ use bouncycastle_core_test_framework::signature::{ use bouncycastle_hex::decode as hex_decode; use bouncycastle_rng::DefaultRNG; 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, Rsa8192PrivateKey, Rsa8192PublicKey, - SIG_LEN, SK_LEN, + PK_LEN, RSA8192PrivateKey, RSA8192PublicKey, 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::collections::HashSet; @@ -80,7 +80,7 @@ fn limbs_from_hex(hex: &str) -> [u64; L] { } /// The fresh, self-generated key used for the BC Java cross-check and for self-consistency. -fn genuine_key() -> Rsa8192PrivateKey { +fn genuine_key() -> RSA8192PrivateKey { let p: [u64; 64] = [ 0xa9a87892c469b1e5, 0x038c3f4efcb198ac, 0xed4f14df1b8a1e1f, 0xef2330d78ee73020, 0xd3093ddaf276904c, 0x94a438d69aeaff23, 0x48dbb3d700ad58ed, 0xbbd763b5346ff916, @@ -171,7 +171,7 @@ fn genuine_key() -> Rsa8192PrivateKey { 0xd1aac2fe108f98c0, 0x1e799537a42b3060, 0xdbcce6fc287e449b, 0x1985969e5afbc524, 0x61ba61f820f83597, 0x65c8523f0767bccc, 0xde04e1644a214f9a, 0x9748f8d853be7131, ]; - Rsa8192PrivateKey::from_crt_components(&p, &q, &d_p, &d_q, &q_inv) + RSA8192PrivateKey::from_crt_components(&p, &q, &d_p, &d_q, &q_inv) .expect("self-generated CRT components must be accepted") } @@ -196,7 +196,7 @@ fn pkcs1_v1_5_matches_bc_java_byte_for_byte() { #[test] fn pkcs1_v1_5_verifies_bc_java_signatures() { let sk = genuine_key(); - let pk = Rsa8192PublicKey::new(sk.n(), 0x10001).unwrap(); + let pk = RSA8192PublicKey::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(); @@ -211,7 +211,7 @@ fn pkcs1_v1_5_verifies_bc_java_signatures() { #[test] fn pss_verifies_bc_java_sha256_signature() { let sk = genuine_key(); - let pk = Rsa8192PublicKey::new(sk.n(), 0x10001).unwrap(); + let pk = RSA8192PublicKey::new(sk.n(), 0x10001).unwrap(); let sig: [u8; 1024] = hex_decode(BC_JAVA_PSS_SHA256_SIG).unwrap().try_into().unwrap(); RSASSA_PSS_SHA256::verify(&pk, b"hello", None, &sig) .expect("BC Java's PSS/SHA-256 signature (default salt length = hLen) must verify"); @@ -226,7 +226,7 @@ fn pss_verifies_bc_java_sha256_signature() { #[test] fn pss_sha256_fixed_salt_round_trips() { let sk = genuine_key(); - let pk = Rsa8192PublicKey::new(sk.n(), 0x10001).unwrap(); + let pk = RSA8192PublicKey::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"); @@ -237,7 +237,7 @@ fn pss_sha256_fixed_salt_round_trips() { #[test] fn pss_sha256_rng_produces_fresh_salts_that_both_verify() { let sk = genuine_key(); - let pk = Rsa8192PublicKey::new(sk.n(), 0x10001).unwrap(); + let pk = RSA8192PublicKey::new(sk.n(), 0x10001).unwrap(); let mut rng = DefaultRNG::default(); let sig_a = RSASSA_PSS_SHA256::sign_randomized(&sk, b"hello", &mut rng).expect("signing must succeed"); @@ -251,7 +251,7 @@ fn pss_sha256_rng_produces_fresh_salts_that_both_verify() { #[test] fn pss_sha384_fixed_salt_round_trips() { let sk = genuine_key(); - let pk = Rsa8192PublicKey::new(sk.n(), 0x10001).unwrap(); + let pk = RSA8192PublicKey::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"); @@ -262,7 +262,7 @@ fn pss_sha384_fixed_salt_round_trips() { #[test] fn pss_sha384_rng_produces_fresh_salts_that_both_verify() { let sk = genuine_key(); - let pk = Rsa8192PublicKey::new(sk.n(), 0x10001).unwrap(); + let pk = RSA8192PublicKey::new(sk.n(), 0x10001).unwrap(); let mut rng = DefaultRNG::default(); let sig_a = RSASSA_PSS_SHA384::sign_randomized(&sk, b"hello", &mut rng).expect("signing must succeed"); @@ -276,7 +276,7 @@ fn pss_sha384_rng_produces_fresh_salts_that_both_verify() { #[test] fn pss_sha512_fixed_salt_round_trips() { let sk = genuine_key(); - let pk = Rsa8192PublicKey::new(sk.n(), 0x10001).unwrap(); + let pk = RSA8192PublicKey::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"); @@ -287,7 +287,7 @@ fn pss_sha512_fixed_salt_round_trips() { #[test] fn pss_sha512_rng_produces_fresh_salts_that_both_verify() { let sk = genuine_key(); - let pk = Rsa8192PublicKey::new(sk.n(), 0x10001).unwrap(); + let pk = RSA8192PublicKey::new(sk.n(), 0x10001).unwrap(); let mut rng = DefaultRNG::default(); let sig_a = RSASSA_PSS_SHA512::sign_randomized(&sk, b"hello", &mut rng).expect("signing must succeed"); @@ -318,7 +318,7 @@ fn distinct_cases(tests: &[Value]) -> Vec<&Value> { fn run_sampled_pkcs1_v1_5_verify_vectors( filename: &str, - verify: impl Fn(&Rsa8192PublicKey, &[u8], &[u8; 1024]) -> bool, + verify: impl Fn(&RSA8192PublicKey, &[u8], &[u8; 1024]) -> bool, expected_sha: &str, ) { let doc: Value = serde_json::from_str(&get_test_data(filename)).expect("valid JSON"); @@ -327,7 +327,7 @@ fn run_sampled_pkcs1_v1_5_verify_vectors( 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 = Rsa8192PublicKey::new(&n, e).unwrap(); + let pk = RSA8192PublicKey::new(&n, e).unwrap(); let tests = group["tests"].as_array().unwrap(); let sample = distinct_cases(tests); @@ -386,9 +386,9 @@ fn rsa_signature_8192_sha512_wycheproof_vectors_sampled() { // ---- bouncycastle_core trait conformance ------------------------------------------------------ -fn fixed_keypair() -> Result<(Rsa8192PublicKey, Rsa8192PrivateKey), SignatureError> { +fn fixed_keypair() -> Result<(RSA8192PublicKey, RSA8192PrivateKey), SignatureError> { let sk = genuine_key(); - let pk = Rsa8192PublicKey::new(sk.n(), 0x10001)?; + let pk = RSA8192PublicKey::new(sk.n(), 0x10001)?; Ok((pk, sk)) } @@ -398,8 +398,8 @@ fn fixed_keypair() -> Result<(Rsa8192PublicKey, Rsa8192PrivateKey), SignatureErr #[test] fn pkcs1_v1_5_sha256_trait_conformance_suite() { TestFrameworkSignature::new(true, false).test_signature::< - Rsa8192PublicKey, - Rsa8192PrivateKey, + RSA8192PublicKey, + RSA8192PrivateKey, RSASSA_PKCS1_v1_5_SHA256, RSASSA_PKCS1_v1_5_SHA256, PK_LEN, @@ -411,13 +411,13 @@ fn pkcs1_v1_5_sha256_trait_conformance_suite() { #[test] fn key_trait_boundary_conditions() { TestFrameworkSignatureKeys::new() - .test_keys::(fixed_keypair); + .test_keys::(fixed_keypair); } -fn trait_round_trip(pk: &Rsa8192PublicKey, sk: &Rsa8192PrivateKey) +fn trait_round_trip(pk: &RSA8192PublicKey, sk: &RSA8192PrivateKey) where - S: Signer - + SignatureVerifier, + S: Signer + + SignatureVerifier, { let msg = b"RSA-8192 trait round trip"; let sig = S::sign(sk, msg, None).unwrap(); diff --git a/mem_usage_benches/src/bench_rsa_mem_usage.rs b/mem_usage_benches/src/bench_rsa_mem_usage.rs index 691edd6c..9ed5ee9c 100644 --- a/mem_usage_benches/src/bench_rsa_mem_usage.rs +++ b/mem_usage_benches/src/bench_rsa_mem_usage.rs @@ -43,40 +43,40 @@ fn print_key_sizes() { println!("\nRSA-1024 (verification only)"); println!("public key on disk (n || e): {} bytes", 132); - println!("size_of: {} bytes", size_of::()); + 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!("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!("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!("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!("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!("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!("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!("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!("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!("signature: {} bytes", 1024); } @@ -96,7 +96,7 @@ fn bench_1024_verify() { 0xb909dd0f4c6014f2, 0x9c8a5810b6d05990, 0x40760d1f23fe9250, 0x90adb011a919575a, 0x45e48572113cab28, 0xcb9ca9ec12000fc8, 0x91b4fcaf62a14595, 0xac9048a7a4f560af, ]; - let pk = rsa_1024::Rsa1024PublicKey::new(&n, 0x10001).unwrap(); + let pk = rsa_1024::RSA1024PublicKey::new(&n, 0x10001).unwrap(); let mut sig = [0u8; 128]; sig.copy_from_slice( &bouncycastle::hex::decode( @@ -113,7 +113,7 @@ fn bench_1024_verify() { } } -fn genuine_2048_key() -> rsa_2048::Rsa2048PrivateKey { +fn genuine_2048_key() -> rsa_2048::RSA2048PrivateKey { let p: [u64; 16] = [ 0x0ea36cfb3a5b18f1, 0x48a6e65332119129, 0x110ad9e7b48a1c93, 0x569156b90113e2e9, 0xe79813a575cfad9c, 0x69d659d143ec6f17, 0xe81e6bab5ddaa783, 0xbff1c5b80a69f788, @@ -144,7 +144,7 @@ fn genuine_2048_key() -> rsa_2048::Rsa2048PrivateKey { 0xe923e1097c0c562f, 0xc968b48a91c38b5b, 0x933e85179c0320b0, 0x7993d0445f758d51, 0x9bfc042ee0924b1b, 0x41f956d90fa8a793, 0xee7a87b6483a66ee, 0x2640fbfbcfefb163, ]; - rsa_2048::Rsa2048PrivateKey::from_crt_components(&p, &q, &d_p, &d_q, &q_inv).unwrap() + rsa_2048::RSA2048PrivateKey::from_crt_components(&p, &q, &d_p, &d_q, &q_inv).unwrap() } fn bench_2048_sign() { @@ -157,7 +157,7 @@ fn bench_2048_sign() { fn bench_2048_verify() { eprintln!("RSA-2048/Verify"); let sk = genuine_2048_key(); - let pk = rsa_2048::Rsa2048PublicKey::new(sk.n(), 0x10001).unwrap(); + let pk = rsa_2048::RSA2048PublicKey::new(sk.n(), 0x10001).unwrap(); let sig = rsa_2048::RSASSA_PKCS1_v1_5_SHA256::sign(&sk, MSG, None).unwrap(); if rsa_2048::RSASSA_PKCS1_v1_5_SHA256::verify(&pk, MSG, None, &sig).is_ok() { @@ -167,7 +167,7 @@ fn bench_2048_verify() { } } -fn genuine_8192_key() -> rsa_8192::Rsa8192PrivateKey { +fn genuine_8192_key() -> rsa_8192::RSA8192PrivateKey { let p: [u64; 64] = [ 0xa9a87892c469b1e5, 0x038c3f4efcb198ac, 0xed4f14df1b8a1e1f, 0xef2330d78ee73020, 0xd3093ddaf276904c, 0x94a438d69aeaff23, 0x48dbb3d700ad58ed, 0xbbd763b5346ff916, @@ -258,7 +258,7 @@ fn genuine_8192_key() -> rsa_8192::Rsa8192PrivateKey { 0xd1aac2fe108f98c0, 0x1e799537a42b3060, 0xdbcce6fc287e449b, 0x1985969e5afbc524, 0x61ba61f820f83597, 0x65c8523f0767bccc, 0xde04e1644a214f9a, 0x9748f8d853be7131, ]; - rsa_8192::Rsa8192PrivateKey::from_crt_components(&p, &q, &d_p, &d_q, &q_inv).unwrap() + rsa_8192::RSA8192PrivateKey::from_crt_components(&p, &q, &d_p, &d_q, &q_inv).unwrap() } fn bench_8192_sign() { @@ -271,7 +271,7 @@ fn bench_8192_sign() { fn bench_8192_verify() { eprintln!("RSA-8192/Verify"); let sk = genuine_8192_key(); - let pk = rsa_8192::Rsa8192PublicKey::new(sk.n(), 0x10001).unwrap(); + let pk = rsa_8192::RSA8192PublicKey::new(sk.n(), 0x10001).unwrap(); let sig = rsa_8192::RSASSA_PKCS1_v1_5_SHA256::sign(&sk, MSG, None).unwrap(); if rsa_8192::RSASSA_PKCS1_v1_5_SHA256::verify(&pk, MSG, None, &sig).is_ok() { From db9c0260fb87833f81e457be41e0a3e52d0f497f Mon Sep 17 00:00:00 2001 From: David Hook Date: Mon, 21 Sep 2026 10:51:12 +1000 Subject: [PATCH 18/55] rsa: add key pair generation (FIPS 186-5 Appendix A.1.3) for RSA-2048/3072/4096/8192, as keygen/keygen_from_rng in each size module and a keygen action in the CLI Until now this crate only consumed keys made elsewhere. This adds generation in the shape the workspace's other signature crates use -- `rsa_2048::keygen() -> Result<(RSA2048PublicKey, RSA2048PrivateKey)>` and `keygen_from_rng(&mut dyn RNG)`, the same pair bouncycastle-ecdsa's curves offer and the `fn() -> Result<(PK, SK)>` core-test-framework's suites take -- over the crate's existing fixed-width limb arithmetic. No arbitrary-precision integer type is introduced: the generator uses `bouncycastle_ec::nat`/`montgomery` and this crate's `modexp` for the wide operations, plus small helpers (a limb-wise `mod u64`, multiply by a `u64`, exact division by a `u64`, a binary GCD and one bit-serial long division) written in keygen.rs. The algorithm is FIPS 186-5 Appendix A.1.3, "Generation of Random Primes that are Probably Prime", step by step, with the standard as the reference and BC Java's org.bouncycastle.crypto.generators.RSAKeyPairGenerator as the structural model (candidate loop, bundled small-factor sieve, the `d` lower-bound retry): * e = 65537 (A.1.1 criterion 1, fixed before the primes; its primality turns criterion 2(a), GCD(p-1, e) = 1, into "e does not divide p-1", step 4.5). * Candidates are nlen/2 DRBG bits with the two top bits set (step 4.2.1) and forced odd (4.3); the top bits make step 4.4's sqrt(2)*2^(nlen/2-1) lower bound hold by construction and n exactly nlen bits, so 4.4 is a debug_assert rather than a retry. * Trial division against the 172 primes below 2^10, bundled into u64 products (Appendix B.7 / BC Java's hasAnySmallFactors), then Appendix B.3.1's Miller-Rabin with random bases in [2, w-2]; the round counts are Table B.1's per size (5 for 1024-bit primes at 2^-112, 4 for 1536-bit at 2^-128, 4 for 2048-bit at 2^-144) and, for RSA-8192's 4096-bit primes which the table does not list, 4 -- Appendix C.1's formula (2), checked to reproduce every table entry, gives 3 at 2^-192 and 5 at 2^-256 for that length. * q additionally satisfies |p - q| > 2^(nlen/2 - 100) (step 5.5 / criterion 2(d)); candidate limits 5*nlen for p and 10*nlen for q (steps 4.7/5.8) turn a stuck RNG into GenericError instead of a hang. * Criterion 3(a), d = e^-1 mod LCM(p-1, q-1) > 2^(nlen/2), is checked on that d (binary GCD, one long division, the e-inverse below) and the whole generation restarts if it fails. * The CRT quintuple: dP = e^-1 mod (p-1) and dQ = e^-1 mod (q-1) (which equal d mod (p-1)/(q-1)), computed without a multi-limb division by the small-prime-e identity d = (k*m + 1)/e with k = -m^-1 mod e (Appendix B.1 allows any algorithm with an equivalent result to its extended Euclid); qInv = q^(p-2) mod p by Fermat through the constant-time mod_pow ladder. * The RNG must offer the modulus's SP 800-57 Part 1 security strength (A.1.3's preamble): 112/128/128/192 bits for 2048/3072/4096/8192, else RNGError::SecurityStrengthInsufficientForAlgorithm. keygen::is_probable_prime is public (Miller-Rabin plus the trial division, conclusive alone below 2^20) so callers importing key material have a primality check; the crate docs' Security Considerations now say that imported keys are still not validated for primality, and that key generation itself is not constant-time (rejection sampling, variable-time small-modulus division on candidates -- BC Java's position too), while signing is unaffected. Candidates and every derived secret live in `Secret` buffers. CLI: `rsa- keygen --pkfile ` writes the private key to stdout and the public key to --pkfile, which is required: an RSA private key file (the CRT quintuple) does not carry e, so there is no PkFromSk here and the public key has to be kept from generation time. The generic rsa_sign_verify_cmd gains the size's keygen as a parameter. Tests (tests/keygen_tests.rs): Miller-Rabin known answers (the documented Wycheproof p and q, M521 and M607 accepted; p+2, p+4, p+6, 2^521+1, even and trivial values rejected; small values decided by trial division alone; zero rounds refused), the FIPS 186-5 A.1.1 criteria checked on generated RSA-2048 and RSA-3072 pairs (top bits, parity, e coprimality, |p-q| bound, n = p*q, p and q probable prime, CRT components reduced) plus sign/verify round trips under both schemes, the conformance suite with the real generator in its keygen slot, and the two RNG failure modes (weak strength, stuck output). RSA-4096/8192 generation is #[ignore]d for --release --ignored runs, being minutes per key. cli/tests/rsa_cli_tests.rs gains a keygen -> sign -> verify round trip. Criterion keygen benches at 2048/3072 (ten samples: it is rejection sampling) and a bench_2048_keygen entry in the memory harness. Co-Authored-By: Claude Fable 5.1 --- cli/src/rsa_cmd.rs | 102 +++- cli/tests/rsa_cli_tests.rs | 41 ++ crypto/rsa/benches/rsa_2048_benches.rs | 8 + crypto/rsa/benches/rsa_3072_benches.rs | 8 + crypto/rsa/src/keygen.rs | 578 +++++++++++++++++++ crypto/rsa/src/keys.rs | 11 +- crypto/rsa/src/lib.rs | 31 +- crypto/rsa/src/rsa_2048.rs | 24 +- crypto/rsa/src/rsa_3072.rs | 24 +- crypto/rsa/src/rsa_4096.rs | 24 +- crypto/rsa/src/rsa_8192.rs | 24 +- crypto/rsa/tests/keygen_tests.rs | 303 ++++++++++ mem_usage_benches/src/bench_rsa_mem_usage.rs | 15 +- 13 files changed, 1143 insertions(+), 50 deletions(-) create mode 100644 crypto/rsa/src/keygen.rs create mode 100644 crypto/rsa/tests/keygen_tests.rs diff --git a/cli/src/rsa_cmd.rs b/cli/src/rsa_cmd.rs index 32ca10c8..dff05f12 100644 --- a/cli/src/rsa_cmd.rs +++ b/cli/src/rsa_cmd.rs @@ -16,20 +16,23 @@ //! 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`. //! -//! `bouncycastle_rsa` does not generate keys (see that crate's `keys` module docs), so there is no -//! `Keygen` action here, and no `PkFromSk` either -- a private key's CRT components alone do not -//! determine the public exponent `e`, so there is nothing to derive a public key from. Private and -//! public key files use the raw fixed-width layout `RsaPrivateKey`/`RsaPublicKey`'s -//! `SignaturePrivateKey`/`SignaturePublicKey` 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. +//! `keygen` (FIPS 186-5 Appendix A.1.3, `bouncycastle_rsa::rsa_*::keygen`) 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 `SignaturePrivateKey`/`SignaturePublicKey` 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 `SignatureVerifier` -- exactly the trait those sizes' //! types implement. -use crate::helpers::{read_from_file, write_bytes_or_hex}; +use crate::helpers::{read_from_file, write_bytes_or_hex, write_bytes_or_hex_to_file}; +use bouncycastle::core::errors::SignatureError; use bouncycastle::core::traits::{ SignaturePrivateKey, SignaturePublicKey, SignatureVerifier, Signer, }; @@ -41,6 +44,8 @@ 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. @@ -163,8 +168,9 @@ fn do_verify< } } -/// One (size, scheme, hash) pairing `S`, signing or verifying stdin per `action`. PSS pairings -/// draw their salt from the library's default OS-backed RNG inside `S::sign_final`. +/// 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::sign_final`; `keygen` is the size's FIPS 186-5 generator, independent of scheme and hash. fn rsa_sign_verify_cmd< PK: SignaturePublicKey, SK: SignaturePrivateKey, @@ -174,6 +180,7 @@ fn rsa_sign_verify_cmd< const SIG_LEN: usize, >( action: &RSAAction, + keygen: fn() -> Result<(PK, SK), SignatureError>, skfile: &Option, pkfile: &Option, sigfile: &Option, @@ -181,6 +188,21 @@ fn rsa_sign_verify_cmd< alg_name: &str, ) { match action { + RSAAction::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().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_bytes_or_hex(&sk.encode(), output_hex); + } RSAAction::Sign => { let sk = parse_sk::(&require_file(skfile, "skfile"), alg_name); @@ -283,11 +305,16 @@ pub(crate) fn rsa_2048_cmd( RSASSA_PSS_SHA512, RSASSA_PSS_SHAKE128, SIG_LEN, SK_LEN, }; let args = (skfile, pkfile, sigfile, output_hex); - let run = - |name: &str, - f: fn(&RSAAction, &Option, &Option, &Option, bool, &str)| { - f(action, args.0, args.1, args.2, args.3, name) - }; + let run = |name: &str, + f: fn( + &RSAAction, + fn() -> Result<(PK, SK), SignatureError>, + &Option, + &Option, + &Option, + bool, + &str, + )| { f(action, rsa_2048::keygen, args.0, args.1, args.2, args.3, name) }; match (scheme, hash) { (RSAScheme::Pkcs1v15, RSAHash::Sha256) => run( "RSA-2048/PKCS#1v1.5/SHA-256", @@ -338,11 +365,16 @@ pub(crate) fn rsa_3072_cmd( RSASSA_PSS_SHA512, RSASSA_PSS_SHAKE128, SIG_LEN, SK_LEN, }; let args = (skfile, pkfile, sigfile, output_hex); - let run = - |name: &str, - f: fn(&RSAAction, &Option, &Option, &Option, bool, &str)| { - f(action, args.0, args.1, args.2, args.3, name) - }; + let run = |name: &str, + f: fn( + &RSAAction, + fn() -> Result<(PK, SK), SignatureError>, + &Option, + &Option, + &Option, + bool, + &str, + )| { f(action, rsa_3072::keygen, args.0, args.1, args.2, args.3, name) }; match (scheme, hash) { (RSAScheme::Pkcs1v15, RSAHash::Sha256) => run( "RSA-3072/PKCS#1v1.5/SHA-256", @@ -394,11 +426,16 @@ pub(crate) fn rsa_4096_cmd( RSASSA_PSS_SHA512, RSASSA_PSS_SHAKE256, SIG_LEN, SK_LEN, }; let args = (skfile, pkfile, sigfile, output_hex); - let run = - |name: &str, - f: fn(&RSAAction, &Option, &Option, &Option, bool, &str)| { - f(action, args.0, args.1, args.2, args.3, name) - }; + let run = |name: &str, + f: fn( + &RSAAction, + fn() -> Result<(PK, SK), SignatureError>, + &Option, + &Option, + &Option, + bool, + &str, + )| { f(action, rsa_4096::keygen, args.0, args.1, args.2, args.3, name) }; match (scheme, hash) { (RSAScheme::Pkcs1v15, RSAHash::Sha256) => run( "RSA-4096/PKCS#1v1.5/SHA-256", @@ -451,11 +488,16 @@ pub(crate) fn rsa_8192_cmd( RSASSA_PSS_SHA512, SIG_LEN, SK_LEN, }; let args = (skfile, pkfile, sigfile, output_hex); - let run = - |name: &str, - f: fn(&RSAAction, &Option, &Option, &Option, bool, &str)| { - f(action, args.0, args.1, args.2, args.3, name) - }; + let run = |name: &str, + f: fn( + &RSAAction, + fn() -> Result<(PK, SK), SignatureError>, + &Option, + &Option, + &Option, + bool, + &str, + )| { f(action, rsa_8192::keygen, args.0, args.1, args.2, args.3, name) }; match (scheme, hash) { (RSAScheme::Pkcs1v15, RSAHash::Sha256) => run( "RSA-8192/PKCS#1v1.5/SHA-256", diff --git a/cli/tests/rsa_cli_tests.rs b/cli/tests/rsa_cli_tests.rs index 62cd8a8c..c799dc5a 100644 --- a/cli/tests/rsa_cli_tests.rs +++ b/cli/tests/rsa_cli_tests.rs @@ -309,3 +309,44 @@ fn unsupported_pairings_are_refused() { ); 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 = RSA2048PublicKey::from_bytes(&unhex(pk_hex.trim())).unwrap(); + assert_eq!(pk.e(), 65537); + + let skfile = temp_file("gensk", sk_hex.trim().as_bytes()); + 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.")); + RSASSA_PSS_SHA256::verify(&pk, &msg, None, &sig).unwrap(); + + let err = run_err(&["rsa-2048", "keygen", "--scheme", "pkcs1v15", "--hash", "sha256"], &[]); + assert!(err.contains("--pkfile"), "stderr: {err}"); +} diff --git a/crypto/rsa/benches/rsa_2048_benches.rs b/crypto/rsa/benches/rsa_2048_benches.rs index 4f0c0ad0..e83579ed 100644 --- a/crypto/rsa/benches/rsa_2048_benches.rs +++ b/crypto/rsa/benches/rsa_2048_benches.rs @@ -9,6 +9,7 @@ use criterion::{Criterion, criterion_group, criterion_main}; use std::hint::black_box; use bouncycastle_rng::DefaultRNG; +use bouncycastle_rsa::rsa_2048::keygen; use bouncycastle_rsa::rsa_2048::{ RSA2048PrivateKey, RSA2048PublicKey, RSASSA_PKCS1_v1_5_SHA256, RSASSA_PKCS1_v1_5_SHA384, RSASSA_PKCS1_v1_5_SHA512, RSASSA_PSS_SHA256, RSASSA_PSS_SHA384, RSASSA_PSS_SHA512, @@ -194,6 +195,13 @@ fn bench_rsa_2048(c: &mut Criterion) { }); 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(keygen().unwrap()))); + keygen_group.finish(); } criterion_group!(benches, bench_rsa_2048); diff --git a/crypto/rsa/benches/rsa_3072_benches.rs b/crypto/rsa/benches/rsa_3072_benches.rs index 7d40145e..b858da88 100644 --- a/crypto/rsa/benches/rsa_3072_benches.rs +++ b/crypto/rsa/benches/rsa_3072_benches.rs @@ -7,6 +7,7 @@ use criterion::{Criterion, criterion_group, criterion_main}; use std::hint::black_box; use bouncycastle_rng::DefaultRNG; +use bouncycastle_rsa::rsa_3072::keygen; use bouncycastle_rsa::rsa_3072::{ RSA3072PrivateKey, RSA3072PublicKey, RSASSA_PKCS1_v1_5_SHA256, RSASSA_PKCS1_v1_5_SHA384, RSASSA_PKCS1_v1_5_SHA512, RSASSA_PSS_SHA256, RSASSA_PSS_SHA384, RSASSA_PSS_SHA512, @@ -202,6 +203,13 @@ fn bench_rsa_3072(c: &mut Criterion) { }); 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(keygen().unwrap()))); + keygen_group.finish(); } criterion_group!(benches, bench_rsa_3072); diff --git a/crypto/rsa/src/keygen.rs b/crypto/rsa/src/keygen.rs new file mode 100644 index 00000000..bd158726 --- /dev/null +++ b/crypto/rsa/src/keygen.rs @@ -0,0 +1,578 @@ +//! 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`/`keygen_from_rng` in their own modules +//! (`crate::rsa_2048::keygen` and siblings): `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::{RsaPrivateKey, RsaPublicKey}; +use crate::modexp::{MontgomeryContext, mod_pow, mul_mod, reduce_wide}; +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; +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_from_rng` 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. + let w_minus_1 = sub_u64(w, 1); + let a = trailing_zeros(&w_minus_1); + let 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 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 = 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 (d1, borrow) = nat::sub(q, p); + let (d2, _) = nat::sub(p, q); + let diff = if borrow == 1 { d2 } else { d1 }; + let threshold_bit = 64 * N as u32 - 100; + let high = shr(&diff, threshold_bit); + if is_zero(&high) { + return true; // |p - q| < 2^(nlen/2 - 100) + } + let mut one = [0u64; N]; + one[0] = 1; + // Exactly 2^(nlen/2 - 100) is also "<=": the high part is 1 and nothing is set below it. + high == one && diff == shl(&one, threshold_bit) +} + +/// 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 `crate::rsa_2048::keygen_from_rng` 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<(RsaPublicKey, RsaPrivateKey), SignatureError> { + 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 g = gcd(&p_minus_1, &q_minus_1); + let q_minus_1_over_g = div(&q_minus_1, &g); + *lcm = montgomery::widening_mul::(&p_minus_1, &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 q_mod_p = reduce_wide::(&q, &p); + let p_minus_2 = sub_u64(&p, 2); + // p is odd by construction (step 4.3), so the context exists. + let ctx_p = MontgomeryContext::new(&p).expect("p is odd"); + *q_inv = mod_pow::(&q_mod_p, &p_minus_2, &ctx_p); + } + + let sk = RsaPrivateKey::::from_crt_components(&p, &q, &d_p, &d_q, &q_inv)?; + let pk = RsaPublicKey::::new(sk.n(), PUBLIC_EXPONENT)?; + return Ok((pk, sk)); + } +} diff --git a/crypto/rsa/src/keys.rs b/crypto/rsa/src/keys.rs index 530b180d..ffb3a735 100644 --- a/crypto/rsa/src/keys.rs +++ b/crypto/rsa/src/keys.rs @@ -2,11 +2,12 @@ //! "second representation", the CRT quintuple `p`, `q`, `dP`, `dQ`, `qInv`), generic over the //! modulus's limb count `L` and each prime's limb count `HALF`. //! -//! This crate does not generate keys: callers construct these from externally supplied key -//! material (e.g. loaded from CAVP/wycheproof test vectors, or a key produced by another -//! implementation), not from primes generated here. 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. +//! Keys come either from [`crate::keygen`] (FIPS 186-5 Appendix A.1.3, via each size module's +//! `keygen`) or from externally supplied key material (e.g. loaded from CAVP/wycheproof test +//! vectors, or a key produced by another implementation) through [`RsaPrivateKey::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. //! //! Each concrete modulus size's aliases of these types (`crate::rsa_2048::RSA2048PrivateKey` and //! siblings) implement `bouncycastle_core`'s `SignaturePrivateKey`/`SignaturePublicKey` traits, diff --git a/crypto/rsa/src/lib.rs b/crypto/rsa/src/lib.rs index b37ad6b9..e2d00947 100644 --- a/crypto/rsa/src/lib.rs +++ b/crypto/rsa/src/lib.rs @@ -21,8 +21,10 @@ //! a caller-supplied RNG through `sign_randomized`, or is fixed through `set_signer_salt` on a //! streaming state. The key types implement //! [`SignaturePrivateKey`](bouncycastle_core::traits::SignaturePrivateKey)/[`SignaturePublicKey`](bouncycastle_core::traits::SignaturePublicKey) -//! per size. The generic `rsassa_*` modules also expose `*_from_hash` entry points that take -//! the message hash rather than the message, for a caller that already holds the digest. +//! per size, and each signing size's module offers `keygen`/`keygen_from_rng` (FIPS 186-5 +//! Appendix A.1.3, in [`keygen`]), the same pair the ECDSA crate's curves offer. The generic +//! `rsassa_*` modules also expose `*_from_hash` entry points that take the message hash rather +//! than the message, for a caller that already holds the digest. //! //! # Usage Examples //! @@ -32,7 +34,10 @@ //! ``` //! use bouncycastle_core::traits::{SignaturePrivateKey, SignaturePublicKey, SignatureVerifier, Signer}; //! use bouncycastle_rsa::rsa_2048::{RSASSA_PKCS1_v1_5_SHA256, RSASSA_PSS_SHA256, RSA2048PrivateKey, RSA2048PublicKey}; -//! # // The same genuine RSA-2048 keypair as the next example; see there for its provenance. +//! # // 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 `bouncycastle_rsa::rsa_2048::keygen()?` 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]; @@ -169,13 +174,18 @@ //! 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. -//! - **This crate does not generate or validate primality of `p`/`q`.** [`keys::RsaPrivateKey::from_crt_components`] -//! checks that `p`/`q` are odd and distinct and that `dP`/`dQ`/`qInv` are in range, but it has no -//! way to check that `p` and `q` are actually prime (that would need a primality test this crate -//! does not implement) or that `e` is coprime to `λ(n)`. Supplying non-prime or otherwise -//! malformed CRT components produces a key that computes *something*, silently, rather than -//! being rejected -- validating the inputs' number-theoretic properties before construction is -//! entirely the caller's responsibility. +//! - **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.** `Signer::sign` draws it from the //! library's default OS-backed RNG; `sign_randomized` takes the caller's RNG and //! `set_signer_salt` takes the salt itself. Unlike ECDSA's per-message secret `k`, a repeated @@ -208,6 +218,7 @@ mod codec; mod emsa_pkcs1_v1_5; mod emsa_pss; mod emsa_pss_shake; +pub mod keygen; pub mod keys; mod mgf1; pub mod modexp; diff --git a/crypto/rsa/src/rsa_2048.rs b/crypto/rsa/src/rsa_2048.rs index 880a7764..7554b16d 100644 --- a/crypto/rsa/src/rsa_2048.rs +++ b/crypto/rsa/src/rsa_2048.rs @@ -18,9 +18,12 @@ use crate::rsassa_pkcs1_v1_5::RSASSA_PKCS1_v1_5; use crate::rsassa_pss::RSASSA_PSS; use crate::rsassa_pss_shake::RSASSA_PSS_SHAKE; use bouncycastle_core::errors::SignatureError; -use bouncycastle_core::traits::{SignaturePrivateKey, SignaturePublicKey}; +use bouncycastle_core::security_strength::SecurityStrength; +use bouncycastle_core::traits::{RNG, SignaturePrivateKey, SignaturePublicKey}; +use bouncycastle_rng::DefaultRNG; use bouncycastle_sha2::{SHA256, SHA384, SHA512}; use bouncycastle_sha3::SHAKE128; +use core::num::NonZeroUsize; /// An RSA-2048 private key (`p`, `q` each 1024 bits). pub type RSA2048PrivateKey = RsaPrivateKey<32, 16>; @@ -36,6 +39,25 @@ pub const PK_LEN: usize = 260; /// Signature length: `k`, the modulus length in octets (RFC 8017 §8.1.1/§8.2.1 step 2.c). pub const SIG_LEN: usize = 256; +/// FIPS 186-5 Appendix A.1.3 key pair generation for RSA-2048 (see [`crate::keygen`]), sourcing +/// the candidates from the library's default OS-backed RNG. `e` is [`crate::keygen::PUBLIC_EXPONENT`]. +pub fn keygen() -> Result<(RSA2048PublicKey, RSA2048PrivateKey), SignatureError> { + keygen_from_rng(&mut DefaultRNG::default()) +} + +/// As [`keygen`], but sourcing the candidates from the caller-provided RNG, which must offer a +/// security strength of at least 112 bits (SP 800-57 Part 1 Rev. 5, Table 2, `k = 2048`). Each +/// candidate prime gets 5 Miller-Rabin rounds: FIPS 186-5 Table B.1's row for 1024-bit `p` and `q` at an error probability of `2^-112`, RSA-2048's security strength (SP 800-57 Part 1 Rev. 5, Table 2). +pub fn keygen_from_rng( + rng: &mut dyn RNG, +) -> Result<(RSA2048PublicKey, RSA2048PrivateKey), SignatureError> { + crate::keygen::keygen_from_rng::<16, 32, 33>( + rng, + NonZeroUsize::new(5).expect("nonzero literal"), + SecurityStrength::_112bit, + ) +} + impl SignaturePrivateKey for RSA2048PrivateKey { fn encode(&self) -> [u8; SK_LEN] { self.encode_raw::<128, SK_LEN>() diff --git a/crypto/rsa/src/rsa_3072.rs b/crypto/rsa/src/rsa_3072.rs index 1423746b..5315a951 100644 --- a/crypto/rsa/src/rsa_3072.rs +++ b/crypto/rsa/src/rsa_3072.rs @@ -6,9 +6,12 @@ use crate::rsassa_pkcs1_v1_5::RSASSA_PKCS1_v1_5; use crate::rsassa_pss::RSASSA_PSS; use crate::rsassa_pss_shake::RSASSA_PSS_SHAKE; use bouncycastle_core::errors::SignatureError; -use bouncycastle_core::traits::{SignaturePrivateKey, SignaturePublicKey}; +use bouncycastle_core::security_strength::SecurityStrength; +use bouncycastle_core::traits::{RNG, SignaturePrivateKey, SignaturePublicKey}; +use bouncycastle_rng::DefaultRNG; use bouncycastle_sha2::{SHA256, SHA384, SHA512}; use bouncycastle_sha3::SHAKE128; +use core::num::NonZeroUsize; /// An RSA-3072 private key (`p`, `q` each 1536 bits). pub type RSA3072PrivateKey = RsaPrivateKey<48, 24>; @@ -24,6 +27,25 @@ pub const PK_LEN: usize = 388; /// Signature length: `k`, the modulus length in octets (RFC 8017 §8.1.1/§8.2.1 step 2.c). pub const SIG_LEN: usize = 384; +/// FIPS 186-5 Appendix A.1.3 key pair generation for RSA-3072 (see [`crate::keygen`]), sourcing +/// the candidates from the library's default OS-backed RNG. `e` is [`crate::keygen::PUBLIC_EXPONENT`]. +pub fn keygen() -> Result<(RSA3072PublicKey, RSA3072PrivateKey), SignatureError> { + keygen_from_rng(&mut DefaultRNG::default()) +} + +/// As [`keygen`], but sourcing the candidates from the caller-provided RNG, which must offer a +/// security strength of at least 128 bits (SP 800-57 Part 1 Rev. 5, Table 2, `k = 3072`). Each +/// candidate prime gets 4 Miller-Rabin rounds: FIPS 186-5 Table B.1's row for 1536-bit `p` and `q` at an error probability of `2^-128`, RSA-3072's security strength (SP 800-57 Part 1 Rev. 5, Table 2). +pub fn keygen_from_rng( + rng: &mut dyn RNG, +) -> Result<(RSA3072PublicKey, RSA3072PrivateKey), SignatureError> { + crate::keygen::keygen_from_rng::<24, 48, 49>( + rng, + NonZeroUsize::new(4).expect("nonzero literal"), + SecurityStrength::_128bit, + ) +} + impl SignaturePrivateKey for RSA3072PrivateKey { fn encode(&self) -> [u8; SK_LEN] { self.encode_raw::<192, SK_LEN>() diff --git a/crypto/rsa/src/rsa_4096.rs b/crypto/rsa/src/rsa_4096.rs index 066576b5..285745ab 100644 --- a/crypto/rsa/src/rsa_4096.rs +++ b/crypto/rsa/src/rsa_4096.rs @@ -6,9 +6,12 @@ use crate::rsassa_pkcs1_v1_5::RSASSA_PKCS1_v1_5; use crate::rsassa_pss::RSASSA_PSS; use crate::rsassa_pss_shake::RSASSA_PSS_SHAKE; use bouncycastle_core::errors::SignatureError; -use bouncycastle_core::traits::{SignaturePrivateKey, SignaturePublicKey}; +use bouncycastle_core::security_strength::SecurityStrength; +use bouncycastle_core::traits::{RNG, SignaturePrivateKey, SignaturePublicKey}; +use bouncycastle_rng::DefaultRNG; use bouncycastle_sha2::{SHA256, SHA384, SHA512}; use bouncycastle_sha3::SHAKE256; +use core::num::NonZeroUsize; /// An RSA-4096 private key (`p`, `q` each 2048 bits). pub type RSA4096PrivateKey = RsaPrivateKey<64, 32>; @@ -24,6 +27,25 @@ pub const PK_LEN: usize = 516; /// Signature length: `k`, the modulus length in octets (RFC 8017 §8.1.1/§8.2.1 step 2.c). pub const SIG_LEN: usize = 512; +/// FIPS 186-5 Appendix A.1.3 key pair generation for RSA-4096 (see [`crate::keygen`]), sourcing +/// the candidates from the library's default OS-backed RNG. `e` is [`crate::keygen::PUBLIC_EXPONENT`]. +pub fn keygen() -> Result<(RSA4096PublicKey, RSA4096PrivateKey), SignatureError> { + keygen_from_rng(&mut DefaultRNG::default()) +} + +/// As [`keygen`], but sourcing the candidates from the caller-provided RNG, which must offer a +/// security strength of at least 128 bits: SP 800-57 Part 1 Rev. 5, Table 2 lists 128 for `k = 3072` and 192 for `k = 7680`, so 4096 is at least 128. Each +/// candidate prime gets 4 Miller-Rabin rounds: FIPS 186-5 Table B.1's row for 2048-bit `p` and `q` at an error probability of `2^-144` (the strength Table B.1 itself pairs with this size). +pub fn keygen_from_rng( + rng: &mut dyn RNG, +) -> Result<(RSA4096PublicKey, RSA4096PrivateKey), SignatureError> { + crate::keygen::keygen_from_rng::<32, 64, 65>( + rng, + NonZeroUsize::new(4).expect("nonzero literal"), + SecurityStrength::_128bit, + ) +} + impl SignaturePrivateKey for RSA4096PrivateKey { fn encode(&self) -> [u8; SK_LEN] { self.encode_raw::<256, SK_LEN>() diff --git a/crypto/rsa/src/rsa_8192.rs b/crypto/rsa/src/rsa_8192.rs index 60e21907..8c8246dc 100644 --- a/crypto/rsa/src/rsa_8192.rs +++ b/crypto/rsa/src/rsa_8192.rs @@ -5,8 +5,11 @@ use crate::keys::{RsaPrivateKey, RsaPublicKey}; use crate::rsassa_pkcs1_v1_5::RSASSA_PKCS1_v1_5; use crate::rsassa_pss::RSASSA_PSS; use bouncycastle_core::errors::SignatureError; -use bouncycastle_core::traits::{SignaturePrivateKey, SignaturePublicKey}; +use bouncycastle_core::security_strength::SecurityStrength; +use bouncycastle_core::traits::{RNG, SignaturePrivateKey, SignaturePublicKey}; +use bouncycastle_rng::DefaultRNG; use bouncycastle_sha2::{SHA256, SHA384, SHA512}; +use core::num::NonZeroUsize; /// An RSA-8192 private key (`p`, `q` each 4096 bits). pub type RSA8192PrivateKey = RsaPrivateKey<128, 64>; @@ -22,6 +25,25 @@ pub const PK_LEN: usize = 1028; /// Signature length: `k`, the modulus length in octets (RFC 8017 §8.1.1/§8.2.1 step 2.c). pub const SIG_LEN: usize = 1024; +/// FIPS 186-5 Appendix A.1.3 key pair generation for RSA-8192 (see [`crate::keygen`]), sourcing +/// the candidates from the library's default OS-backed RNG. `e` is [`crate::keygen::PUBLIC_EXPONENT`]. +pub fn keygen() -> Result<(RSA8192PublicKey, RSA8192PrivateKey), SignatureError> { + keygen_from_rng(&mut DefaultRNG::default()) +} + +/// As [`keygen`], but sourcing the candidates from the caller-provided RNG, which must offer a +/// security strength of at least 192 bits (SP 800-57 Part 1 Rev. 5, Table 2: `k = 7680` gives 192, and 8192 exceeds it). Each +/// candidate prime gets 4 Miller-Rabin rounds: FIPS 186-5 Table B.1 stops at 2048-bit primes; Appendix C.1's formula (2), which reproduces every entry of that table, gives 3 rounds for 4096-bit primes at `2^-192` (RSA-8192 exceeds SP 800-57's 7680-bit/192-bit row) and 5 at `2^-256`, so 4 is taken, matching the table's last row with margin. +pub fn keygen_from_rng( + rng: &mut dyn RNG, +) -> Result<(RSA8192PublicKey, RSA8192PrivateKey), SignatureError> { + crate::keygen::keygen_from_rng::<64, 128, 129>( + rng, + NonZeroUsize::new(4).expect("nonzero literal"), + SecurityStrength::_192bit, + ) +} + impl SignaturePrivateKey for RSA8192PrivateKey { fn encode(&self) -> [u8; SK_LEN] { self.encode_raw::<512, SK_LEN>() diff --git a/crypto/rsa/tests/keygen_tests.rs b/crypto/rsa/tests/keygen_tests.rs new file mode 100644 index 00000000..ad4c1efe --- /dev/null +++ b/crypto/rsa/tests/keygen_tests.rs @@ -0,0 +1,303 @@ +//! Tests for [`bouncycastle_rsa::keygen`] and the per-size `keygen`/`keygen_from_rng` 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::traits::{RNG, SignaturePrivateKey, SignatureVerifier, Signer}; +use bouncycastle_core_test_framework::signature::TestFrameworkSignature; +use bouncycastle_ec::montgomery::widening_mul; +use bouncycastle_rng::DefaultRNG; +use bouncycastle_rsa::keygen::{PUBLIC_EXPONENT, is_probable_prime}; +use bouncycastle_rsa::rsa_2048::{ + self, PK_LEN, RSA2048PrivateKey, RSA2048PublicKey, RSASSA_PKCS1_v1_5_SHA256, RSASSA_PSS_SHA256, + SIG_LEN, SK_LEN, +}; +use bouncycastle_rsa::{rsa_3072, rsa_4096, rsa_8192}; +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) = rsa_2048::keygen().unwrap(); + assert_eq!(pk.e(), PUBLIC_EXPONENT); + assert_eq!(pk.n(), sk.n()); + assert_fips_186_5_criteria::<16, 32, 33>(&sk.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 = RSASSA_PKCS1_v1_5_SHA256::sign(&sk, msg, None).unwrap(); + RSASSA_PKCS1_v1_5_SHA256::verify(&pk, msg, None, &sig).unwrap(); + assert!(RSASSA_PKCS1_v1_5_SHA256::verify(&pk, b"other", None, &sig).is_err()); + let sig = RSASSA_PSS_SHA256::sign(&sk, msg, None).unwrap(); + RSASSA_PSS_SHA256::verify(&pk, msg, None, &sig).unwrap(); + + // Two generations give two keys. + let (pk2, _) = rsa_2048::keygen().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(true, false).test_signature::< + RSA2048PublicKey, + RSA2048PrivateKey, + RSASSA_PKCS1_v1_5_SHA256, + RSASSA_PKCS1_v1_5_SHA256, + PK_LEN, + SK_LEN, + SIG_LEN, + >(rsa_2048::keygen, false); +} + +#[test] +fn keygen_3072_meets_fips_186_5_criteria_and_signs() { + let (pk, sk) = rsa_3072::keygen().unwrap(); + assert_fips_186_5_criteria::<24, 48, 49>(&sk.encode(), pk.n(), 4); + let msg = b"signed with a freshly generated RSA-3072 key"; + let sig = rsa_3072::RSASSA_PKCS1_v1_5_SHA384::sign(&sk, msg, None).unwrap(); + rsa_3072::RSASSA_PKCS1_v1_5_SHA384::verify(&pk, 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) = rsa_4096::keygen().unwrap(); + assert_fips_186_5_criteria::<32, 64, 65>(&sk.encode(), pk.n(), 4); + let msg = b"signed with a freshly generated RSA-4096 key"; + let sig = rsa_4096::RSASSA_PSS_SHA512::sign(&sk, msg, None).unwrap(); + rsa_4096::RSASSA_PSS_SHA512::verify(&pk, 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) = rsa_8192::keygen().unwrap(); + assert_fips_186_5_criteria::<64, 128, 129>(&sk.encode(), pk.n(), 4); + let msg = b"signed with a freshly generated RSA-8192 key"; + let sig = rsa_8192::RSASSA_PKCS1_v1_5_SHA256::sign(&sk, msg, None).unwrap(); + rsa_8192::RSASSA_PKCS1_v1_5_SHA256::verify(&pk, 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_from_rng_rejects_an_rng_below_the_required_strength() { + let mut weak = ConstantRng { fill: 0x42, strength: SecurityStrength::None }; + assert!(matches!( + rsa_2048::keygen_from_rng(&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_from_rng_gives_up_on_a_stuck_rng() { + let mut stuck = ConstantRng { fill: 0x42, strength: SecurityStrength::_256bit }; + assert!(matches!(rsa_2048::keygen_from_rng(&mut stuck), Err(SignatureError::GenericError(_)))); +} diff --git a/mem_usage_benches/src/bench_rsa_mem_usage.rs b/mem_usage_benches/src/bench_rsa_mem_usage.rs index 9ed5ee9c..0f2ff629 100644 --- a/mem_usage_benches/src/bench_rsa_mem_usage.rs +++ b/mem_usage_benches/src/bench_rsa_mem_usage.rs @@ -30,7 +30,9 @@ #![allow(dead_code)] #![allow(unused_imports)] -use bouncycastle::core::traits::{SignatureVerifier, Signer}; +use bouncycastle::core::traits::{ + SignaturePrivateKey, SignaturePublicKey, SignatureVerifier, Signer, +}; use bouncycastle::rsa::{rsa_1024, rsa_1536, rsa_2048, rsa_3072, rsa_4096, rsa_8192}; const MSG: &[u8] = b"peak stack usage of RSA sign/verify, held constant across every modulus size"; @@ -147,6 +149,16 @@ fn genuine_2048_key() -> rsa_2048::RSA2048PrivateKey { rsa_2048::RSA2048PrivateKey::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) = rsa_2048::keygen().unwrap(); + println!("{:x?}", pk.encode()); + println!("{}", sk.encode().len()); +} + fn bench_2048_sign() { eprintln!("RSA-2048/Sign"); let sk = genuine_2048_key(); @@ -285,6 +297,7 @@ fn main() { print_key_sizes() // bench_do_nothing() // bench_1024_verify() + // bench_2048_keygen() // bench_2048_sign() // bench_2048_verify() // bench_8192_sign() From b53961273dd5963e0af1c44a103c5a70ada5e8e9 Mon Sep 17 00:00:00 2001 From: David Hook Date: Thu, 24 Sep 2026 20:56:20 +1000 Subject: [PATCH 19/55] rsa: split the exponentiation out of rsavp1/rsasp1 into crate-private public_exp/crt_exp, ahead of RSASVE reusing it under SP 800-56B's range checks MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A refactor only, with no change in behaviour: rsavp1 and rsasp1 keep their RFC 8017 §5.2.2/§5.2.1 step 1 range checks (0 <= x < n) and now call public_exp (x^e mod n) and crt_exp (RFC 8017 §5.2.1 step 2.b's CRT recombination). The code is moved as it was, comments included. The coming RSASVE KEM needs the same two exponentiations under different range checks: SP 800-56B Rev. 2 §7.1.1 RSAEP and §7.1.2.3 RSADP both require 1 < x < n - 1. Splitting the exponentiation out lets each primitive own its specification's check without duplicating the CRT code. Assisted-by: Claude:claude-opus-5-5 Co-Authored-By: Claude Opus 5.5 --- crypto/rsa/src/rsa_core.rs | 34 ++++++++++++++++++++++++++++++++-- 1 file changed, 32 insertions(+), 2 deletions(-) diff --git a/crypto/rsa/src/rsa_core.rs b/crypto/rsa/src/rsa_core.rs index 4a081456..6d7f75c8 100644 --- a/crypto/rsa/src/rsa_core.rs +++ b/crypto/rsa/src/rsa_core.rs @@ -28,13 +28,24 @@ pub(crate) fn rsavp1( if nat::sub(s, pk.n()).1 != 1 { return Err(SignatureError::DecodingError("signature representative out of range")); } + Ok(public_exp::(pk, s)) +} + +/// `x^e mod n` under the public key, with no range check of its own: RSAVP1's step 2 (RFC 8017 +/// §5.2.2), shared with any other primitive that exponentiates by `e` -- each caller applies its +/// own specification's range check on `x` first, since those differ (RFC 8017 §5.2.2 step 1 +/// accepts "between 0 and n - 1"). +pub(crate) fn public_exp( + pk: &RsaPublicKey, + x: &[u64; L], +) -> [u64; L] { let ctx = MontgomeryContext::::new(pk.n()) .expect("RsaPublicKey::new already validated n is odd and nonzero"); let mut e_limbs = [0u64; L]; e_limbs[0] = pk.e() as u64; - Ok(mod_pow::(s, &e_limbs, &ctx)) + mod_pow::(x, &e_limbs, &ctx) } /// RSASP1 (RFC 8017 §5.2.1), CRT form (step 2.b, two-prime case): `s1 = m^dP mod p`, `s2 = m^dQ @@ -57,6 +68,25 @@ pub(crate) fn rsasp1< return Err(SignatureError::DecodingError("message representative out of range")); } + Ok(crt_exp::(sk, m)) +} + +/// `m^d mod n` through the CRT quintuple, with no range check of its own: RSASP1's step 2.b (RFC +/// 8017 §5.2.1, two-prime case), shared with any other primitive that exponentiates by the private +/// key -- each caller applies its own specification's range check on `m` first, since those +/// differ (RFC 8017 §5.2.1 step 1 accepts "between 0 and n - 1"). `m < n` is all this function +/// itself relies on. +pub(crate) fn crt_exp< + const L: usize, + const L2: usize, + const L21: usize, + const HALF: usize, + const HALF2: usize, + const HALF21: usize, +>( + sk: &RsaPrivateKey, + m: &[u64; L], +) -> [u64; L] { let ctx_p = MontgomeryContext::::new(sk.p()) .expect("RsaPrivateKey::from_crt_components already validated p is odd and nonzero"); let ctx_q = MontgomeryContext::::new(sk.q()) @@ -92,7 +122,7 @@ pub(crate) fn rsasp1< let (s, carry) = nat::add(&s2_wide, &q_h); debug_assert_eq!(carry, 0, "CRT recombination must stay within n's width"); - Ok(s) + s } #[cfg(test)] From e075ea60f31382fc28b397a28dced814a93cb96f Mon Sep 17 00:00:00 2001 From: David Hook Date: Thu, 24 Sep 2026 22:53:53 +1000 Subject: [PATCH 20/55] =?UTF-8?q?rsa:=20add=20RSASVE=20(SP=20800-56B=20Rev?= =?UTF-8?q?.=202=20=C2=A77.2.1)=20as=20a=20KEM=20for=20RSA-2048/3072/4096/?= =?UTF-8?q?8192,=20with=20KEM-only=20key=20types,=20and=20rsasve-=20?= =?UTF-8?q?CLI=20subcommands?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit RSA Secret-Value Encapsulation is the scheme BC FIPS Java 2.0 exposes as FipsRSA.KTS_SVE (JCA "RSA-KAS-KEM") and OpenSSL 3 as its "RSASVE" KEM operation. Each signing size module now has `RSASVE`, which implements bouncycastle_core's KEMEncapsulator/KEMDecapsulator: * encaps_rng is RSASVE.GENERATE (§7.2.1.2). It draws nLen bytes Z, and z = BS2I(Z) is redrawn until 1 < z < n - 1 (step 2.c), capped at 128 draws so a stuck RNG gives GenericError instead of a hang. C = z^e mod n. The RNG must meet the modulus's SP 800-57 strength (§5.3): 112/128/128/192 bits for 2048/3072/4096/8192. * decaps is RSASVE.RECOVER (§7.2.1.3). A ciphertext that is not nLen bytes long is a LengthError. RSADP's range check (§7.1.2.3 step 1, 1 < c < n - 1) gives DecapsulationFailed, and the CRT exponentiation follows. * The shared secret is Z itself: nLen bytes, KeyType::CryptographicRandom, labelled with the modulus's security strength. It is not a derived key. SP 800-56B only ever uses Z as KDF input, and the crate docs' Security Considerations say so. The key types are new: RsaKEMPublicKey/RsaKEMPrivateKey, per-size RSAKEMPublicKey/RSAKEMPrivateKey. They wrap the signature key types, so a signing key cannot decapsulate and a KEM key cannot sign. §6.1 item 5 forbids using one key pair for both purposes. BC FIPS Java enforces this at runtime with canBeUsed(ENCRYPT_OR_DECRYPT); here the compiler does. The encodings are the signature keys' raw layouts, unchanged. The KEM key types also require e >= 65537 (§6.2.1 item 2) and an n of exactly the size's bit length (§6.4.2.2 requires an approved modulus length). The second check also fixes nLen and keeps step 2.c's rejection rate below one half. RSASVE::keygen/keygen_from_rng wrap each size's existing FIPS 186-5 generator. Validation, tests/rsasve_tests.rs (vectors in bc-test-data/crypto/rsa): * NIST ACVP-Server KAS-IFC-SSC-Sp800-56Br2: the KAS1 group (2048, CRT) and the KAS2 group (3072, CRT, both directions). decaps recovers Z from C, and encaps_rng fed the vector's Z reproduces its C. The failChangedZ cases do not match. * ACVP-Server RSA-DecryptionPrimitive-Sp800-56Br2, CRT groups at 2048/3072/4096: 45 cases, 12 of them out-of-range ciphertexts that must fail. * OpenSSL 3.0.13 EVP_PKEY_encapsulate with kem op "RSASVE", at all four sizes: five encapsulations per size, both directions. The harness source is openssl/ossl_rsasve.c. Live interop also agreed: bc-rust CLI encaps to OpenSSL decap at every size, and bc-rust- generated keys (PEM-converted) with OpenSSL at 2048-4096. * core-test-framework's KEM and KEM-key suites at every size. There are boundary tests for both range checks (0, 1, 2, n-2, n-1, n, all ones), the draw cap, the RNG strength, key validation and the error mapping. cargo mutants over rsasve.rs and the KEM code in rsa_{2048,3072,4096, 8192}.rs, running rsasve_tests: 168 mutants, 72 caught, 95 unviable (mostly Default::default() on types without Default), 0 missed. One timeout is a real hang: `attempts += 1` -> `*= 1` removes the draw cap. Seven timeouts at --timeout 300 were rechecked at 900 and caught. Also: criterion encaps/decaps benches per size; bench_rsa_mem_usage entries (peak stack 10.7 KB encaps / 10.7 KB decaps at 2048, 35.5 KB / 40.8 KB at 8192); crate docs (Scope, Usage Examples with an HKDF step, Status, Memory Usage, Security Considerations); and the cli rsasve-2048 .. rsasve-8192 subcommands (keygen/encaps/decaps, shaped like mlkem's). Known limitations, documented: e must fit in a u32. Decapsulation is not blinded. Only partial public-key validation is done. RSASVE does not authenticate a ciphertext: any C in range recovers some Z. Encapsulation costs a full-width modexp (12.6 ms at 2048 against 3.4 ms for decaps) because mod_pow walks all 64 * L exponent bits even for a 17-bit e. RSA signature verification already pays this cost, and a fix is left for a separate change. Assisted-by: Claude:claude-opus-5-5 Co-Authored-By: Claude Opus 5.5 --- cli/src/main.rs | 108 ++++ cli/src/rsasve_cmd.rs | 213 +++++++ crypto/rsa/benches/rsa_2048_benches.rs | 19 +- crypto/rsa/benches/rsa_3072_benches.rs | 19 +- crypto/rsa/benches/rsa_4096_benches.rs | 19 +- crypto/rsa/benches/rsa_8192_benches.rs | 19 +- crypto/rsa/src/lib.rs | 101 ++- crypto/rsa/src/rsa_2048.rs | 78 ++- crypto/rsa/src/rsa_3072.rs | 78 ++- crypto/rsa/src/rsa_4096.rs | 78 ++- crypto/rsa/src/rsa_8192.rs | 78 ++- crypto/rsa/src/rsasve.rs | 417 +++++++++++++ crypto/rsa/tests/rsasve_tests.rs | 619 +++++++++++++++++++ mem_usage_benches/src/bench_rsa_mem_usage.rs | 94 ++- 14 files changed, 1925 insertions(+), 15 deletions(-) create mode 100644 cli/src/rsasve_cmd.rs create mode 100644 crypto/rsa/src/rsasve.rs create mode 100644 crypto/rsa/tests/rsasve_tests.rs diff --git a/cli/src/main.rs b/cli/src/main.rs index f33dc22b..85b9bdcd 100644 --- a/cli/src/main.rs +++ b/cli/src/main.rs @@ -2944,6 +2944,102 @@ 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, + }, + /// 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 { @@ -3791,6 +3887,18 @@ fn run() { Some(Subcommands::RSASVE_8192 { action, skfile, pkfile, ctfile, x }) => { rsasve_cmd::rsasve_8192_cmd(action, skfile, pkfile, ctfile, *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_1024 { scheme, hash, pkfile, sigfile }) => { rsa_cmd::rsa_1024_cmd(scheme, hash, pkfile, sigfile); } diff --git a/cli/src/rsasve_cmd.rs b/cli/src/rsasve_cmd.rs new file mode 100644 index 00000000..e50f313f --- /dev/null +++ b/cli/src/rsasve_cmd.rs @@ -0,0 +1,213 @@ +//! 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 `KEMEncapsulator`/`KEMDecapsulator` traits, 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::{ + read_from_file, read_from_file_or_stdin, write_bytes_or_hex, write_bytes_or_hex_to_file, +}; +use bouncycastle::core::errors::KEMError; +use bouncycastle::core::key_material::KeyMaterialTrait; +use bouncycastle::core::traits::{KEMDecapsulator, KEMEncapsulator, KEMPrivateKey, KEMPublicKey}; +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, +} + +fn require_file(file: &Option, flag_name: &str) -> Vec { + match file { + Some(f) => read_from_file(f), + None => { + eprintln!("Error: no {flag_name} provided."); + exit(-1); + } + } +} + +/// One modulus size's RSASVE, per `action`. +fn rsasve_cmd< + PK: KEMPublicKey, + SK: KEMPrivateKey, + K: KEMEncapsulator + KEMDecapsulator, + const PK_LEN: usize, + const SK_LEN: usize, + const CT_LEN: usize, + const SS_LEN: usize, +>( + action: &RSASVEAction, + keygen: fn() -> 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().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_bytes_or_hex(&sk.encode(), output_hex); + } + RSASVEAction::Encaps => { + let pk = PK::from_bytes(&read_from_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) = K::encaps(&pk).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_bytes_or_hex(ss.ref_to_bytes(), output_hex); + } + None => { + write_bytes_or_hex(&ct, true); + println!(); + write_bytes_or_hex(ss.ref_to_bytes(), true); + } + } + } + RSASVEAction::Decaps => { + let sk = SK::from_bytes(&require_file(skfile, "skfile")).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); + }); + // `decaps` reports a wrong-length ciphertext itself (as `LengthError`). + let ss = K::decaps(&sk, &read_from_file_or_stdin(ctfile)).unwrap_or_else(|e| { + eprintln!("Error: {alg_name} decapsulation failed: {e:?}"); + exit(-1); + }); + write_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/crypto/rsa/benches/rsa_2048_benches.rs b/crypto/rsa/benches/rsa_2048_benches.rs index e83579ed..58765bd7 100644 --- a/crypto/rsa/benches/rsa_2048_benches.rs +++ b/crypto/rsa/benches/rsa_2048_benches.rs @@ -4,7 +4,11 @@ //! 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::traits::{SignatureVerifier, Signer}; +use bouncycastle_core::traits::{ + KEMDecapsulator, KEMEncapsulator, KEMPrivateKey, KEMPublicKey, SignaturePrivateKey, + SignaturePublicKey, SignatureVerifier, Signer, +}; +use bouncycastle_rsa::rsa_2048::{RSA2048KEMPrivateKey, RSA2048KEMPublicKey, RSASVE}; use criterion::{Criterion, criterion_group, criterion_main}; use std::hint::black_box; @@ -194,6 +198,19 @@ fn bench_rsa_2048(c: &mut Criterion) { }) }); + // 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.encode()).unwrap(); + let kem_pk = RSA2048KEMPublicKey::from_bytes(&pk.encode()).unwrap(); + let (_, kem_ct) = RSASVE::encaps(&kem_pk).unwrap(); + group.bench_function("rsasve_encaps", |b| { + b.iter(|| black_box(RSASVE::encaps_rng(black_box(&kem_pk), &mut rng).unwrap())) + }); + group.bench_function("rsasve_decaps", |b| { + b.iter(|| black_box(RSASVE::decaps(black_box(&kem_sk), black_box(&kem_ct)).unwrap())) + }); + group.finish(); // FIPS 186-5 A.1.3 key generation: rejection sampling, so the run-to-run spread is large; diff --git a/crypto/rsa/benches/rsa_3072_benches.rs b/crypto/rsa/benches/rsa_3072_benches.rs index b858da88..fc2b2026 100644 --- a/crypto/rsa/benches/rsa_3072_benches.rs +++ b/crypto/rsa/benches/rsa_3072_benches.rs @@ -2,7 +2,11 @@ //! key is the same one `tests/rsa_3072_tests.rs` recovers from Wycheproof's //! `rsa_pkcs1_3072_sig_gen_test.json`. -use bouncycastle_core::traits::{SignatureVerifier, Signer}; +use bouncycastle_core::traits::{ + KEMDecapsulator, KEMEncapsulator, KEMPrivateKey, KEMPublicKey, SignaturePrivateKey, + SignaturePublicKey, SignatureVerifier, Signer, +}; +use bouncycastle_rsa::rsa_3072::{RSA3072KEMPrivateKey, RSA3072KEMPublicKey, RSASVE}; use criterion::{Criterion, criterion_group, criterion_main}; use std::hint::black_box; @@ -202,6 +206,19 @@ fn bench_rsa_3072(c: &mut Criterion) { }) }); + // 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.encode()).unwrap(); + let kem_pk = RSA3072KEMPublicKey::from_bytes(&pk.encode()).unwrap(); + let (_, kem_ct) = RSASVE::encaps(&kem_pk).unwrap(); + group.bench_function("rsasve_encaps", |b| { + b.iter(|| black_box(RSASVE::encaps_rng(black_box(&kem_pk), &mut rng).unwrap())) + }); + group.bench_function("rsasve_decaps", |b| { + b.iter(|| black_box(RSASVE::decaps(black_box(&kem_sk), black_box(&kem_ct)).unwrap())) + }); + group.finish(); // FIPS 186-5 A.1.3 key generation: rejection sampling, so the run-to-run spread is large; diff --git a/crypto/rsa/benches/rsa_4096_benches.rs b/crypto/rsa/benches/rsa_4096_benches.rs index 1eb00c31..db41417e 100644 --- a/crypto/rsa/benches/rsa_4096_benches.rs +++ b/crypto/rsa/benches/rsa_4096_benches.rs @@ -3,7 +3,11 @@ //! `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::traits::{SignatureVerifier, Signer}; +use bouncycastle_core::traits::{ + KEMDecapsulator, KEMEncapsulator, KEMPrivateKey, KEMPublicKey, SignaturePrivateKey, + SignaturePublicKey, SignatureVerifier, Signer, +}; +use bouncycastle_rsa::rsa_4096::{RSA4096KEMPrivateKey, RSA4096KEMPublicKey, RSASVE}; use criterion::{Criterion, criterion_group, criterion_main}; use std::hint::black_box; @@ -212,6 +216,19 @@ fn bench_rsa_4096(c: &mut Criterion) { }) }); + // 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.encode()).unwrap(); + let kem_pk = RSA4096KEMPublicKey::from_bytes(&pk.encode()).unwrap(); + let (_, kem_ct) = RSASVE::encaps(&kem_pk).unwrap(); + group.bench_function("rsasve_encaps", |b| { + b.iter(|| black_box(RSASVE::encaps_rng(black_box(&kem_pk), &mut rng).unwrap())) + }); + group.bench_function("rsasve_decaps", |b| { + b.iter(|| black_box(RSASVE::decaps(black_box(&kem_sk), black_box(&kem_ct)).unwrap())) + }); + group.finish(); } diff --git a/crypto/rsa/benches/rsa_8192_benches.rs b/crypto/rsa/benches/rsa_8192_benches.rs index 36b6435c..166ee354 100644 --- a/crypto/rsa/benches/rsa_8192_benches.rs +++ b/crypto/rsa/benches/rsa_8192_benches.rs @@ -3,7 +3,11 @@ //! 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::traits::{SignatureVerifier, Signer}; +use bouncycastle_core::traits::{ + KEMDecapsulator, KEMEncapsulator, KEMPrivateKey, KEMPublicKey, SignaturePrivateKey, + SignaturePublicKey, SignatureVerifier, Signer, +}; +use bouncycastle_rsa::rsa_8192::{RSA8192KEMPrivateKey, RSA8192KEMPublicKey, RSASVE}; use criterion::{Criterion, criterion_group, criterion_main}; use std::hint::black_box; @@ -227,6 +231,19 @@ fn bench_rsa_8192(c: &mut Criterion) { }) }); + // 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.encode()).unwrap(); + let kem_pk = RSA8192KEMPublicKey::from_bytes(&pk.encode()).unwrap(); + let (_, kem_ct) = RSASVE::encaps(&kem_pk).unwrap(); + group.bench_function("rsasve_encaps", |b| { + b.iter(|| black_box(RSASVE::encaps_rng(black_box(&kem_pk), &mut rng).unwrap())) + }); + group.bench_function("rsasve_decaps", |b| { + b.iter(|| black_box(RSASVE::decaps(black_box(&kem_sk), black_box(&kem_ct)).unwrap())) + }); + group.finish(); } diff --git a/crypto/rsa/src/lib.rs b/crypto/rsa/src/lib.rs index e2d00947..c7d734e4 100644 --- a/crypto/rsa/src/lib.rs +++ b/crypto/rsa/src/lib.rs @@ -1,4 +1,5 @@ -//! RSA digital signatures: RSASSA-PKCS1-v1_5 and RSASSA-PSS (RFC 8017 §8), built on +//! RSA digital signatures, RSASSA-PKCS1-v1_5 and RSASSA-PSS (RFC 8017 §8), and the RSASVE +//! key-encapsulation mechanism (NIST SP 800-56B Rev. 2 §7.2.1), 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 @@ -7,7 +8,8 @@ //! //! # Scope //! -//! Signature schemes only -- no RSAES-OAEP or RSAES-PKCS1-v1_5 encryption. Modulus sizes 2048 +//! Signature schemes, plus RSASVE as a KEM ([`rsasve`]; see below). There is no RSAES-OAEP or +//! RSAES-PKCS1-v1_5 encryption, and so no KTS-OAEP. Modulus sizes 2048 //! through 8192 bits ([`rsa_2048`], [`rsa_3072`], [`rsa_4096`], [`rsa_8192`]) support both signing //! and verification; 1024- and 1536-bit moduli ([`rsa_1024`], [`rsa_1536`]) support verification //! only, enforced by the absence of a private-key type (and so of any `Signer` impl) for those @@ -26,6 +28,15 @@ //! `rsassa_*` modules also expose `*_from_hash` entry points that take the message hash rather //! than the message, for a caller that already holds the digest. //! +//! 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` in each of the 2048/3072/4096/8192 size modules. +//! It implements [`bouncycastle_core`]'s +//! [`KEMEncapsulator`](bouncycastle_core::traits::KEMEncapsulator)/[`KEMDecapsulator`](bouncycastle_core::traits::KEMDecapsulator) +//! over its own key types (`RSA2048KEMPrivateKey`/`RSA2048KEMPublicKey` and siblings), which are +//! kept apart from the signing key types; see [`rsasve`]'s `# Key separation`. Key generation is +//! `RSASVE::keygen`/`keygen_from_rng`, the same FIPS 186-5 generator the signature keys use. The +//! shared secret is RSASVE's raw secret value `Z`, the full modulus length. It is not a derived key. +//! //! # Usage Examples //! //! RSA-2048 with SHA-256 through the `bouncycastle_core` signature traits ([`rsa_2048`]), the @@ -114,6 +125,45 @@ //! # Ok::<(), bouncycastle_core::errors::SignatureError>(()) //! ``` //! +//! RSASVE through the `bouncycastle_core` KEM traits ([`rsa_2048::RSASVE`]). 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::traits::{KEMDecapsulator, KEMEncapsulator, KEMPrivateKey, KEMPublicKey, KDF}; +//! use bouncycastle_rsa::rsa_2048::{RSASVE, RSA2048KEMPrivateKey, RSA2048KEMPublicKey, CT_LEN}; +//! # 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) = RSASVE::encaps(&pk)?; +//! assert_eq!(ct.len(), CT_LEN); +//! +//! // The private-key holder recovers the same Z from C. +//! let z_again = RSASVE::decaps(&sk, &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") +//! .expect("HKDF accepts any non-empty input key"); +//! assert_eq!(key.key_len(), 32); +//! +//! // A wrong-length ciphertext is an error. So is one outside (1, n - 1) (SP 800-56B §7.1.2.3). +//! assert!(RSASVE::decaps(&sk, &ct[1..]).is_err()); +//! assert!(RSASVE::decaps(&sk, &[0u8; CT_LEN]).is_err()); +//! # 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, `sign_randomized` and @@ -140,6 +190,12 @@ //! ([`rsa_2048`], [`rsa_3072`]) and SHAKE256 with RSA-4096 ([`rsa_4096`]), each validated against //! its own genuine Wycheproof `rsa_pss_*_shake*_test.json` vectors. //! +//! RSASVE ([`rsasve`]) is implemented at 2048/3072/4096/8192. 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 | @@ -151,6 +207,20 @@ //! | 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 | +//! //! All values are in bytes. "On disk" is the `SignaturePublicKey`/`SignaturePrivateKey` 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 @@ -204,6 +274,32 @@ //! 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 salt length is fixed to the hash's own output length** (RFC 8017 §9.1 note //! 4's "typical" choice) rather than being caller-configurable. A verifier that expects a //! different salt length (including the zero-length salt some other implementations default @@ -232,3 +328,4 @@ mod rsa_core; pub mod rsassa_pkcs1_v1_5; pub mod rsassa_pss; pub mod rsassa_pss_shake; +pub mod rsasve; diff --git a/crypto/rsa/src/rsa_2048.rs b/crypto/rsa/src/rsa_2048.rs index 7554b16d..78c44f7b 100644 --- a/crypto/rsa/src/rsa_2048.rs +++ b/crypto/rsa/src/rsa_2048.rs @@ -17,9 +17,12 @@ use crate::keys::{RsaPrivateKey, RsaPublicKey}; use crate::rsassa_pkcs1_v1_5::RSASSA_PKCS1_v1_5; use crate::rsassa_pss::RSASSA_PSS; use crate::rsassa_pss_shake::RSASSA_PSS_SHAKE; -use bouncycastle_core::errors::SignatureError; +use crate::rsasve::{RsaKEMPrivateKey, RsaKEMPublicKey}; +use bouncycastle_core::errors::{KEMError, SignatureError}; use bouncycastle_core::security_strength::SecurityStrength; -use bouncycastle_core::traits::{RNG, SignaturePrivateKey, SignaturePublicKey}; +use bouncycastle_core::traits::{ + KEMPrivateKey, KEMPublicKey, RNG, SignaturePrivateKey, SignaturePublicKey, +}; use bouncycastle_rng::DefaultRNG; use bouncycastle_sha2::{SHA256, SHA384, SHA512}; use bouncycastle_sha3::SHAKE128; @@ -128,3 +131,74 @@ pub type RSASSA_PSS_SHA512 = #[allow(non_camel_case_types)] pub type RSASSA_PSS_SHAKE128 = RSASSA_PSS_SHAKE; + +/// An RSA-2048 private key-establishment key for [`RSASVE`], kept apart from the signing key type +/// [`RSA2048PrivateKey`] (see [`crate::rsasve`]'s `# Key separation`). It uses the same `SK_LEN`-byte +/// encoding. +pub type RSA2048KEMPrivateKey = RsaKEMPrivateKey<32, 16>; +/// An RSA-2048 public key-establishment key for [`RSASVE`]; see [`RSA2048KEMPrivateKey`]. It uses +/// the same `PK_LEN`-byte encoding. +pub type RSA2048KEMPublicKey = RsaKEMPublicKey<32>; + +/// [`RSASVE`] ciphertext length: `nLen`, the modulus length in octets (SP 800-56B Rev. 2 +/// §7.2.1.2's output `C`). +pub const CT_LEN: usize = 256; +/// [`RSASVE`] shared-secret length: also `nLen` (§7.2.1.2's output `Z`). This is the raw secret +/// value, not a derived key: see [`crate::rsasve`]. +pub const SS_LEN: usize = 256; + +/// RSASVE (SP 800-56B Rev. 2 §7.2.1) over RSA-2048 as a `KEMEncapsulator`/`KEMDecapsulator`: +/// [`crate::rsasve::RSASVE`] at this size's widths and its 112-bit security strength. +pub type RSASVE = crate::rsasve::RSASVE<32, 64, 65, 16, 32, 33, 256, 112>; + +impl RSASVE { + /// Generates a key-establishment key pair with [`keygen`] (FIPS 186-5 Appendix A.1.3, + /// `e = 65537`), sourcing the candidates from the library's default OS-backed RNG. + pub fn keygen() -> Result<(RSA2048KEMPublicKey, RSA2048KEMPrivateKey), KEMError> { + Self::keygen_from_rng(&mut DefaultRNG::default()) + } + + /// As [`Self::keygen`], but sourcing the candidates from the caller-provided RNG, with the + /// same RNG requirements as [`keygen_from_rng`]. + pub fn keygen_from_rng( + rng: &mut dyn RNG, + ) -> Result<(RSA2048KEMPublicKey, RSA2048KEMPrivateKey), KEMError> { + crate::rsasve::keygen_from(keygen_from_rng(rng)) + } +} + +impl KEMPrivateKey for RSA2048KEMPrivateKey { + fn encode(&self) -> [u8; SK_LEN] { + self.0.encode_raw::<128, SK_LEN>() + } + + fn encode_out(&self, out: &mut [u8; SK_LEN]) -> usize { + *out = self.0.encode_raw::<128, SK_LEN>(); + SK_LEN + } + + fn from_bytes(bytes: &[u8]) -> Result { + let bytes: &[u8; SK_LEN] = bytes + .try_into() + .map_err(|_| KEMError::DecodingError("RSA-2048 private key must be 640 bytes"))?; + crate::rsasve::private_key_from_bytes::<32, 16, 128, SK_LEN>(bytes) + } +} + +impl KEMPublicKey for RSA2048KEMPublicKey { + fn encode(&self) -> [u8; PK_LEN] { + self.0.encode_raw::<256, PK_LEN>() + } + + fn encode_out(&self, out: &mut [u8; PK_LEN]) -> usize { + *out = self.0.encode_raw::<256, PK_LEN>(); + PK_LEN + } + + fn from_bytes(bytes: &[u8]) -> Result { + let bytes: &[u8; PK_LEN] = bytes + .try_into() + .map_err(|_| KEMError::DecodingError("RSA-2048 public key must be 260 bytes"))?; + crate::rsasve::public_key_from_bytes::<32, 256, PK_LEN>(bytes) + } +} diff --git a/crypto/rsa/src/rsa_3072.rs b/crypto/rsa/src/rsa_3072.rs index 5315a951..7c1f2b76 100644 --- a/crypto/rsa/src/rsa_3072.rs +++ b/crypto/rsa/src/rsa_3072.rs @@ -5,9 +5,12 @@ use crate::keys::{RsaPrivateKey, RsaPublicKey}; use crate::rsassa_pkcs1_v1_5::RSASSA_PKCS1_v1_5; use crate::rsassa_pss::RSASSA_PSS; use crate::rsassa_pss_shake::RSASSA_PSS_SHAKE; -use bouncycastle_core::errors::SignatureError; +use crate::rsasve::{RsaKEMPrivateKey, RsaKEMPublicKey}; +use bouncycastle_core::errors::{KEMError, SignatureError}; use bouncycastle_core::security_strength::SecurityStrength; -use bouncycastle_core::traits::{RNG, SignaturePrivateKey, SignaturePublicKey}; +use bouncycastle_core::traits::{ + KEMPrivateKey, KEMPublicKey, RNG, SignaturePrivateKey, SignaturePublicKey, +}; use bouncycastle_rng::DefaultRNG; use bouncycastle_sha2::{SHA256, SHA384, SHA512}; use bouncycastle_sha3::SHAKE128; @@ -113,3 +116,74 @@ pub type RSASSA_PSS_SHA512 = #[allow(non_camel_case_types)] pub type RSASSA_PSS_SHAKE128 = RSASSA_PSS_SHAKE; + +/// An RSA-3072 private key-establishment key for [`RSASVE`], kept apart from the signing key type +/// [`RSA3072PrivateKey`] (see [`crate::rsasve`]'s `# Key separation`). It uses the same `SK_LEN`-byte +/// encoding. +pub type RSA3072KEMPrivateKey = RsaKEMPrivateKey<48, 24>; +/// An RSA-3072 public key-establishment key for [`RSASVE`]; see [`RSA3072KEMPrivateKey`]. It uses +/// the same `PK_LEN`-byte encoding. +pub type RSA3072KEMPublicKey = RsaKEMPublicKey<48>; + +/// [`RSASVE`] ciphertext length: `nLen`, the modulus length in octets (SP 800-56B Rev. 2 +/// §7.2.1.2's output `C`). +pub const CT_LEN: usize = 384; +/// [`RSASVE`] shared-secret length: also `nLen` (§7.2.1.2's output `Z`). This is the raw secret +/// value, not a derived key: see [`crate::rsasve`]. +pub const SS_LEN: usize = 384; + +/// RSASVE (SP 800-56B Rev. 2 §7.2.1) over RSA-3072 as a `KEMEncapsulator`/`KEMDecapsulator`: +/// [`crate::rsasve::RSASVE`] at this size's widths and its 128-bit security strength. +pub type RSASVE = crate::rsasve::RSASVE<48, 96, 97, 24, 48, 49, 384, 128>; + +impl RSASVE { + /// Generates a key-establishment key pair with [`keygen`] (FIPS 186-5 Appendix A.1.3, + /// `e = 65537`), sourcing the candidates from the library's default OS-backed RNG. + pub fn keygen() -> Result<(RSA3072KEMPublicKey, RSA3072KEMPrivateKey), KEMError> { + Self::keygen_from_rng(&mut DefaultRNG::default()) + } + + /// As [`Self::keygen`], but sourcing the candidates from the caller-provided RNG, with the + /// same RNG requirements as [`keygen_from_rng`]. + pub fn keygen_from_rng( + rng: &mut dyn RNG, + ) -> Result<(RSA3072KEMPublicKey, RSA3072KEMPrivateKey), KEMError> { + crate::rsasve::keygen_from(keygen_from_rng(rng)) + } +} + +impl KEMPrivateKey for RSA3072KEMPrivateKey { + fn encode(&self) -> [u8; SK_LEN] { + self.0.encode_raw::<192, SK_LEN>() + } + + fn encode_out(&self, out: &mut [u8; SK_LEN]) -> usize { + *out = self.0.encode_raw::<192, SK_LEN>(); + SK_LEN + } + + fn from_bytes(bytes: &[u8]) -> Result { + let bytes: &[u8; SK_LEN] = bytes + .try_into() + .map_err(|_| KEMError::DecodingError("RSA-3072 private key must be 960 bytes"))?; + crate::rsasve::private_key_from_bytes::<48, 24, 192, SK_LEN>(bytes) + } +} + +impl KEMPublicKey for RSA3072KEMPublicKey { + fn encode(&self) -> [u8; PK_LEN] { + self.0.encode_raw::<384, PK_LEN>() + } + + fn encode_out(&self, out: &mut [u8; PK_LEN]) -> usize { + *out = self.0.encode_raw::<384, PK_LEN>(); + PK_LEN + } + + fn from_bytes(bytes: &[u8]) -> Result { + let bytes: &[u8; PK_LEN] = bytes + .try_into() + .map_err(|_| KEMError::DecodingError("RSA-3072 public key must be 388 bytes"))?; + crate::rsasve::public_key_from_bytes::<48, 384, PK_LEN>(bytes) + } +} diff --git a/crypto/rsa/src/rsa_4096.rs b/crypto/rsa/src/rsa_4096.rs index 285745ab..18530600 100644 --- a/crypto/rsa/src/rsa_4096.rs +++ b/crypto/rsa/src/rsa_4096.rs @@ -5,9 +5,12 @@ use crate::keys::{RsaPrivateKey, RsaPublicKey}; use crate::rsassa_pkcs1_v1_5::RSASSA_PKCS1_v1_5; use crate::rsassa_pss::RSASSA_PSS; use crate::rsassa_pss_shake::RSASSA_PSS_SHAKE; -use bouncycastle_core::errors::SignatureError; +use crate::rsasve::{RsaKEMPrivateKey, RsaKEMPublicKey}; +use bouncycastle_core::errors::{KEMError, SignatureError}; use bouncycastle_core::security_strength::SecurityStrength; -use bouncycastle_core::traits::{RNG, SignaturePrivateKey, SignaturePublicKey}; +use bouncycastle_core::traits::{ + KEMPrivateKey, KEMPublicKey, RNG, SignaturePrivateKey, SignaturePublicKey, +}; use bouncycastle_rng::DefaultRNG; use bouncycastle_sha2::{SHA256, SHA384, SHA512}; use bouncycastle_sha3::SHAKE256; @@ -113,3 +116,74 @@ pub type RSASSA_PSS_SHA512 = #[allow(non_camel_case_types)] pub type RSASSA_PSS_SHAKE256 = RSASSA_PSS_SHAKE; + +/// An RSA-4096 private key-establishment key for [`RSASVE`], kept apart from the signing key type +/// [`RSA4096PrivateKey`] (see [`crate::rsasve`]'s `# Key separation`). It uses the same `SK_LEN`-byte +/// encoding. +pub type RSA4096KEMPrivateKey = RsaKEMPrivateKey<64, 32>; +/// An RSA-4096 public key-establishment key for [`RSASVE`]; see [`RSA4096KEMPrivateKey`]. It uses +/// the same `PK_LEN`-byte encoding. +pub type RSA4096KEMPublicKey = RsaKEMPublicKey<64>; + +/// [`RSASVE`] ciphertext length: `nLen`, the modulus length in octets (SP 800-56B Rev. 2 +/// §7.2.1.2's output `C`). +pub const CT_LEN: usize = 512; +/// [`RSASVE`] shared-secret length: also `nLen` (§7.2.1.2's output `Z`). This is the raw secret +/// value, not a derived key: see [`crate::rsasve`]. +pub const SS_LEN: usize = 512; + +/// RSASVE (SP 800-56B Rev. 2 §7.2.1) over RSA-4096 as a `KEMEncapsulator`/`KEMDecapsulator`: +/// [`crate::rsasve::RSASVE`] at this size's widths and its 128-bit security strength. +pub type RSASVE = crate::rsasve::RSASVE<64, 128, 129, 32, 64, 65, 512, 128>; + +impl RSASVE { + /// Generates a key-establishment key pair with [`keygen`] (FIPS 186-5 Appendix A.1.3, + /// `e = 65537`), sourcing the candidates from the library's default OS-backed RNG. + pub fn keygen() -> Result<(RSA4096KEMPublicKey, RSA4096KEMPrivateKey), KEMError> { + Self::keygen_from_rng(&mut DefaultRNG::default()) + } + + /// As [`Self::keygen`], but sourcing the candidates from the caller-provided RNG, with the + /// same RNG requirements as [`keygen_from_rng`]. + pub fn keygen_from_rng( + rng: &mut dyn RNG, + ) -> Result<(RSA4096KEMPublicKey, RSA4096KEMPrivateKey), KEMError> { + crate::rsasve::keygen_from(keygen_from_rng(rng)) + } +} + +impl KEMPrivateKey for RSA4096KEMPrivateKey { + fn encode(&self) -> [u8; SK_LEN] { + self.0.encode_raw::<256, SK_LEN>() + } + + fn encode_out(&self, out: &mut [u8; SK_LEN]) -> usize { + *out = self.0.encode_raw::<256, SK_LEN>(); + SK_LEN + } + + fn from_bytes(bytes: &[u8]) -> Result { + let bytes: &[u8; SK_LEN] = bytes + .try_into() + .map_err(|_| KEMError::DecodingError("RSA-4096 private key must be 1280 bytes"))?; + crate::rsasve::private_key_from_bytes::<64, 32, 256, SK_LEN>(bytes) + } +} + +impl KEMPublicKey for RSA4096KEMPublicKey { + fn encode(&self) -> [u8; PK_LEN] { + self.0.encode_raw::<512, PK_LEN>() + } + + fn encode_out(&self, out: &mut [u8; PK_LEN]) -> usize { + *out = self.0.encode_raw::<512, PK_LEN>(); + PK_LEN + } + + fn from_bytes(bytes: &[u8]) -> Result { + let bytes: &[u8; PK_LEN] = bytes + .try_into() + .map_err(|_| KEMError::DecodingError("RSA-4096 public key must be 516 bytes"))?; + crate::rsasve::public_key_from_bytes::<64, 512, PK_LEN>(bytes) + } +} diff --git a/crypto/rsa/src/rsa_8192.rs b/crypto/rsa/src/rsa_8192.rs index 8c8246dc..4e268a41 100644 --- a/crypto/rsa/src/rsa_8192.rs +++ b/crypto/rsa/src/rsa_8192.rs @@ -4,9 +4,12 @@ use crate::keys::{RsaPrivateKey, RsaPublicKey}; use crate::rsassa_pkcs1_v1_5::RSASSA_PKCS1_v1_5; use crate::rsassa_pss::RSASSA_PSS; -use bouncycastle_core::errors::SignatureError; +use crate::rsasve::{RsaKEMPrivateKey, RsaKEMPublicKey}; +use bouncycastle_core::errors::{KEMError, SignatureError}; use bouncycastle_core::security_strength::SecurityStrength; -use bouncycastle_core::traits::{RNG, SignaturePrivateKey, SignaturePublicKey}; +use bouncycastle_core::traits::{ + KEMPrivateKey, KEMPublicKey, RNG, SignaturePrivateKey, SignaturePublicKey, +}; use bouncycastle_rng::DefaultRNG; use bouncycastle_sha2::{SHA256, SHA384, SHA512}; use core::num::NonZeroUsize; @@ -107,3 +110,74 @@ pub type RSASSA_PSS_SHA384 = #[allow(non_camel_case_types)] pub type RSASSA_PSS_SHA512 = RSASSA_PSS; + +/// An RSA-8192 private key-establishment key for [`RSASVE`], kept apart from the signing key type +/// [`RSA8192PrivateKey`] (see [`crate::rsasve`]'s `# Key separation`). It uses the same `SK_LEN`-byte +/// encoding. +pub type RSA8192KEMPrivateKey = RsaKEMPrivateKey<128, 64>; +/// An RSA-8192 public key-establishment key for [`RSASVE`]; see [`RSA8192KEMPrivateKey`]. It uses +/// the same `PK_LEN`-byte encoding. +pub type RSA8192KEMPublicKey = RsaKEMPublicKey<128>; + +/// [`RSASVE`] ciphertext length: `nLen`, the modulus length in octets (SP 800-56B Rev. 2 +/// §7.2.1.2's output `C`). +pub const CT_LEN: usize = 1024; +/// [`RSASVE`] shared-secret length: also `nLen` (§7.2.1.2's output `Z`). This is the raw secret +/// value, not a derived key: see [`crate::rsasve`]. +pub const SS_LEN: usize = 1024; + +/// RSASVE (SP 800-56B Rev. 2 §7.2.1) over RSA-8192 as a `KEMEncapsulator`/`KEMDecapsulator`: +/// [`crate::rsasve::RSASVE`] at this size's widths and its 192-bit security strength. +pub type RSASVE = crate::rsasve::RSASVE<128, 256, 257, 64, 128, 129, 1024, 192>; + +impl RSASVE { + /// Generates a key-establishment key pair with [`keygen`] (FIPS 186-5 Appendix A.1.3, + /// `e = 65537`), sourcing the candidates from the library's default OS-backed RNG. + pub fn keygen() -> Result<(RSA8192KEMPublicKey, RSA8192KEMPrivateKey), KEMError> { + Self::keygen_from_rng(&mut DefaultRNG::default()) + } + + /// As [`Self::keygen`], but sourcing the candidates from the caller-provided RNG, with the + /// same RNG requirements as [`keygen_from_rng`]. + pub fn keygen_from_rng( + rng: &mut dyn RNG, + ) -> Result<(RSA8192KEMPublicKey, RSA8192KEMPrivateKey), KEMError> { + crate::rsasve::keygen_from(keygen_from_rng(rng)) + } +} + +impl KEMPrivateKey for RSA8192KEMPrivateKey { + fn encode(&self) -> [u8; SK_LEN] { + self.0.encode_raw::<512, SK_LEN>() + } + + fn encode_out(&self, out: &mut [u8; SK_LEN]) -> usize { + *out = self.0.encode_raw::<512, SK_LEN>(); + SK_LEN + } + + fn from_bytes(bytes: &[u8]) -> Result { + let bytes: &[u8; SK_LEN] = bytes + .try_into() + .map_err(|_| KEMError::DecodingError("RSA-8192 private key must be 2560 bytes"))?; + crate::rsasve::private_key_from_bytes::<128, 64, 512, SK_LEN>(bytes) + } +} + +impl KEMPublicKey for RSA8192KEMPublicKey { + fn encode(&self) -> [u8; PK_LEN] { + self.0.encode_raw::<1024, PK_LEN>() + } + + fn encode_out(&self, out: &mut [u8; PK_LEN]) -> usize { + *out = self.0.encode_raw::<1024, PK_LEN>(); + PK_LEN + } + + fn from_bytes(bytes: &[u8]) -> Result { + let bytes: &[u8; PK_LEN] = bytes + .try_into() + .map_err(|_| KEMError::DecodingError("RSA-8192 public key must be 1028 bytes"))?; + crate::rsasve::public_key_from_bytes::<128, 1024, PK_LEN>(bytes) + } +} diff --git a/crypto/rsa/src/rsasve.rs b/crypto/rsa/src/rsasve.rs new file mode 100644 index 00000000..3bc3e83c --- /dev/null +++ b/crypto/rsa/src/rsasve.rs @@ -0,0 +1,417 @@ +//! RSASVE, RSA Secret-Value Encapsulation (NIST SP 800-56B Rev. 2 §7.2.1), as a +//! [`bouncycastle_core`] KEM: [`RSASVE`] implements +//! [`KEMEncapsulator`]/[`KEMDecapsulator`], with RSASVE.GENERATE (§7.2.1.2) as `encaps` and +//! RSASVE.RECOVER (§7.2.1.3) as `decaps`, over the KEM-only key types [`RsaKEMPublicKey`] and +//! [`RsaKEMPrivateKey`]. +//! +//! 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' [`RsaPublicKey`]/[`RsaPrivateKey`] rather than +//! reusing them, so the type system keeps key-establishment and signing keys apart. There is no +//! `Signer` impl for an [`RsaKEMPrivateKey`] and no `KEMDecapsulator` impl for an +//! [`RsaPrivateKey`]. 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 [`RsaPublicKey::new`]/[`RsaPrivateKey::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 `64 * L` 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 `8 * L` 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 [`RsaPublicKey::new`] checks). Nothing here +//! amounts to full public-key validation, which §6.4.2.2 notes "is not specified in this +//! Recommendation". + +use crate::codec::{be_bytes_from_limbs, limbs_from_be_bytes}; +use crate::keys::{RsaPrivateKey, RsaPublicKey}; +use crate::rsa_core::{crt_exp, public_exp}; +use bouncycastle_core::errors::{KEMError, RNGError, SignatureError}; +use bouncycastle_core::key_material::{ + KeyMaterial, KeyMaterialTrait, KeyType, do_hazardous_operations, +}; +use bouncycastle_core::security_strength::SecurityStrength; +use bouncycastle_core::traits::{ + KEMDecapsulator, KEMEncapsulator, KEMPrivateKey, KEMPublicKey, RNG, +}; +use bouncycastle_ec::nat; +use bouncycastle_rng::DefaultRNG; +use bouncycastle_utils::secret::Secret; +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: "65,537 ≤ e < 2^256". +pub const MIN_PUBLIC_EXPONENT: u32 = 65537; + +/// How many `nLen`-byte draws RSASVE.GENERATE's step 2 makes before it gives up with +/// `GenericError`. §7.2.1.2 step 2.c just says "go to step 2a", with no limit. The limit exists so +/// that a broken RNG, e.g. one stuck on all-`0xFF` output, produces an error rather than a hang, the +/// same reason `crate::keygen` caps its candidate loops. `n`'s top bit is set (see the module docs' +/// `# Key validation`), so a working RNG's draw falls outside `(1, n - 1)` with probability below +/// one half, and 128 draws all fail with probability below `2^-128`. +pub const MAX_GENERATE_ATTEMPTS: usize = 128; + +/// Maps an error from the signature-typed key constructors and key generation this module wraps +/// into its [`KEMError`] equivalent. Every variant those can actually produce keeps its meaning. +fn kem_error(e: SignatureError) -> KEMError { + match e { + SignatureError::DecodingError(s) => KEMError::DecodingError(s), + SignatureError::RNGError(e) => KEMError::RNGError(e), + SignatureError::GenericError(s) => KEMError::GenericError(s), + _ => KEMError::GenericError("unexpected error from the RSA key layer"), + } +} + +/// Whether `n` is exactly `64 * L` bits: see the module docs' `# Key validation`. +fn has_full_bit_length(n: &[u64; L]) -> bool { + n[L - 1] >> 63 == 1 +} + +/// `1 < x < n - 1`, the range SP 800-56B Rev. 2 requires of RSAEP's plaintext (§7.1.1 input 2), +/// RSADP's ciphertext (§7.1.2.3 step 1), and RSASVE.GENERATE's `z` (§7.2.1.2 step 2.c). +/// +/// Written as two borrow-outs combined with `&` rather than as a short-circuiting comparison. In +/// RSASVE.GENERATE `x` is the secret `z`, and it should not matter to the timing which half of the +/// test a rejected candidate failed. +fn in_open_range(x: &[u64; L], n: &[u64; L]) -> 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[0] &= !1; + let mut one = [0u64; L]; + one[0] = 1; + // `x - (n - 1)` borrows exactly when `x < n - 1`; `1 - x` borrows exactly when `1 < x`. + let below_n_minus_1 = nat::sub(x, &n_minus_1).1; + let above_1 = nat::sub(&one, x).1; + (below_n_minus_1 & above_1) == 1 +} + +/// An RSA public key-establishment key: an [`RsaPublicKey`] with the extra checks listed in the +/// module docs' `# Key validation`, and a distinct type so that it cannot verify signatures (see +/// `# Key separation`). +/// +/// # Encoding +/// +/// `KEMPublicKey::encode`/`from_bytes` (implemented per size, e.g. for +/// `crate::rsa_2048::RSA2048KEMPublicKey`) use [`RsaPublicKey`]'s layout, `n || e`, unchanged. +/// Decoding applies this type's checks as well as [`RsaPublicKey`]'s. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct RsaKEMPublicKey(pub(crate) RsaPublicKey); + +impl RsaKEMPublicKey { + /// Builds a public key from its modulus and exponent. Returns + /// `Err(`[`KEMError::DecodingError`]`)` in the cases [`RsaPublicKey::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: &[u64; L], e: u32) -> Result { + Self::from_rsa_key(RsaPublicKey::new(n, e).map_err(kem_error)?) + } + + /// Applies this type's own checks to an already-built [`RsaPublicKey`]. Crate-private, so there + /// is no direct signature-key-to-KEM-key conversion in the public API. Key material still gets + /// in through its raw components or encoding, which the two kinds of key share. + pub(crate) fn from_rsa_key(pk: RsaPublicKey) -> 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`. + pub fn n(&self) -> &[u64; L] { + self.0.n() + } + + /// The public exponent `e`. + pub fn e(&self) -> u32 { + self.0.e() + } +} + +/// Defers to [`RsaPublicKey`]'s `Display`. Required by `KEMPublicKey`'s `Display` supertrait. +impl Display for RsaKEMPublicKey { + fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { + self.0.fmt(f) + } +} + +/// An RSA private key-establishment key: an [`RsaPrivateKey`] (CRT form) with the modulus +/// bit-length check listed in the module docs' `# Key validation`, and a distinct type so that it +/// cannot sign (see `# Key separation`). +/// +/// # Encoding +/// +/// `KEMPrivateKey::encode`/`from_bytes` (implemented per size, e.g. for +/// `crate::rsa_2048::RSA2048KEMPrivateKey`) use [`RsaPrivateKey`]'s layout, +/// `p || q || dP || dQ || qInv`, unchanged. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct RsaKEMPrivateKey(pub(crate) RsaPrivateKey); + +impl RsaKEMPrivateKey { + /// Builds a private key from its CRT components. Returns + /// `Err(`[`KEMError::DecodingError`]`)` in the cases [`RsaPrivateKey::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: &[u64; HALF], + q: &[u64; HALF], + d_p: &[u64; HALF], + d_q: &[u64; HALF], + q_inv: &[u64; HALF], + ) -> Result { + Self::from_rsa_key( + RsaPrivateKey::from_crt_components(p, q, d_p, d_q, q_inv).map_err(kem_error)?, + ) + } + + /// As [`RsaKEMPublicKey::from_rsa_key`], for the private half. + pub(crate) fn from_rsa_key(sk: RsaPrivateKey) -> 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`. + pub fn n(&self) -> &[u64; L] { + self.0.n() + } +} + +/// RSASVE (SP 800-56B Rev. 2 §7.2.1) at one modulus size, as a +/// [`KEMEncapsulator`]/[`KEMDecapsulator`]. Each size module names its own instantiation (e.g. +/// `crate::rsa_2048::RSASVE`), along with that size's `keygen`/`keygen_from_rng` as inherent +/// associated functions, which is where the KEM traits' docs put key generation. +/// +/// `L`/`L2`/`L21`/`HALF`/`HALF2`/`HALF21` are the widths the rest of this crate threads through +/// `rsa_core` (see [`crate::modexp`]). `N_BYTES = 8 * L` is `nLen`, which is both the ciphertext +/// length and the shared-secret length. `SECURITY_BITS` is the modulus's SP 800-57 Part 1 +/// security strength, the same value that size's `keygen_from_rng` demands of its RNG. `encaps_rng` +/// demands it too, and the shared secret is labelled with it. +/// +/// Uninhabited: every operation is an associated function, as with the other KEMs in this +/// workspace. +#[allow(non_camel_case_types)] +pub struct RSASVE< + const L: usize, + const L2: usize, + const L21: usize, + const HALF: usize, + const HALF2: usize, + const HALF21: usize, + const N_BYTES: usize, + const SECURITY_BITS: usize, +> { + _widths: PhantomData<[u64; L]>, +} + +impl< + const L: usize, + const L2: usize, + const L21: usize, + const HALF: usize, + const HALF2: usize, + const HALF21: usize, + const N_BYTES: usize, + const SECURITY_BITS: usize, + const PK_LEN: usize, +> KEMEncapsulator, PK_LEN, N_BYTES, N_BYTES> + for RSASVE +where + RsaKEMPublicKey: KEMPublicKey, +{ + /// RSASVE.GENERATE, drawing `Z` from the library's default OS-backed RNG. See + /// [`Self::encaps_rng`]. + fn encaps(pk: &RsaKEMPublicKey) -> Result<(KeyMaterial, [u8; N_BYTES]), KEMError> { + Self::encaps_rng(pk, &mut DefaultRNG::default()) + } + + /// RSASVE.GENERATE((n, e)) (SP 800-56B Rev. 2 §7.2.1.2), drawing `Z` from `rng`. Returns + /// `(Z, C)`: the secret value as a [`KeyMaterial`] of type + /// [`KeyType::CryptographicRandom`] at the modulus's security strength, and the ciphertext. + /// + /// Errors: `RNGError(SecurityStrengthInsufficientForAlgorithm)` if `rng` is weaker than the + /// modulus (§5.3: an RBG generating `Z` "shall be instantiated to support a security strength + /// that is equal to or greater than the security strength associated with the RSA modulus + /// length"), + /// `RNGError` if `rng` fails, and `GenericError` if [`MAX_GENERATE_ATTEMPTS`] draws all fall + /// outside `(1, n - 1)`, which a working RNG does not do (see that constant). + // `Z`, `C`: SP 800-56B's own names (see QUALITY_AND_STYLE.md's naming exception). + #[allow(non_snake_case)] + fn encaps_rng( + pk: &RsaKEMPublicKey, + rng: &mut dyn RNG, + ) -> Result<(KeyMaterial, [u8; N_BYTES]), KEMError> { + debug_assert_eq!(N_BYTES, 8 * L, "RSASVE needs N_BYTES == 8 * L"); + if rng.security_strength() < SecurityStrength::from_bits(SECURITY_BITS) { + return Err(KEMError::RNGError(RNGError::SecurityStrengthInsufficientForAlgorithm)); + } + + // Step 1: "nLen = len(n)/8, the byte length of the modulus n" -- N_BYTES, since + // `RsaKEMPublicKey` guarantees `n` is exactly `8 * N_BYTES` bits. + + // `Z` and `z` are held in `Secret` so that they are scrubbed on every exit, including + // the error ones: §7.2.1.2's closing paragraph requires this routine to "destroy any + // locally stored portions of Z and z". + let mut Z = Secret::<[u8; N_BYTES]>::new(); + let mut z = Secret::<[u64; L]>::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; + // Step 2.a: "Using the RBG ..., generate Z, a byte string of nLen bytes." + rng.next_bytes_out(&mut *Z)?; + // Step 2.b: "z = BS2I(Z, nLen)." + *z = limbs_from_be_bytes::(&Z); + // Step 2.c: "If z does not satisfy 1 < z < (n – 1), then go to step 2a." + if in_open_range(&z, pk.n()) { + break; + } + } + + // Step 3.a: "c = RSAEP((n, e), z)". RSAEP's own step 1 range check (§7.1.1, "1 < m < + // (n – 1)") is the one step 2.c has just ensured, so it is not repeated: `public_exp` is + // RSAEP's step 2, `c = z^e mod n`. + let c = public_exp::(&pk.0, &z); + // Step 3.b: "C = I2BS(c, nLen)." + let C = be_bytes_from_limbs::(&c); + + // Step 4: "Output the string Z as the secret value, and the ciphertext C." + let mut ss = KeyMaterial::::from_bytes_as_type(&*Z, KeyType::CryptographicRandom)?; + do_hazardous_operations(&mut ss, |ss| { + ss.set_security_strength(SecurityStrength::from_bits(SECURITY_BITS)) + })?; + Ok((ss, C)) + } +} + +impl< + const L: usize, + const L2: usize, + const L21: usize, + const HALF: usize, + const HALF2: usize, + const HALF21: usize, + const N_BYTES: usize, + const SECURITY_BITS: usize, + const SK_LEN: usize, +> KEMDecapsulator, SK_LEN, N_BYTES, N_BYTES> + for RSASVE +where + RsaKEMPrivateKey: KEMPrivateKey, +{ + /// RSASVE.RECOVER((n, d), C) (SP 800-56B Rev. 2 §7.2.1.3), with the private key in CRT form + /// (§7.1.2.3's RSADP). Returns `Z` as a [`KeyMaterial`] of type + /// [`KeyType::CryptographicRandom`] at the modulus's security strength, matching what + /// [`KEMEncapsulator::encaps_rng`] returned to the other party. + /// + /// Errors: `LengthError` if `ct` is not `nLen` bytes long (step 2), and `DecapsulationFailed` + /// if RSADP finds the ciphertext out of range (step 3.c). §7.2.1.3 calls both "an indication + /// of a decryption error". They are kept as separate variants because every KEM in this workspace reports a + /// wrong-length ciphertext as `LengthError`, which `bouncycastle_core_test_framework`'s KEM + /// suite checks. A ciphertext that is in range but was never produced by `encaps` is *not* + /// detected. RSASVE has no redundancy to check, so such a ciphertext just recovers a different + /// `Z` (see the crate docs' `# Security Considerations`). + #[allow(non_snake_case)] + fn decaps(sk: &RsaKEMPrivateKey, ct: &[u8]) -> Result, KEMError> { + debug_assert_eq!(N_BYTES, 8 * L, "RSASVE needs N_BYTES == 8 * L"); + // Step 1: "nLen = len(n)/8" -- N_BYTES, as in `encaps_rng`. + + // Step 2: "If the length of the ciphertext C is not nLen bytes in length, output an + // indication of a decryption error". + let C: &[u8; N_BYTES] = ct + .try_into() + .map_err(|_| KEMError::LengthError("RSASVE ciphertext must be exactly nLen bytes"))?; + + // Step 3.a: "c = BS2I(C)." + let c = limbs_from_be_bytes::(C); + + // Step 3.b/3.c: "z = RSADP((n, d), c)", and "If RSADP indicates that the ciphertext is + // out of range, output an indication of a decryption error". This is RSADP's step 1 + // (§7.1.2.3, "If the ciphertext c does not satisfy 1 < c < (n – 1) ..."), checked here + // rather than inside a separate RSADP function, and `crt_exp` is its steps 2-5 (`mp = + // c^dP mod p`, `mq = c^dQ mod q`, `h = ((mp − mq) × qInv) mod p`, `m = mq + q × h`). + // `c` is the public ciphertext, so the range check need not be constant-time, although + // it is. + if !in_open_range(&c, sk.n()) { + return Err(KEMError::DecapsulationFailed); + } + let mut z = Secret::<[u64; L]>::new(); + *z = crt_exp::(&sk.0, &c); + + // Step 3.d: "Z = I2BS(z, nLen)." + let mut Z = Secret::<[u8; N_BYTES]>::new(); + *Z = be_bytes_from_limbs::(&z); + + // Step 4: "Output the string Z as the secret value (i.e., the shared secret)". + let mut ss = KeyMaterial::::from_bytes_as_type(&*Z, KeyType::CryptographicRandom)?; + do_hazardous_operations(&mut ss, |ss| { + ss.set_security_strength(SecurityStrength::from_bits(SECURITY_BITS)) + })?; + Ok(ss) + } +} + +/// Wraps a size module's signature-typed `keygen_from_rng` result as a KEM key pair, applying +/// the KEM key types' checks. These always pass for this crate's own keys, which have `e = 65537` +/// and an `n` of exactly `nlen` bits by construction (see [`crate::keygen`]). +pub(crate) fn keygen_from( + pair: Result<(RsaPublicKey, RsaPrivateKey), SignatureError>, +) -> Result<(RsaKEMPublicKey, RsaKEMPrivateKey), KEMError> { + let (pk, sk) = pair.map_err(kem_error)?; + Ok((RsaKEMPublicKey::from_rsa_key(pk)?, RsaKEMPrivateKey::from_rsa_key(sk)?)) +} + +/// Decodes [`RsaPrivateKey`]'s raw layout into an [`RsaKEMPrivateKey`], for the per-size +/// `KEMPrivateKey::from_bytes` impls, which reject a wrong-length slice before calling this. +pub(crate) fn private_key_from_bytes< + const L: usize, + const HALF: usize, + const HALF_BYTES: usize, + const SK_LEN: usize, +>( + bytes: &[u8; SK_LEN], +) -> Result, KEMError> { + RsaKEMPrivateKey::from_rsa_key( + RsaPrivateKey::from_bytes_raw::(bytes).map_err(kem_error)?, + ) +} + +/// Decodes [`RsaPublicKey`]'s raw layout into an [`RsaKEMPublicKey`], for the per-size +/// `KEMPublicKey::from_bytes` impls, which reject a wrong-length slice before calling this. +pub(crate) fn public_key_from_bytes( + bytes: &[u8; PK_LEN], +) -> Result, KEMError> { + RsaKEMPublicKey::from_rsa_key( + RsaPublicKey::from_bytes_raw::(bytes).map_err(kem_error)?, + ) +} diff --git a/crypto/rsa/tests/rsasve_tests.rs b/crypto/rsa/tests/rsasve_tests.rs new file mode 100644 index 00000000..3dd5461b --- /dev/null +++ b/crypto/rsa/tests/rsasve_tests.rs @@ -0,0 +1,619 @@ +//! 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_rng` 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, RNGError}; +use bouncycastle_core::key_material::{KeyMaterialTrait, KeyType}; +use bouncycastle_core::security_strength::SecurityStrength; +use bouncycastle_core::traits::{KEMDecapsulator, KEMEncapsulator, KEMPrivateKey, KEMPublicKey}; +use bouncycastle_core_test_framework::FixedSeedRNG; +use bouncycastle_core_test_framework::kem::{TestFrameworkKEM, TestFrameworkKEMKeys}; +use bouncycastle_hex::decode as hex_decode; +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 { + let mut rng = FixedSeedRNG::new(bytes); + rng.set_security_strength(strength); + rng +} + +macro_rules! rsasve_suite { + ($module:ident, $size:ident, $bits:literal, $L:literal, $HALF:literal, $strength:expr, $weaker:expr) => { + mod $module { + use super::*; + use bouncycastle_rsa::$size::{CT_LEN, PK_LEN, RSASVE, SK_LEN, SS_LEN}; + + type PK = bouncycastle_rsa::rsasve::RsaKEMPublicKey<$L>; + type SK = bouncycastle_rsa::rsasve::RsaKEMPrivateKey<$L, $HALF>; + + 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::<$HALF>(v[p].as_str().unwrap()), + &limbs::<$HALF>(v[q].as_str().unwrap()), + &limbs::<$HALF>(v[dp].as_str().unwrap()), + &limbs::<$HALF>(v[dq].as_str().unwrap()), + &limbs::<$HALF>(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::<$L>(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::( + 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` is the wrapped signature key type's, unchanged. + let inner = bouncycastle_rsa::keys::RsaPublicKey::<$L>::new(pk.n(), 65537).unwrap(); + assert_eq!(format!("{pk}"), format!("{inner}")); + } + + /// OpenSSL encapsulated; this crate decapsulates. And the other way round: fed + /// OpenSSL's `Z` as its RNG output, `encaps_rng` 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 = RSASVE::decaps(&sk, &c).unwrap(); + assert_eq!(ss.ref_to_bytes(), &z[..]); + + let (ss, ct) = + RSASVE::encaps_rng(&pk, &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) = RSASVE::encaps(&pk).unwrap(); + assert_eq!(ss.key_len(), SS_LEN); + assert_eq!(ss.key_type(), KeyType::CryptographicRandom); + assert_eq!(ss.security_strength(), $strength); + let ss2 = RSASVE::decaps(&sk, &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_rng_accepts_exactly_the_modulus_strength_and_rejects_below_it() { + let (pk, _) = openssl_keypair().unwrap(); + assert!( + RSASVE::encaps_rng(&pk, &mut rng_emitting([0x5Au8; CT_LEN], $strength)).is_ok() + ); + assert!(matches!( + RSASVE::encaps_rng(&pk, &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) = RSASVE::encaps_rng( + &pk, + &mut rng_emitting(stream, SecurityStrength::_256bit), + ) + .unwrap(); + assert_eq!(ss.ref_to_bytes(), &good[..]); + assert_eq!(RSASVE::decaps(&sk, &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!( + RSASVE::encaps_rng( + &pk, + &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 mut rng = + FixedSeedRNG::<{ ATTEMPTS * CT_LEN }>::new(stream.try_into().unwrap()); + let (ss, _) = RSASVE::encaps_rng(&pk, &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!( + RSASVE::decaps(&sk, &bad), + Err(KEMError::DecapsulationFailed) + )); + } + for good in [two, n_minus_2] { + assert!(RSASVE::decaps(&sk, &good).is_ok()); + } + } + + #[test] + fn recover_rejects_a_wrong_length_ciphertext() { + let (_, sk) = openssl_keypair().unwrap(); + for len in [0, CT_LEN - 1, CT_LEN + 1] { + assert!(matches!( + RSASVE::decaps(&sk, &vec![0x5Au8; len]), + Err(KEMError::LengthError(_)) + )); + } + } + + #[test] + fn public_key_validation() { + let v = openssl_vectors(); + let n = limbs::<$L>(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; + short_n[$L - 1] &= !(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(KEMError::DecodingError(_)))); + let mut bytes = pk.encode(); + bytes[PK_LEN - 4..].copy_from_slice(&3u32.to_be_bytes()); + assert!(matches!(PK::from_bytes(&bytes), Err(KEMError::DecodingError(_)))); + } + + #[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::<$HALF>(v["p"].as_str().unwrap()), + &limbs::<$HALF>(v["p"].as_str().unwrap()), + &limbs::<$HALF>(v["dP"].as_str().unwrap()), + &limbs::<$HALF>(v["dP"].as_str().unwrap()), + &limbs::<$HALF>(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; $HALF]; + p[0] = 3; + let mut q = [0u64; $HALF]; + q[0] = 5; + let mut small = [0u64; $HALF]; + 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[..8 * $HALF].fill(0); // p = 0, which is even + assert!(matches!(SK::from_bytes(&bytes), Err(KEMError::DecodingError(_)))); + } + } + }; +} + +rsasve_suite!( + rsa_2048_rsasve, + rsa_2048, + 2048, + 32, + 16, + SecurityStrength::_112bit, + SecurityStrength::None +); +rsasve_suite!( + rsa_3072_rsasve, + rsa_3072, + 3072, + 48, + 24, + SecurityStrength::_128bit, + SecurityStrength::_112bit +); +rsasve_suite!( + rsa_4096_rsasve, + rsa_4096, + 4096, + 64, + 32, + SecurityStrength::_128bit, + SecurityStrength::_112bit +); +rsasve_suite!( + rsa_8192_rsasve, + rsa_8192, + 8192, + 128, + 64, + 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_rng` reproduces `serverC` from `serverZ`. +#[test] +fn acvp_kas_ifc_ssc_kas1_2048() { + use bouncycastle_rsa::rsa_2048::{CT_LEN, RSA2048KEMPrivateKey, RSA2048KEMPublicKey, RSASVE}; + 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 = RSASVE::decaps(&sk, &c).unwrap(); + if t["testPassed"].as_bool().unwrap() { + assert_eq!(recovered.ref_to_bytes(), &z[..], "tcId {}", t["tcId"]); + let (_, ct) = + RSASVE::encaps_rng(&pk, &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, RSASVE}; + 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 = RSASVE::decaps(sk, &c).unwrap(); + if ok { + assert_eq!(recovered.ref_to_bytes(), &z[..], "tcId {}", t["tcId"]); + let (_, ct) = + RSASVE::encaps_rng(pk, &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, $bits:literal, $L:literal, $HALF:literal) => { + #[test] + fn $name() { + use bouncycastle_rsa::$size::{CT_LEN, RSASVE}; + type SK = bouncycastle_rsa::rsasve::RsaKEMPrivateKey<$L, $HALF>; + 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!( + RSASVE::decaps(&sk, &ct).unwrap().ref_to_bytes(), + &pt[..], + "tcId {}", + t["tcId"] + ); + passed += 1; + } else { + assert!( + matches!(RSASVE::decaps(&sk, &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, 2048, 32, 16); +acvp_rsadp!(acvp_rsadp_crt_3072, rsa_3072, 3072, 48, 24); +acvp_rsadp!(acvp_rsadp_crt_4096, rsa_4096, 4096, 64, 32); + +/// `RSASVE::keygen`'s pairs are usable KEM keys (a genuine generation, at the smallest size +/// only: key generation is the slow part), and `keygen_from_rng` enforces the RNG strength. +#[test] +fn keygen_produces_working_kem_keys() { + use bouncycastle_rsa::rsa_2048::RSASVE; + let (pk, sk) = RSASVE::keygen().unwrap(); + assert_eq!(pk.e(), 65537); + assert_eq!(pk.n(), sk.n()); + let (ss, ct) = RSASVE::encaps(&pk).unwrap(); + assert_eq!(RSASVE::decaps(&sk, &ct).unwrap(), ss); + + // A stuck RNG exhausts FIPS 186-5 A.1.3's candidate limit (see `keygen_tests.rs`'s + // `keygen_from_rng_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_from_rng(&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_from_rng(&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().unwrap(); + assert_eq!(pk.e(), 65537); + assert_eq!(pk.n(), sk.n()); + let (ss, ct) = RSASVE::encaps(&pk).unwrap(); + assert_eq!(RSASVE::decaps(&sk, &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/mem_usage_benches/src/bench_rsa_mem_usage.rs b/mem_usage_benches/src/bench_rsa_mem_usage.rs index 0f2ff629..17c1d11c 100644 --- a/mem_usage_benches/src/bench_rsa_mem_usage.rs +++ b/mem_usage_benches/src/bench_rsa_mem_usage.rs @@ -30,8 +30,10 @@ #![allow(dead_code)] #![allow(unused_imports)] +use bouncycastle::core::key_material::KeyMaterialTrait; use bouncycastle::core::traits::{ - SignaturePrivateKey, SignaturePublicKey, SignatureVerifier, Signer, + KEMDecapsulator, KEMEncapsulator, KEMPrivateKey, KEMPublicKey, SignaturePrivateKey, + SignaturePublicKey, SignatureVerifier, Signer, }; use bouncycastle::rsa::{rsa_1024, rsa_1536, rsa_2048, rsa_3072, rsa_4096, rsa_8192}; @@ -58,6 +60,16 @@ fn print_key_sizes() { 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"); @@ -65,6 +77,16 @@ fn print_key_sizes() { 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"); @@ -72,6 +94,16 @@ fn print_key_sizes() { 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"); @@ -79,6 +111,16 @@ fn print_key_sizes() { 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); } @@ -293,6 +335,52 @@ fn bench_8192_verify() { } } +/// 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 = rsa_2048::RSA2048PublicKey::new(sk.n(), 0x10001).unwrap(); + let pk = rsa_2048::RSA2048KEMPublicKey::from_bytes(&pk.encode()).unwrap(); + let (ss, ct) = rsa_2048::RSASVE::encaps(&pk).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().encode()).unwrap(); + let mut ct = [0x5Au8; rsa_2048::CT_LEN]; + ct[0] = 0x01; // well inside (1, n - 1) + let ss = rsa_2048::RSASVE::decaps(&sk, &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 = rsa_8192::RSA8192PublicKey::new(sk.n(), 0x10001).unwrap(); + let pk = rsa_8192::RSA8192KEMPublicKey::from_bytes(&pk.encode()).unwrap(); + let (ss, ct) = rsa_8192::RSASVE::encaps(&pk).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().encode()).unwrap(); + let mut ct = [0x5Au8; rsa_8192::CT_LEN]; + ct[0] = 0x01; // well inside (1, n - 1) + let ss = rsa_8192::RSASVE::decaps(&sk, &ct).unwrap(); + println!("{}", ss.key_len()); +} + fn main() { print_key_sizes() // bench_do_nothing() @@ -302,4 +390,8 @@ fn main() { // 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() } From 20af567e49cb866672ab986cb2b336dd3ceba5f1 Mon Sep 17 00:00:00 2001 From: David Hook Date: Sat, 10 Oct 2026 00:26:08 +1100 Subject: [PATCH 21/55] rsa: reject a signature representative more than 64 bits shorter than n in rsavp1 MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit RFC 8017 §5.2.2 accepts any s in [0, n - 1]. rsavp1 now also returns DecodingError("signature representative too small") when bitlen(s) <= bitlen(n) - 64, which a genuine signature trips with probability 2^-64; the trait verify_final paths fold it into SignatureVerificationFailed as they do for s >= n. rsasp1, crt_exp, public_exp and RSASVE are untouched. keygen's leading_zeros is made pub(crate) for the bit-length computation. Wycheproof's rsa_signature_{2048,3072}_sha{256,512} files each carry one "valid" SmallSignature vector, which Wycheproof's note says "may be a reason for a library to reject the signature"; those harnesses now expect rejection for that flag and count it separately. Documented in lib.rs's Security Considerations. Tests: verify_from_hash_lower_bound_on_the_representative, and a trait_verify_rejects_small_representative_and_malformed_signatures battery for PKCS#1 v1.5, PSS and PSS-SHAKE. cargo test -p bouncycastle-rsa: 250 passed, 0 failed, 4 ignored. Assisted-by: Claude:claude-mythos-5-1 Co-Authored-By: Claude Mythos 5.1 --- crypto/rsa/src/keygen.rs | 2 +- crypto/rsa/src/lib.rs | 4 ++ crypto/rsa/src/rsa_core.rs | 15 +++- ...rsa_2048_pkcs1_v1_5_sha384_sha512_tests.rs | 14 +++- crypto/rsa/tests/rsa_2048_pkcs1_v1_5_tests.rs | 71 ++++++++++++++++++- .../rsa/tests/rsa_2048_pss_shake128_tests.rs | 26 +++++++ crypto/rsa/tests/rsa_2048_pss_tests.rs | 26 +++++++ crypto/rsa/tests/rsa_3072_tests.rs | 17 ++++- 8 files changed, 169 insertions(+), 6 deletions(-) diff --git a/crypto/rsa/src/keygen.rs b/crypto/rsa/src/keygen.rs index bd158726..646a01ca 100644 --- a/crypto/rsa/src/keygen.rs +++ b/crypto/rsa/src/keygen.rs @@ -175,7 +175,7 @@ fn trailing_zeros(a: &[u64; N]) -> u32 { count } -fn leading_zeros(a: &[u64; N]) -> u32 { +pub(crate) fn leading_zeros(a: &[u64; N]) -> u32 { let mut count = 0; for limb in a.iter().rev() { if *limb == 0 { diff --git a/crypto/rsa/src/lib.rs b/crypto/rsa/src/lib.rs index c7d734e4..9a80f34a 100644 --- a/crypto/rsa/src/lib.rs +++ b/crypto/rsa/src/lib.rs @@ -264,6 +264,10 @@ //! 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`. +//! - **Verification rejects a signature representative more than 64 bits shorter than `n`.** +//! RFC 8017 §5.2.2 accepts any `s` in `[0, n - 1]`; this crate additionally reports `s` with +//! `bitlen(s) <= bitlen(n) - 64` as an invalid signature. A genuine signature trips this with +//! probability 2^-64. Wycheproof's `SmallSignature` vectors are therefore rejected by policy. //! - **`ctx` is accepted but ignored.** RSASSA-PKCS1-v1_5 and RSASSA-PSS (RFC 8017 §8) have no //! context-string input; `Signer`/`SignatureVerifier`'s `ctx` parameter is accepted for trait //! conformance and silently ignored, as `bouncycastle-ecdsa` does for ECDSA. A caller relying diff --git a/crypto/rsa/src/rsa_core.rs b/crypto/rsa/src/rsa_core.rs index 6d7f75c8..cbdf3cd7 100644 --- a/crypto/rsa/src/rsa_core.rs +++ b/crypto/rsa/src/rsa_core.rs @@ -10,6 +10,7 @@ //! `(r_i, d_i, t_i)` triplets): [`crate::keys::RsaPrivateKey`] has no representation for //! multi-prime RSA, so there is nothing here to extend to `u > 2`. +use crate::keygen::leading_zeros; use crate::keys::{RsaPrivateKey, RsaPublicKey}; use crate::modexp::{MontgomeryContext, mod_pow, mul_mod, reduce_wide, sub_mod}; use bouncycastle_core::errors::SignatureError; @@ -20,7 +21,8 @@ use bouncycastle_ec::nat; /// 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. +/// 'signature representative out of range'") is `Err(`[`SignatureError::DecodingError`]`)` here, +/// as is a representative whose bit length is at most 64 below `n`'s. pub(crate) fn rsavp1( pk: &RsaPublicKey, s: &[u64; L], @@ -28,9 +30,20 @@ pub(crate) fn rsavp1( if nat::sub(s, pk.n()).1 != 1 { return Err(SignatureError::DecodingError("signature representative out of range")); } + // A genuine signature is this small with probability 2^-64; rejecting it stops a pre-chosen + // value being matched to a key computed afterwards. + if bit_len(s) + 64 <= bit_len(pk.n()) { + return Err(SignatureError::DecodingError("signature representative too small")); + } Ok(public_exp::(pk, s)) } +/// The number of significant bits in `x` (`0` for zero). Variable-time, used only on public +/// values. +fn bit_len(x: &[u64; L]) -> u32 { + 64 * L as u32 - leading_zeros(x) +} + /// `x^e mod n` under the public key, with no range check of its own: RSAVP1's step 2 (RFC 8017 /// §5.2.2), shared with any other primitive that exponentiates by `e` -- each caller applies its /// own specification's range check on `x` first, since those differ (RFC 8017 §5.2.2 step 1 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 index 70fea371..922954dd 100644 --- 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 @@ -118,6 +118,7 @@ fn run_verify_vectors( expected_sha: &str, expected_num_tests: usize, expected_num_valid: usize, + expected_num_small_signature: usize, expected_num_invalid: usize, ) { let doc: Value = serde_json::from_str(&get_test_data(filename)).expect("valid JSON"); @@ -126,6 +127,7 @@ fn run_verify_vectors( let mut num_valid = 0usize; let mut num_invalid = 0usize; let mut num_missing_null = 0usize; + let mut num_small_signature = 0usize; for group in doc["testGroups"].as_array().unwrap() { assert_eq!(group["sha"], expected_sha); @@ -150,6 +152,13 @@ fn run_verify_vectors( let verified = verify(&pk, &msg, &sig); match test["result"].as_str().unwrap() { + // Wycheproof's `SmallSignature` is a genuine `e = 3` signature whose representative + // is far below `n`, which RSAVP1's lower bound rejects by policy (see + // `rsa_core::rsavp1`). + "valid" if flags.contains(&"SmallSignature") => { + assert!(!verified, "tcId {tc_id}: a small representative must be rejected"); + num_small_signature += 1; + } "valid" => { assert!(verified, "tcId {tc_id}: expected valid, got invalid"); num_valid += 1; @@ -174,6 +183,7 @@ fn run_verify_vectors( assert_eq!(num_tests, expected_num_tests); assert_eq!(num_missing_null, 1); + assert_eq!(num_small_signature, expected_num_small_signature, "for {filename}"); assert_eq!(num_valid, expected_num_valid); assert_eq!(num_invalid, expected_num_invalid); } @@ -186,6 +196,7 @@ fn rsa_signature_sha384_wycheproof_vectors() { "SHA-384", 258, 7, + 0, 250, ); } @@ -197,7 +208,8 @@ fn rsa_signature_sha512_wycheproof_vectors() { |pk, msg, sig| RSASSA_PKCS1_v1_5_SHA512::verify(pk, msg, None, sig).is_ok(), "SHA-512", 259, - 8, + 7, + 1, 250, ); } diff --git a/crypto/rsa/tests/rsa_2048_pkcs1_v1_5_tests.rs b/crypto/rsa/tests/rsa_2048_pkcs1_v1_5_tests.rs index 78bc53bb..acd07702 100644 --- a/crypto/rsa/tests/rsa_2048_pkcs1_v1_5_tests.rs +++ b/crypto/rsa/tests/rsa_2048_pkcs1_v1_5_tests.rs @@ -252,6 +252,7 @@ fn rsa_signature_sha256_all_groups() { let mut num_valid = 0usize; let mut num_invalid = 0usize; let mut num_wrong_length = 0usize; + let mut num_small_signature = 0usize; for group in doc["testGroups"].as_array().unwrap() { let n: [u64; 32] = limbs_from_hex(group["publicKey"]["modulus"].as_str().unwrap()); @@ -265,7 +266,20 @@ fn rsa_signature_sha256_all_groups() { let msg = hex_decode(test["msg"].as_str().unwrap()).unwrap(); let sig = hex_decode(test["sig"].as_str().unwrap()).unwrap(); let result = RSASSA_PKCS1_v1_5_SHA256::verify(&pk, &msg, None, &sig); + let flags: Vec<&str> = + test["flags"].as_array().unwrap().iter().map(|f| f.as_str().unwrap()).collect(); match test["result"].as_str().unwrap() { + // Wycheproof's `SmallSignature` is a genuine `e = 3` signature whose representative + // is far below `n`, which RSAVP1's lower bound rejects by policy (see + // `rsa_core::rsavp1`). + "valid" if flags.contains(&"SmallSignature") => { + assert!( + matches!(result, Err(SignatureError::SignatureVerificationFailed)), + "tcId {tc_id}: a small representative must be 'invalid signature', got \ + {result:?}" + ); + num_small_signature += 1; + } // "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:?}")); @@ -290,7 +304,8 @@ fn rsa_signature_sha256_all_groups() { } assert_eq!(num_tests, 259); - assert_eq!(num_valid, 10); + assert_eq!(num_valid, 9); + assert_eq!(num_small_signature, 1); assert_eq!(num_invalid, 249); assert!(num_wrong_length > 0, "the file must contain wrong-length signatures to exercise"); } @@ -317,3 +332,57 @@ fn trait_verify_reports_out_of_range_representative_as_invalid_signature() { Err(SignatureError::SignatureVerificationFailed) )); } + +/// RSAVP1's lower bound on the representative (see `rsa_core::rsavp1`): exactly `2^(2048 - 64)` +/// gets past it and fails only at the padding check, while `2^(2048 - 64) - 1` is the same +/// `DecodingError` as the out-of-range case above. +#[test] +fn verify_from_hash_lower_bound_on_the_representative() { + let (pk, _) = fixed_keypair().unwrap(); + let mut digest = [0u8; 32]; + SHA256::default().hash_out(b"msg", &mut digest); + + let mut at_bound = [0u8; SIG_LEN]; + at_bound[7] = 0x01; + assert!(matches!( + rsassa_pkcs1_v1_5::verify_from_hash::( + &pk, &digest, &at_bound + ), + Err(SignatureError::SignatureVerificationFailed) + )); + + let mut below_bound = [0xffu8; SIG_LEN]; + below_bound[..8].fill(0); + assert!(matches!( + rsassa_pkcs1_v1_5::verify_from_hash::( + &pk, &digest, &below_bound + ), + Err(SignatureError::DecodingError(_)) + )); +} + +/// Through the trait every malformed signature is `SignatureVerificationFailed`, never a panic or +/// another error: a representative with its top eight bytes zero (RSAVP1's lower bound), empty, +/// three bytes, all zero, one byte short and one byte long. A genuine signature still verifies. +#[test] +fn trait_verify_rejects_small_representative_and_malformed_signatures() { + let (pk, sk) = fixed_keypair().unwrap(); + let msg = b"msg"; + let mut small = [0xffu8; SIG_LEN]; + small[..8].fill(0); + let malformed: [&[u8]; 6] = + [&small, &[], &[0xff; 3], &[0; SIG_LEN], &[0xff; SIG_LEN - 1], &[0xff; SIG_LEN + 1]]; + for sig in malformed { + assert!( + matches!( + RSASSA_PKCS1_v1_5_SHA256::verify(&pk, msg, None, sig), + Err(SignatureError::SignatureVerificationFailed) + ), + "{}-byte signature", + sig.len() + ); + } + + let sig = RSASSA_PKCS1_v1_5_SHA256::sign(&sk, msg, None).unwrap(); + RSASSA_PKCS1_v1_5_SHA256::verify(&pk, msg, None, &sig).unwrap(); +} diff --git a/crypto/rsa/tests/rsa_2048_pss_shake128_tests.rs b/crypto/rsa/tests/rsa_2048_pss_shake128_tests.rs index 32d582e6..5fe654fe 100644 --- a/crypto/rsa/tests/rsa_2048_pss_shake128_tests.rs +++ b/crypto/rsa/tests/rsa_2048_pss_shake128_tests.rs @@ -306,3 +306,29 @@ fn sign_randomized_takes_the_salt_from_the_callers_rng() { RSASSA_PSS_SHAKE128::verify(&pk, msg, None, &b).unwrap(); assert!(RSASSA_PSS_SHAKE128::verify(&pk, b"other", None, &a).is_err()); } + +/// Through the trait every malformed signature is `SignatureVerificationFailed`, never a panic or +/// another error: a representative with its top eight bytes zero (RSAVP1's lower bound), empty, +/// three bytes, all zero, one byte short and one byte long. A genuine signature still verifies. +#[test] +fn trait_verify_rejects_small_representative_and_malformed_signatures() { + let (pk, sk) = fixed_keypair().unwrap(); + let msg = b"msg"; + let mut small = [0xffu8; SIG_LEN]; + small[..8].fill(0); + let malformed: [&[u8]; 6] = + [&small, &[], &[0xff; 3], &[0; SIG_LEN], &[0xff; SIG_LEN - 1], &[0xff; SIG_LEN + 1]]; + for sig in malformed { + assert!( + matches!( + RSASSA_PSS_SHAKE128::verify(&pk, msg, None, sig), + Err(SignatureError::SignatureVerificationFailed) + ), + "{}-byte signature", + sig.len() + ); + } + + let sig = sign_with_salt!(RSASSA_PSS_SHAKE128, &sk, msg, [0x42u8; 32]).unwrap(); + RSASSA_PSS_SHAKE128::verify(&pk, msg, None, &sig).unwrap(); +} diff --git a/crypto/rsa/tests/rsa_2048_pss_tests.rs b/crypto/rsa/tests/rsa_2048_pss_tests.rs index a55375f4..1aaa9b71 100644 --- a/crypto/rsa/tests/rsa_2048_pss_tests.rs +++ b/crypto/rsa/tests/rsa_2048_pss_tests.rs @@ -309,3 +309,29 @@ fn sign_randomized_takes_the_salt_from_the_callers_rng() { RSASSA_PSS_SHA256::verify(&pk, msg, None, &b).unwrap(); assert!(RSASSA_PSS_SHA256::verify(&pk, b"other", None, &a).is_err()); } + +/// Through the trait every malformed signature is `SignatureVerificationFailed`, never a panic or +/// another error: a representative with its top eight bytes zero (RSAVP1's lower bound), empty, +/// three bytes, all zero, one byte short and one byte long. A genuine signature still verifies. +#[test] +fn trait_verify_rejects_small_representative_and_malformed_signatures() { + let (pk, sk) = fixed_keypair().unwrap(); + let msg = b"msg"; + let mut small = [0xffu8; SIG_LEN]; + small[..8].fill(0); + let malformed: [&[u8]; 6] = + [&small, &[], &[0xff; 3], &[0; SIG_LEN], &[0xff; SIG_LEN - 1], &[0xff; SIG_LEN + 1]]; + for sig in malformed { + assert!( + matches!( + RSASSA_PSS_SHA256::verify(&pk, msg, None, sig), + Err(SignatureError::SignatureVerificationFailed) + ), + "{}-byte signature", + sig.len() + ); + } + + let sig = sign_with_salt!(RSASSA_PSS_SHA256, &sk, msg, [0x42u8; 32]).unwrap(); + RSASSA_PSS_SHA256::verify(&pk, msg, None, &sig).unwrap(); +} diff --git a/crypto/rsa/tests/rsa_3072_tests.rs b/crypto/rsa/tests/rsa_3072_tests.rs index 92ca507f..2ebdd81e 100644 --- a/crypto/rsa/tests/rsa_3072_tests.rs +++ b/crypto/rsa/tests/rsa_3072_tests.rs @@ -237,12 +237,14 @@ fn run_pkcs1_v1_5_verify_vectors( verify: impl Fn(&RSA3072PublicKey, &[u8], &[u8; 384]) -> bool, expected_sha: &str, expected_valid: usize, + expected_small_signature: 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; + let mut num_small_signature = 0usize; for group in doc["testGroups"].as_array().unwrap() { assert_eq!(group["sha"], expected_sha); @@ -265,6 +267,13 @@ fn run_pkcs1_v1_5_verify_vectors( }; let verified = verify(&pk, &msg, &sig); match test["result"].as_str().unwrap() { + // Wycheproof's `SmallSignature` is a genuine `e = 3` signature whose representative + // is far below `n`, which RSAVP1's lower bound rejects by policy (see + // `rsa_core::rsavp1`). + "valid" if flags.contains(&"SmallSignature") => { + assert!(!verified, "tcId {tc_id}: a small representative must be rejected"); + num_small_signature += 1; + } "valid" => { assert!(verified, "tcId {tc_id}: expected valid, got invalid"); num_valid += 1; @@ -283,6 +292,7 @@ fn run_pkcs1_v1_5_verify_vectors( } } assert_eq!(num_missing_null, 1); + assert_eq!(num_small_signature, expected_small_signature, "for {filename}"); assert_eq!(num_valid, expected_valid, "for {filename}"); assert_eq!(num_invalid, expected_invalid, "for {filename}"); } @@ -293,7 +303,8 @@ fn rsa_signature_3072_sha256_wycheproof_vectors() { "rsa_signature_3072_sha256_test.json", |pk, msg, sig| RSASSA_PKCS1_v1_5_SHA256::verify(pk, msg, None, sig).is_ok(), "SHA-256", - 8, + 7, + 1, 250, ); } @@ -309,6 +320,7 @@ fn rsa_signature_3072_sha384_wycheproof_vectors() { |pk, msg, sig| RSASSA_PKCS1_v1_5_SHA384::verify(pk, msg, None, sig).is_ok(), "SHA-384", 7, + 0, 251, ); } @@ -323,7 +335,8 @@ fn rsa_signature_3072_sha512_wycheproof_vectors() { "rsa_signature_3072_sha512_test.json", |pk, msg, sig| RSASSA_PKCS1_v1_5_SHA512::verify(pk, msg, None, sig).is_ok(), "SHA-512", - 8, + 7, + 1, 251, ); } From eb95dce7f06ce4ae9e3d4f39f5b18acb393cdf69 Mon Sep 17 00:00:00 2001 From: David Hook Date: Sat, 10 Oct 2026 14:06:47 +1100 Subject: [PATCH 22/55] Revert "rsa: reject a signature representative more than 64 bits shorter than n in rsavp1" MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit This reverts commit d5f1367590f57429e133dad77c053dd7839ee305. A lower bound on the representative only narrows which keys can be built around a fixed value; it is not a property RSA verification can enforce, and the binding of a signature to a key belongs to the protocol layer. Restores RFC 8017 §5.2.2's range check as the only check on s, and the Wycheproof harnesses' original expectations. Co-Authored-By: Claude Mythos 5.1 --- crypto/rsa/src/keygen.rs | 2 +- crypto/rsa/src/lib.rs | 4 -- crypto/rsa/src/rsa_core.rs | 15 +--- ...rsa_2048_pkcs1_v1_5_sha384_sha512_tests.rs | 14 +--- crypto/rsa/tests/rsa_2048_pkcs1_v1_5_tests.rs | 71 +------------------ .../rsa/tests/rsa_2048_pss_shake128_tests.rs | 26 ------- crypto/rsa/tests/rsa_2048_pss_tests.rs | 26 ------- crypto/rsa/tests/rsa_3072_tests.rs | 17 +---- 8 files changed, 6 insertions(+), 169 deletions(-) diff --git a/crypto/rsa/src/keygen.rs b/crypto/rsa/src/keygen.rs index 646a01ca..bd158726 100644 --- a/crypto/rsa/src/keygen.rs +++ b/crypto/rsa/src/keygen.rs @@ -175,7 +175,7 @@ fn trailing_zeros(a: &[u64; N]) -> u32 { count } -pub(crate) fn leading_zeros(a: &[u64; N]) -> u32 { +fn leading_zeros(a: &[u64; N]) -> u32 { let mut count = 0; for limb in a.iter().rev() { if *limb == 0 { diff --git a/crypto/rsa/src/lib.rs b/crypto/rsa/src/lib.rs index 9a80f34a..c7d734e4 100644 --- a/crypto/rsa/src/lib.rs +++ b/crypto/rsa/src/lib.rs @@ -264,10 +264,6 @@ //! 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`. -//! - **Verification rejects a signature representative more than 64 bits shorter than `n`.** -//! RFC 8017 §5.2.2 accepts any `s` in `[0, n - 1]`; this crate additionally reports `s` with -//! `bitlen(s) <= bitlen(n) - 64` as an invalid signature. A genuine signature trips this with -//! probability 2^-64. Wycheproof's `SmallSignature` vectors are therefore rejected by policy. //! - **`ctx` is accepted but ignored.** RSASSA-PKCS1-v1_5 and RSASSA-PSS (RFC 8017 §8) have no //! context-string input; `Signer`/`SignatureVerifier`'s `ctx` parameter is accepted for trait //! conformance and silently ignored, as `bouncycastle-ecdsa` does for ECDSA. A caller relying diff --git a/crypto/rsa/src/rsa_core.rs b/crypto/rsa/src/rsa_core.rs index cbdf3cd7..6d7f75c8 100644 --- a/crypto/rsa/src/rsa_core.rs +++ b/crypto/rsa/src/rsa_core.rs @@ -10,7 +10,6 @@ //! `(r_i, d_i, t_i)` triplets): [`crate::keys::RsaPrivateKey`] has no representation for //! multi-prime RSA, so there is nothing here to extend to `u > 2`. -use crate::keygen::leading_zeros; use crate::keys::{RsaPrivateKey, RsaPublicKey}; use crate::modexp::{MontgomeryContext, mod_pow, mul_mod, reduce_wide, sub_mod}; use bouncycastle_core::errors::SignatureError; @@ -21,8 +20,7 @@ use bouncycastle_ec::nat; /// 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, -/// as is a representative whose bit length is at most 64 below `n`'s. +/// 'signature representative out of range'") is `Err(`[`SignatureError::DecodingError`]`)` here. pub(crate) fn rsavp1( pk: &RsaPublicKey, s: &[u64; L], @@ -30,20 +28,9 @@ pub(crate) fn rsavp1( if nat::sub(s, pk.n()).1 != 1 { return Err(SignatureError::DecodingError("signature representative out of range")); } - // A genuine signature is this small with probability 2^-64; rejecting it stops a pre-chosen - // value being matched to a key computed afterwards. - if bit_len(s) + 64 <= bit_len(pk.n()) { - return Err(SignatureError::DecodingError("signature representative too small")); - } Ok(public_exp::(pk, s)) } -/// The number of significant bits in `x` (`0` for zero). Variable-time, used only on public -/// values. -fn bit_len(x: &[u64; L]) -> u32 { - 64 * L as u32 - leading_zeros(x) -} - /// `x^e mod n` under the public key, with no range check of its own: RSAVP1's step 2 (RFC 8017 /// §5.2.2), shared with any other primitive that exponentiates by `e` -- each caller applies its /// own specification's range check on `x` first, since those differ (RFC 8017 §5.2.2 step 1 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 index 922954dd..70fea371 100644 --- 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 @@ -118,7 +118,6 @@ fn run_verify_vectors( expected_sha: &str, expected_num_tests: usize, expected_num_valid: usize, - expected_num_small_signature: usize, expected_num_invalid: usize, ) { let doc: Value = serde_json::from_str(&get_test_data(filename)).expect("valid JSON"); @@ -127,7 +126,6 @@ fn run_verify_vectors( let mut num_valid = 0usize; let mut num_invalid = 0usize; let mut num_missing_null = 0usize; - let mut num_small_signature = 0usize; for group in doc["testGroups"].as_array().unwrap() { assert_eq!(group["sha"], expected_sha); @@ -152,13 +150,6 @@ fn run_verify_vectors( let verified = verify(&pk, &msg, &sig); match test["result"].as_str().unwrap() { - // Wycheproof's `SmallSignature` is a genuine `e = 3` signature whose representative - // is far below `n`, which RSAVP1's lower bound rejects by policy (see - // `rsa_core::rsavp1`). - "valid" if flags.contains(&"SmallSignature") => { - assert!(!verified, "tcId {tc_id}: a small representative must be rejected"); - num_small_signature += 1; - } "valid" => { assert!(verified, "tcId {tc_id}: expected valid, got invalid"); num_valid += 1; @@ -183,7 +174,6 @@ fn run_verify_vectors( assert_eq!(num_tests, expected_num_tests); assert_eq!(num_missing_null, 1); - assert_eq!(num_small_signature, expected_num_small_signature, "for {filename}"); assert_eq!(num_valid, expected_num_valid); assert_eq!(num_invalid, expected_num_invalid); } @@ -196,7 +186,6 @@ fn rsa_signature_sha384_wycheproof_vectors() { "SHA-384", 258, 7, - 0, 250, ); } @@ -208,8 +197,7 @@ fn rsa_signature_sha512_wycheproof_vectors() { |pk, msg, sig| RSASSA_PKCS1_v1_5_SHA512::verify(pk, msg, None, sig).is_ok(), "SHA-512", 259, - 7, - 1, + 8, 250, ); } diff --git a/crypto/rsa/tests/rsa_2048_pkcs1_v1_5_tests.rs b/crypto/rsa/tests/rsa_2048_pkcs1_v1_5_tests.rs index acd07702..78bc53bb 100644 --- a/crypto/rsa/tests/rsa_2048_pkcs1_v1_5_tests.rs +++ b/crypto/rsa/tests/rsa_2048_pkcs1_v1_5_tests.rs @@ -252,7 +252,6 @@ fn rsa_signature_sha256_all_groups() { let mut num_valid = 0usize; let mut num_invalid = 0usize; let mut num_wrong_length = 0usize; - let mut num_small_signature = 0usize; for group in doc["testGroups"].as_array().unwrap() { let n: [u64; 32] = limbs_from_hex(group["publicKey"]["modulus"].as_str().unwrap()); @@ -266,20 +265,7 @@ fn rsa_signature_sha256_all_groups() { let msg = hex_decode(test["msg"].as_str().unwrap()).unwrap(); let sig = hex_decode(test["sig"].as_str().unwrap()).unwrap(); let result = RSASSA_PKCS1_v1_5_SHA256::verify(&pk, &msg, None, &sig); - let flags: Vec<&str> = - test["flags"].as_array().unwrap().iter().map(|f| f.as_str().unwrap()).collect(); match test["result"].as_str().unwrap() { - // Wycheproof's `SmallSignature` is a genuine `e = 3` signature whose representative - // is far below `n`, which RSAVP1's lower bound rejects by policy (see - // `rsa_core::rsavp1`). - "valid" if flags.contains(&"SmallSignature") => { - assert!( - matches!(result, Err(SignatureError::SignatureVerificationFailed)), - "tcId {tc_id}: a small representative must be 'invalid signature', got \ - {result:?}" - ); - num_small_signature += 1; - } // "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:?}")); @@ -304,8 +290,7 @@ fn rsa_signature_sha256_all_groups() { } assert_eq!(num_tests, 259); - assert_eq!(num_valid, 9); - assert_eq!(num_small_signature, 1); + assert_eq!(num_valid, 10); assert_eq!(num_invalid, 249); assert!(num_wrong_length > 0, "the file must contain wrong-length signatures to exercise"); } @@ -332,57 +317,3 @@ fn trait_verify_reports_out_of_range_representative_as_invalid_signature() { Err(SignatureError::SignatureVerificationFailed) )); } - -/// RSAVP1's lower bound on the representative (see `rsa_core::rsavp1`): exactly `2^(2048 - 64)` -/// gets past it and fails only at the padding check, while `2^(2048 - 64) - 1` is the same -/// `DecodingError` as the out-of-range case above. -#[test] -fn verify_from_hash_lower_bound_on_the_representative() { - let (pk, _) = fixed_keypair().unwrap(); - let mut digest = [0u8; 32]; - SHA256::default().hash_out(b"msg", &mut digest); - - let mut at_bound = [0u8; SIG_LEN]; - at_bound[7] = 0x01; - assert!(matches!( - rsassa_pkcs1_v1_5::verify_from_hash::( - &pk, &digest, &at_bound - ), - Err(SignatureError::SignatureVerificationFailed) - )); - - let mut below_bound = [0xffu8; SIG_LEN]; - below_bound[..8].fill(0); - assert!(matches!( - rsassa_pkcs1_v1_5::verify_from_hash::( - &pk, &digest, &below_bound - ), - Err(SignatureError::DecodingError(_)) - )); -} - -/// Through the trait every malformed signature is `SignatureVerificationFailed`, never a panic or -/// another error: a representative with its top eight bytes zero (RSAVP1's lower bound), empty, -/// three bytes, all zero, one byte short and one byte long. A genuine signature still verifies. -#[test] -fn trait_verify_rejects_small_representative_and_malformed_signatures() { - let (pk, sk) = fixed_keypair().unwrap(); - let msg = b"msg"; - let mut small = [0xffu8; SIG_LEN]; - small[..8].fill(0); - let malformed: [&[u8]; 6] = - [&small, &[], &[0xff; 3], &[0; SIG_LEN], &[0xff; SIG_LEN - 1], &[0xff; SIG_LEN + 1]]; - for sig in malformed { - assert!( - matches!( - RSASSA_PKCS1_v1_5_SHA256::verify(&pk, msg, None, sig), - Err(SignatureError::SignatureVerificationFailed) - ), - "{}-byte signature", - sig.len() - ); - } - - let sig = RSASSA_PKCS1_v1_5_SHA256::sign(&sk, msg, None).unwrap(); - RSASSA_PKCS1_v1_5_SHA256::verify(&pk, msg, None, &sig).unwrap(); -} diff --git a/crypto/rsa/tests/rsa_2048_pss_shake128_tests.rs b/crypto/rsa/tests/rsa_2048_pss_shake128_tests.rs index 5fe654fe..32d582e6 100644 --- a/crypto/rsa/tests/rsa_2048_pss_shake128_tests.rs +++ b/crypto/rsa/tests/rsa_2048_pss_shake128_tests.rs @@ -306,29 +306,3 @@ fn sign_randomized_takes_the_salt_from_the_callers_rng() { RSASSA_PSS_SHAKE128::verify(&pk, msg, None, &b).unwrap(); assert!(RSASSA_PSS_SHAKE128::verify(&pk, b"other", None, &a).is_err()); } - -/// Through the trait every malformed signature is `SignatureVerificationFailed`, never a panic or -/// another error: a representative with its top eight bytes zero (RSAVP1's lower bound), empty, -/// three bytes, all zero, one byte short and one byte long. A genuine signature still verifies. -#[test] -fn trait_verify_rejects_small_representative_and_malformed_signatures() { - let (pk, sk) = fixed_keypair().unwrap(); - let msg = b"msg"; - let mut small = [0xffu8; SIG_LEN]; - small[..8].fill(0); - let malformed: [&[u8]; 6] = - [&small, &[], &[0xff; 3], &[0; SIG_LEN], &[0xff; SIG_LEN - 1], &[0xff; SIG_LEN + 1]]; - for sig in malformed { - assert!( - matches!( - RSASSA_PSS_SHAKE128::verify(&pk, msg, None, sig), - Err(SignatureError::SignatureVerificationFailed) - ), - "{}-byte signature", - sig.len() - ); - } - - let sig = sign_with_salt!(RSASSA_PSS_SHAKE128, &sk, msg, [0x42u8; 32]).unwrap(); - RSASSA_PSS_SHAKE128::verify(&pk, msg, None, &sig).unwrap(); -} diff --git a/crypto/rsa/tests/rsa_2048_pss_tests.rs b/crypto/rsa/tests/rsa_2048_pss_tests.rs index 1aaa9b71..a55375f4 100644 --- a/crypto/rsa/tests/rsa_2048_pss_tests.rs +++ b/crypto/rsa/tests/rsa_2048_pss_tests.rs @@ -309,29 +309,3 @@ fn sign_randomized_takes_the_salt_from_the_callers_rng() { RSASSA_PSS_SHA256::verify(&pk, msg, None, &b).unwrap(); assert!(RSASSA_PSS_SHA256::verify(&pk, b"other", None, &a).is_err()); } - -/// Through the trait every malformed signature is `SignatureVerificationFailed`, never a panic or -/// another error: a representative with its top eight bytes zero (RSAVP1's lower bound), empty, -/// three bytes, all zero, one byte short and one byte long. A genuine signature still verifies. -#[test] -fn trait_verify_rejects_small_representative_and_malformed_signatures() { - let (pk, sk) = fixed_keypair().unwrap(); - let msg = b"msg"; - let mut small = [0xffu8; SIG_LEN]; - small[..8].fill(0); - let malformed: [&[u8]; 6] = - [&small, &[], &[0xff; 3], &[0; SIG_LEN], &[0xff; SIG_LEN - 1], &[0xff; SIG_LEN + 1]]; - for sig in malformed { - assert!( - matches!( - RSASSA_PSS_SHA256::verify(&pk, msg, None, sig), - Err(SignatureError::SignatureVerificationFailed) - ), - "{}-byte signature", - sig.len() - ); - } - - let sig = sign_with_salt!(RSASSA_PSS_SHA256, &sk, msg, [0x42u8; 32]).unwrap(); - RSASSA_PSS_SHA256::verify(&pk, msg, None, &sig).unwrap(); -} diff --git a/crypto/rsa/tests/rsa_3072_tests.rs b/crypto/rsa/tests/rsa_3072_tests.rs index 2ebdd81e..92ca507f 100644 --- a/crypto/rsa/tests/rsa_3072_tests.rs +++ b/crypto/rsa/tests/rsa_3072_tests.rs @@ -237,14 +237,12 @@ fn run_pkcs1_v1_5_verify_vectors( verify: impl Fn(&RSA3072PublicKey, &[u8], &[u8; 384]) -> bool, expected_sha: &str, expected_valid: usize, - expected_small_signature: 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; - let mut num_small_signature = 0usize; for group in doc["testGroups"].as_array().unwrap() { assert_eq!(group["sha"], expected_sha); @@ -267,13 +265,6 @@ fn run_pkcs1_v1_5_verify_vectors( }; let verified = verify(&pk, &msg, &sig); match test["result"].as_str().unwrap() { - // Wycheproof's `SmallSignature` is a genuine `e = 3` signature whose representative - // is far below `n`, which RSAVP1's lower bound rejects by policy (see - // `rsa_core::rsavp1`). - "valid" if flags.contains(&"SmallSignature") => { - assert!(!verified, "tcId {tc_id}: a small representative must be rejected"); - num_small_signature += 1; - } "valid" => { assert!(verified, "tcId {tc_id}: expected valid, got invalid"); num_valid += 1; @@ -292,7 +283,6 @@ fn run_pkcs1_v1_5_verify_vectors( } } assert_eq!(num_missing_null, 1); - assert_eq!(num_small_signature, expected_small_signature, "for {filename}"); assert_eq!(num_valid, expected_valid, "for {filename}"); assert_eq!(num_invalid, expected_invalid, "for {filename}"); } @@ -303,8 +293,7 @@ fn rsa_signature_3072_sha256_wycheproof_vectors() { "rsa_signature_3072_sha256_test.json", |pk, msg, sig| RSASSA_PKCS1_v1_5_SHA256::verify(pk, msg, None, sig).is_ok(), "SHA-256", - 7, - 1, + 8, 250, ); } @@ -320,7 +309,6 @@ fn rsa_signature_3072_sha384_wycheproof_vectors() { |pk, msg, sig| RSASSA_PKCS1_v1_5_SHA384::verify(pk, msg, None, sig).is_ok(), "SHA-384", 7, - 0, 251, ); } @@ -335,8 +323,7 @@ fn rsa_signature_3072_sha512_wycheproof_vectors() { "rsa_signature_3072_sha512_test.json", |pk, msg, sig| RSASSA_PKCS1_v1_5_SHA512::verify(pk, msg, None, sig).is_ok(), "SHA-512", - 7, - 1, + 8, 251, ); } From 6e98b41f83975996eb9ffa94799b88f1272296b9 Mon Sep 17 00:00:00 2001 From: David Hook Date: Sun, 11 Oct 2026 20:36:14 +1100 Subject: [PATCH 23/55] rsa, cli: follow feature/ecdsa's do_ rename of the streaming Signer and SignatureVerifier methods 60634add on feature/ecdsa renamed the streaming halves of the signature traits to do_sign_init / do_sign_update / do_sign_final / do_sign_final_out and do_verify_init / do_verify_update / do_verify_final, and moved do_hazardous_operations from bouncycastle_core::key_material to bouncycastle_core::hazmat. The preceding merge brought those changes in, but the RSA crate, its tests and the rsa CLI command still used the old names, so the workspace did not build. This is the mechanical rename and import fix, nothing else. Assisted-by: Claude:claude-mythos-5-1 --- cli/src/rsa_cmd.rs | 20 +++---- crypto/rsa/src/lib.rs | 26 ++++----- crypto/rsa/src/rsassa_pkcs1_v1_5.rs | 39 +++++++------- crypto/rsa/src/rsassa_pss.rs | 53 ++++++++++--------- crypto/rsa/src/rsassa_pss_shake.rs | 49 +++++++++-------- crypto/rsa/src/rsasve.rs | 5 +- crypto/rsa/tests/rsa_2048_pkcs1_v1_5_tests.rs | 22 ++++---- .../tests/rsa_2048_pss_sha384_sha512_tests.rs | 8 +-- .../rsa/tests/rsa_2048_pss_shake128_tests.rs | 28 +++++----- crypto/rsa/tests/rsa_2048_pss_tests.rs | 28 +++++----- .../rsa/tests/rsa_3072_pss_shake128_tests.rs | 8 +-- crypto/rsa/tests/rsa_3072_tests.rs | 8 +-- .../rsa/tests/rsa_4096_pss_shake256_tests.rs | 8 +-- crypto/rsa/tests/rsa_4096_tests.rs | 16 +++--- crypto/rsa/tests/rsa_8192_tests.rs | 16 +++--- 15 files changed, 171 insertions(+), 163 deletions(-) diff --git a/cli/src/rsa_cmd.rs b/cli/src/rsa_cmd.rs index dff05f12..4d1a5bfc 100644 --- a/cli/src/rsa_cmd.rs +++ b/cli/src/rsa_cmd.rs @@ -141,7 +141,7 @@ fn parse_pk, const PK_LEN: usize>( /// Verifies stdin against `--pkfile`/`--sigfile` through `V`'s streaming `SignatureVerifier` /// impl. Shared by [`rsa_sign_verify_cmd`]'s `Verify` arm, 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 `verify_final` reports it. +/// invalid (RFC 8017 §8.1.2/§8.2.2 step 1), as `do_verify_final` reports it. fn do_verify< PK: SignaturePublicKey, V: SignatureVerifier, @@ -155,12 +155,12 @@ fn do_verify< let pk = parse_pk::(&require_file(pkfile, "pkfile"), alg_name); let sig = require_file(sigfile, "sigfile"); - // `verify_init` is infallible for every `bouncycastle_rsa` verifier (it only stores the key + // `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 = V::verify_init(&pk, None).unwrap(); - stream_stdin_into(|chunk| verifier.verify_update(chunk)); + let mut verifier = V::do_verify_init(&pk, None).unwrap(); + stream_stdin_into(|chunk| verifier.do_verify_update(chunk)); - if verifier.verify_final(&sig).is_ok() { + if verifier.do_verify_final(&sig).is_ok() { println!("Signature is valid."); } else { eprintln!("Signature is invalid."); @@ -170,7 +170,7 @@ fn do_verify< /// 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::sign_final`; `keygen` is the size's FIPS 186-5 generator, independent of scheme and hash. +/// `S::do_sign_final`; `keygen` is the size's FIPS 186-5 generator, independent of scheme and hash. fn rsa_sign_verify_cmd< PK: SignaturePublicKey, SK: SignaturePrivateKey, @@ -206,10 +206,10 @@ fn rsa_sign_verify_cmd< RSAAction::Sign => { let sk = parse_sk::(&require_file(skfile, "skfile"), alg_name); - // `sign_init` is infallible for every `bouncycastle_rsa` signer (see `do_verify`). - let mut signer = S::sign_init(&sk, None).unwrap(); - stream_stdin_into(|chunk| signer.sign_update(chunk)); - let sig = signer.sign_final().unwrap_or_else(|_| { + // `do_sign_init` is infallible for every `bouncycastle_rsa` signer (see `do_verify`). + let mut signer = S::do_sign_init(&sk, None).unwrap(); + stream_stdin_into(|chunk| signer.do_sign_update(chunk)); + let sig = signer.do_sign_final().unwrap_or_else(|_| { eprintln!("Error: signing failed."); exit(-1); }); diff --git a/crypto/rsa/src/lib.rs b/crypto/rsa/src/lib.rs index c7d734e4..eff46487 100644 --- a/crypto/rsa/src/lib.rs +++ b/crypto/rsa/src/lib.rs @@ -62,15 +62,15 @@ //! RSASSA_PKCS1_v1_5_SHA256::verify(&pk, b"the message to sign", None, &signature)?; //! //! // Streaming: the message arrives in chunks and is hashed as it goes. -//! let mut signer = RSASSA_PKCS1_v1_5_SHA256::sign_init(&sk, None)?; -//! signer.sign_update(b"the message "); -//! signer.sign_update(b"to sign"); -//! let streamed = signer.sign_final()?; +//! let mut signer = RSASSA_PKCS1_v1_5_SHA256::do_sign_init(&sk, None)?; +//! signer.do_sign_update(b"the message "); +//! signer.do_sign_update(b"to sign"); +//! let streamed = signer.do_sign_final()?; //! assert_eq!(streamed, signature); // PKCS#1 v1.5 is deterministic //! -//! let mut verifier = RSASSA_PKCS1_v1_5_SHA256::verify_init(&pk, None)?; -//! verifier.verify_update(b"the message to sign"); -//! verifier.verify_final(&streamed)?; +//! let mut verifier = RSASSA_PKCS1_v1_5_SHA256::do_verify_init(&pk, None)?; +//! verifier.do_verify_update(b"the message to sign"); +//! verifier.do_verify_final(&streamed)?; //! //! // `verify` takes a `&[u8]`: a signature of the wrong length is rejected as invalid //! // (RFC 8017 §8.2.2 step 1), as is one over a different message. @@ -91,14 +91,14 @@ //! //! // ... or fixed on a streaming state (as ML-DSA's `set_signer_rnd`), which makes PSS //! // deterministic -- for a caller with its own randomness source, or a test against a known salt. -//! let mut signer = RSASSA_PSS_SHA256::sign_init(&sk, None)?; +//! let mut signer = RSASSA_PSS_SHA256::do_sign_init(&sk, None)?; //! signer.set_signer_salt([0x42u8; 32]); -//! signer.sign_update(b"the message to sign"); -//! let sig_d = signer.sign_final()?; -//! let mut signer = RSASSA_PSS_SHA256::sign_init(&sk, None)?; +//! signer.do_sign_update(b"the message to sign"); +//! let sig_d = signer.do_sign_final()?; +//! let mut signer = RSASSA_PSS_SHA256::do_sign_init(&sk, None)?; //! signer.set_signer_salt([0x42u8; 32]); -//! signer.sign_update(b"the message to sign"); -//! assert_eq!(signer.sign_final()?, sig_d); +//! signer.do_sign_update(b"the message to sign"); +//! assert_eq!(signer.do_sign_final()?, sig_d); //! RSASSA_PSS_SHA256::verify(&pk, b"the message to sign", None, &sig_d)?; //! //! // Keys round-trip through the traits' raw fixed-width encoding (see `keys`'s docs). diff --git a/crypto/rsa/src/rsassa_pkcs1_v1_5.rs b/crypto/rsa/src/rsassa_pkcs1_v1_5.rs index 23aaaab4..e6bc5697 100644 --- a/crypto/rsa/src/rsassa_pkcs1_v1_5.rs +++ b/crypto/rsa/src/rsassa_pkcs1_v1_5.rs @@ -6,7 +6,7 @@ //! literals (e.g. RSA-2048/SHA-256 in [`crate::rsa_2048`]) rather than a caller choosing them. //! //! [`RSASSA_PKCS1_v1_5`] implements `bouncycastle_core`'s [`Signer`]/[`SignatureVerifier`] traits -//! over those widths -- one-shot and streaming (`sign_init`/`sign_update`/`sign_final`), with a +//! over those widths -- one-shot and streaming (`do_sign_init`/`do_sign_update`/`do_sign_final`), with a //! `&[u8]`-typed signature on the verify side -- on top of [`sign_from_hash`]/[`verify_from_hash`], //! which take the message hash rather than the message and are the pre-hash entry points for a //! caller that has already computed it. @@ -36,7 +36,7 @@ use bouncycastle_core::traits::{ /// `ctx` is accepted but ignored by every method: RSASSA-PKCS1-v1_5 (RFC 8017 §8.2) has no /// context-string input, the same position `bouncycastle_ecdsa` takes for ECDSA. /// -/// The key is cloned into this state by `sign_init`/`verify_init` (the traits leave no room for a +/// The key is cloned into this state by `do_sign_init`/`do_verify_init` (the traits leave no room for a /// borrow), so a signing state for the largest modulus size holds a copy of its /// `RsaPrivateKey`'s `Secret` fields for as long as the state lives -- see the crate docs' /// `# Memory Usage`. @@ -87,9 +87,9 @@ where msg: &[u8], ctx: Option<&[u8]>, ) -> Result<[u8; K_LEN], SignatureError> { - let mut s = Self::sign_init(sk, ctx)?; - s.sign_update(msg); - s.sign_final() + let mut s = Self::do_sign_init(sk, ctx)?; + s.do_sign_update(msg); + s.do_sign_final() } fn sign_out( @@ -103,18 +103,21 @@ where Ok(K_LEN) } - fn sign_init(sk: &RsaPrivateKey, _ctx: Option<&[u8]>) -> Result { + fn do_sign_init( + sk: &RsaPrivateKey, + _ctx: Option<&[u8]>, + ) -> Result { // ctx ignored -- see the type's docs. Ok(Self { hash: H::default(), sk: Some(sk.clone()), pk: None }) } - fn sign_update(&mut self, msg_chunk: &[u8]) { + fn do_sign_update(&mut self, msg_chunk: &[u8]) { self.hash.do_update(msg_chunk); } - fn sign_final(self) -> Result<[u8; K_LEN], SignatureError> { + fn do_sign_final(self) -> Result<[u8; K_LEN], SignatureError> { let sk = self.sk.ok_or(SignatureError::GenericError( - "sign_final called on a verify-initialized RSASSA_PKCS1_v1_5; call verify_final instead", + "do_sign_final called on a verify-initialized RSASSA_PKCS1_v1_5; call do_verify_final instead", ))?; // EMSA-PKCS1-v1_5 step 1, `H = Hash(M)`, completed here over the streamed chunks. let mut digest = [0u8; H_LEN]; @@ -122,9 +125,9 @@ where sign_from_hash::(&sk, &digest) } - fn sign_final_out(self, output: &mut [u8; K_LEN]) -> Result { + fn do_sign_final_out(self, output: &mut [u8; K_LEN]) -> Result { output.fill(0); - *output = self.sign_final()?; + *output = self.do_sign_final()?; Ok(K_LEN) } } @@ -153,22 +156,22 @@ where ctx: Option<&[u8]>, sig: &[u8], ) -> Result<(), SignatureError> { - let mut v = Self::verify_init(pk, ctx)?; - v.verify_update(msg); - v.verify_final(sig) + let mut v = Self::do_verify_init(pk, ctx)?; + v.do_verify_update(msg); + v.do_verify_final(sig) } - fn verify_init(pk: &RsaPublicKey, _ctx: Option<&[u8]>) -> Result { + fn do_verify_init(pk: &RsaPublicKey, _ctx: Option<&[u8]>) -> Result { Ok(Self { hash: H::default(), sk: None, pk: Some(pk.clone()) }) } - fn verify_update(&mut self, msg_chunk: &[u8]) { + fn do_verify_update(&mut self, msg_chunk: &[u8]) { self.hash.do_update(msg_chunk); } - fn verify_final(self, sig: &[u8]) -> Result<(), SignatureError> { + fn do_verify_final(self, sig: &[u8]) -> Result<(), SignatureError> { let pk = self.pk.ok_or(SignatureError::GenericError( - "verify_final called on a sign-initialized RSASSA_PKCS1_v1_5; call sign_final instead", + "do_verify_final called on a sign-initialized RSASSA_PKCS1_v1_5; call do_sign_final instead", ))?; // RFC 8017 §8.2.2 step 1: "Length checking: If the length of the signature S is not k // octets, output "invalid signature" and stop." -- the one place in this crate that step diff --git a/crypto/rsa/src/rsassa_pss.rs b/crypto/rsa/src/rsassa_pss.rs index 0370ad5c..7cafe702 100644 --- a/crypto/rsa/src/rsassa_pss.rs +++ b/crypto/rsa/src/rsassa_pss.rs @@ -28,7 +28,7 @@ use bouncycastle_rng::DefaultRNG; /// `crate::rsa_2048::RSASSA_PSS_SHA256`. /// /// [`Signer::sign`] has no RNG parameter, and that trait's docs define it as sourcing any -/// randomness it needs from the library's default OS-backed RNG, so `sign_final` draws the salt +/// randomness it needs from the library's default OS-backed RNG, so `do_sign_final` draws the salt /// (EMSA-PSS-ENCODE step 4) from a fresh [`DefaultRNG`] unless the caller fixed one. Two /// `Signer::sign` calls over the same key and message therefore produce different, both valid, /// signatures. Control over that randomness follows the workspace's other signature crates: @@ -57,7 +57,7 @@ pub struct RSASSA_PSS< hash: H, sk: Option>, pk: Option>, - /// The salt `sign_final` will use, if [`Self::set_signer_salt`] fixed one; `None` means a + /// The salt `do_sign_final` will use, if [`Self::set_signer_salt`] fixed one; `None` means a /// fresh one from [`DefaultRNG`]. salt: Option<[u8; S_LEN]>, } @@ -110,13 +110,13 @@ where ) -> Result<[u8; K_LEN], SignatureError> { let mut salt = [0u8; S_LEN]; rng.next_bytes_out(&mut salt).map_err(SignatureError::RNGError)?; - let mut signer = Self::sign_init(sk, None)?; + let mut signer = Self::do_sign_init(sk, None)?; signer.set_signer_salt(salt); - signer.sign_update(msg); - signer.sign_final() + signer.do_sign_update(msg); + signer.do_sign_final() } - /// Fixes the salt [`Signer::sign_final`] will use (EMSA-PSS-ENCODE step 4) instead of drawing + /// Fixes the salt [`Signer::do_sign_final`] will use (EMSA-PSS-ENCODE step 4) instead of drawing /// one from the default RNG -- the counterpart of `bouncycastle_mldsa`'s `set_signer_rnd`, for /// a caller with its own randomness source, a device without an RNG, or a test against a known /// salt. With the salt fixed, signing is deterministic; PSS's security argument assumes a @@ -171,9 +171,9 @@ where msg: &[u8], ctx: Option<&[u8]>, ) -> Result<[u8; K_LEN], SignatureError> { - let mut s = Self::sign_init(sk, ctx)?; - s.sign_update(msg); - s.sign_final() + let mut s = Self::do_sign_init(sk, ctx)?; + s.do_sign_update(msg); + s.do_sign_final() } fn sign_out( @@ -187,18 +187,21 @@ where Ok(K_LEN) } - fn sign_init(sk: &RsaPrivateKey, _ctx: Option<&[u8]>) -> Result { + fn do_sign_init( + sk: &RsaPrivateKey, + _ctx: Option<&[u8]>, + ) -> Result { // ctx ignored -- see the type's docs. Ok(Self { hash: H::default(), sk: Some(sk.clone()), pk: None, salt: None }) } - fn sign_update(&mut self, msg_chunk: &[u8]) { + fn do_sign_update(&mut self, msg_chunk: &[u8]) { self.hash.do_update(msg_chunk); } - fn sign_final(self) -> Result<[u8; K_LEN], SignatureError> { + fn do_sign_final(self) -> Result<[u8; K_LEN], SignatureError> { let sk = self.sk.ok_or(SignatureError::GenericError( - "sign_final called on a verify-initialized RSASSA_PSS; call verify_final instead", + "do_sign_final called on a verify-initialized RSASSA_PSS; call do_verify_final instead", ))?; // EMSA-PSS step 2, `mHash = Hash(M)`, completed here over the streamed chunks. let mut m_hash = [0u8; H_LEN]; @@ -232,9 +235,9 @@ where >(&sk, &m_hash, &salt) } - fn sign_final_out(self, output: &mut [u8; K_LEN]) -> Result { + fn do_sign_final_out(self, output: &mut [u8; K_LEN]) -> Result { output.fill(0); - *output = self.sign_final()?; + *output = self.do_sign_final()?; Ok(K_LEN) } } @@ -282,31 +285,31 @@ where ctx: Option<&[u8]>, sig: &[u8], ) -> Result<(), SignatureError> { - let mut v = Self::verify_init(pk, ctx)?; - v.verify_update(msg); - v.verify_final(sig) + let mut v = Self::do_verify_init(pk, ctx)?; + v.do_verify_update(msg); + v.do_verify_final(sig) } - fn verify_init(pk: &RsaPublicKey, _ctx: Option<&[u8]>) -> Result { + fn do_verify_init(pk: &RsaPublicKey, _ctx: Option<&[u8]>) -> Result { Ok(Self { hash: H::default(), sk: None, pk: Some(pk.clone()), salt: None }) } - fn verify_update(&mut self, msg_chunk: &[u8]) { + fn do_verify_update(&mut self, msg_chunk: &[u8]) { self.hash.do_update(msg_chunk); } - fn verify_final(self, sig: &[u8]) -> Result<(), SignatureError> { + fn do_verify_final(self, sig: &[u8]) -> Result<(), SignatureError> { let pk = self.pk.ok_or(SignatureError::GenericError( - "verify_final called on a sign-initialized RSASSA_PSS; call sign_final instead", + "do_verify_final called on a sign-initialized RSASSA_PSS; call do_sign_final instead", ))?; // RFC 8017 §8.1.2 step 1: "Length checking: If the length of the signature S is not k - // octets, output "invalid signature" and stop." (See `RSASSA_PKCS1_v1_5::verify_final`.) + // octets, output "invalid signature" and stop." (See `RSASSA_PKCS1_v1_5::do_verify_final`.) let sig: &[u8; K_LEN] = sig.try_into().map_err(|_| SignatureError::SignatureVerificationFailed)?; let mut m_hash = [0u8; H_LEN]; self.hash.do_final_out(&mut m_hash); // Step 2.b: RSAVP1's "signature representative out of range" is "invalid signature" here - // (see `RSASSA_PKCS1_v1_5::verify_final`). + // (see `RSASSA_PKCS1_v1_5::do_verify_final`). verify_from_hash::( &pk, &m_hash, sig, ) @@ -316,7 +319,7 @@ where /// RSASSA-PSS-SIGN (RFC 8017 §8.1.1) with the salt supplied directly rather than drawn from an /// RNG, given the message's hash `m_hash` (`H`'s output over the message) rather than the message -/// itself -- what the [`Signer`] impl's `sign_final` calls once it has hashed the streamed +/// itself -- what the [`Signer`] impl's `do_sign_final` calls once it has hashed the streamed /// message and settled the salt. EMSA-PSS is randomized only in its choice of salt (§9.1's own /// note 5), so a fixed salt makes this deterministic and directly testable against a known salt. pub fn sign_from_hash_with_salt< diff --git a/crypto/rsa/src/rsassa_pss_shake.rs b/crypto/rsa/src/rsassa_pss_shake.rs index 08cc0819..3d9441d1 100644 --- a/crypto/rsa/src/rsassa_pss_shake.rs +++ b/crypto/rsa/src/rsassa_pss_shake.rs @@ -89,13 +89,13 @@ where ) -> Result<[u8; K_LEN], SignatureError> { let mut salt = [0u8; S_LEN]; rng.next_bytes_out(&mut salt).map_err(SignatureError::RNGError)?; - let mut signer = Self::sign_init(sk, None)?; + let mut signer = Self::do_sign_init(sk, None)?; signer.set_signer_salt(salt); - signer.sign_update(msg); - signer.sign_final() + signer.do_sign_update(msg); + signer.do_sign_final() } - /// As [`crate::rsassa_pss::RSASSA_PSS::set_signer_salt`]: fixes the salt `sign_final` uses. + /// As [`crate::rsassa_pss::RSASSA_PSS::set_signer_salt`]: fixes the salt `do_sign_final` uses. pub fn set_signer_salt(&mut self, salt: [u8; S_LEN]) { self.salt = Some(salt); } @@ -142,9 +142,9 @@ where msg: &[u8], ctx: Option<&[u8]>, ) -> Result<[u8; K_LEN], SignatureError> { - let mut s = Self::sign_init(sk, ctx)?; - s.sign_update(msg); - s.sign_final() + let mut s = Self::do_sign_init(sk, ctx)?; + s.do_sign_update(msg); + s.do_sign_final() } fn sign_out( @@ -158,18 +158,21 @@ where Ok(K_LEN) } - fn sign_init(sk: &RsaPrivateKey, _ctx: Option<&[u8]>) -> Result { + fn do_sign_init( + sk: &RsaPrivateKey, + _ctx: Option<&[u8]>, + ) -> Result { // ctx ignored -- see `RSASSA_PKCS1_v1_5`'s docs. Ok(Self { hash: X::default(), sk: Some(sk.clone()), pk: None, salt: None }) } - fn sign_update(&mut self, msg_chunk: &[u8]) { + fn do_sign_update(&mut self, msg_chunk: &[u8]) { self.hash.do_update(msg_chunk); } - fn sign_final(self) -> Result<[u8; K_LEN], SignatureError> { + fn do_sign_final(self) -> Result<[u8; K_LEN], SignatureError> { let sk = self.sk.ok_or(SignatureError::GenericError( - "sign_final called on a verify-initialized RSASSA_PSS_SHAKE; call verify_final instead", + "do_sign_final called on a verify-initialized RSASSA_PSS_SHAKE; call do_verify_final instead", ))?; // EMSA-PSS step 2, `mHash = Hash(M)`, completed here over the streamed chunks. let mut m_hash = [0u8; H_LEN]; @@ -202,9 +205,9 @@ where >(&sk, &m_hash, &salt) } - fn sign_final_out(self, output: &mut [u8; K_LEN]) -> Result { + fn do_sign_final_out(self, output: &mut [u8; K_LEN]) -> Result { output.fill(0); - *output = self.sign_final()?; + *output = self.do_sign_final()?; Ok(K_LEN) } } @@ -250,31 +253,31 @@ where ctx: Option<&[u8]>, sig: &[u8], ) -> Result<(), SignatureError> { - let mut v = Self::verify_init(pk, ctx)?; - v.verify_update(msg); - v.verify_final(sig) + let mut v = Self::do_verify_init(pk, ctx)?; + v.do_verify_update(msg); + v.do_verify_final(sig) } - fn verify_init(pk: &RsaPublicKey, _ctx: Option<&[u8]>) -> Result { + fn do_verify_init(pk: &RsaPublicKey, _ctx: Option<&[u8]>) -> Result { Ok(Self { hash: X::default(), sk: None, pk: Some(pk.clone()), salt: None }) } - fn verify_update(&mut self, msg_chunk: &[u8]) { + fn do_verify_update(&mut self, msg_chunk: &[u8]) { self.hash.do_update(msg_chunk); } - fn verify_final(self, sig: &[u8]) -> Result<(), SignatureError> { + fn do_verify_final(self, sig: &[u8]) -> Result<(), SignatureError> { let pk = self.pk.ok_or(SignatureError::GenericError( - "verify_final called on a sign-initialized RSASSA_PSS_SHAKE; call sign_final instead", + "do_verify_final called on a sign-initialized RSASSA_PSS_SHAKE; call do_sign_final instead", ))?; // RFC 8017 §8.1.2 step 1: "Length checking: If the length of the signature S is not k - // octets, output "invalid signature" and stop." (See `RSASSA_PKCS1_v1_5::verify_final`.) + // octets, output "invalid signature" and stop." (See `RSASSA_PKCS1_v1_5::do_verify_final`.) let sig: &[u8; K_LEN] = sig.try_into().map_err(|_| SignatureError::SignatureVerificationFailed)?; let mut m_hash = [0u8; H_LEN]; self.hash.do_final_out(&mut m_hash); // Step 2.b: RSAVP1's "signature representative out of range" is "invalid signature" here - // (see `RSASSA_PKCS1_v1_5::verify_final`). + // (see `RSASSA_PKCS1_v1_5::do_verify_final`). verify_from_hash::( &pk, &m_hash, sig, ) @@ -284,7 +287,7 @@ where /// RSASSA-PSS-SIGN (RFC 8017 §8.1.1) with the salt supplied directly, given the message's hash /// `m_hash` (`X`'s `H_LEN`-byte output over the message) rather than the message -- mirroring -/// [`crate::rsassa_pss::sign_from_hash_with_salt`], and what the [`Signer`] impl's `sign_final` +/// [`crate::rsassa_pss::sign_from_hash_with_salt`], and what the [`Signer`] impl's `do_sign_final` /// calls. pub fn sign_from_hash_with_salt< X: XOF + Default, diff --git a/crypto/rsa/src/rsasve.rs b/crypto/rsa/src/rsasve.rs index 3bc3e83c..46a4d7f1 100644 --- a/crypto/rsa/src/rsasve.rs +++ b/crypto/rsa/src/rsasve.rs @@ -47,9 +47,8 @@ use crate::codec::{be_bytes_from_limbs, limbs_from_be_bytes}; use crate::keys::{RsaPrivateKey, RsaPublicKey}; use crate::rsa_core::{crt_exp, public_exp}; use bouncycastle_core::errors::{KEMError, RNGError, SignatureError}; -use bouncycastle_core::key_material::{ - KeyMaterial, KeyMaterialTrait, KeyType, do_hazardous_operations, -}; +use bouncycastle_core::hazmat::do_hazardous_operations; +use bouncycastle_core::key_material::{KeyMaterial, KeyMaterialTrait, KeyType}; use bouncycastle_core::security_strength::SecurityStrength; use bouncycastle_core::traits::{ KEMDecapsulator, KEMEncapsulator, KEMPrivateKey, KEMPublicKey, RNG, diff --git a/crypto/rsa/tests/rsa_2048_pkcs1_v1_5_tests.rs b/crypto/rsa/tests/rsa_2048_pkcs1_v1_5_tests.rs index 78bc53bb..afc8a3b5 100644 --- a/crypto/rsa/tests/rsa_2048_pkcs1_v1_5_tests.rs +++ b/crypto/rsa/tests/rsa_2048_pkcs1_v1_5_tests.rs @@ -189,16 +189,16 @@ fn key_trait_boundary_conditions() { } /// Streamed and one-shot signing are one computation: PKCS#1 v1.5 is deterministic, so the -/// chunked `sign_init`/`sign_update`/`sign_final` path reproduces `Signer::sign` byte for byte. +/// chunked `do_sign_init`/`do_sign_update`/`do_sign_final` path reproduces `Signer::sign` 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 = RSASSA_PKCS1_v1_5_SHA256::sign(&sk, msg, None).unwrap(); - let mut signer = RSASSA_PKCS1_v1_5_SHA256::sign_init(&sk, None).unwrap(); - signer.sign_update(&msg[..10]); - signer.sign_update(&msg[10..]); - let streamed = signer.sign_final().unwrap(); + let mut signer = RSASSA_PKCS1_v1_5_SHA256::do_sign_init(&sk, None).unwrap(); + signer.do_sign_update(&msg[..10]); + signer.do_sign_update(&msg[10..]); + let streamed = signer.do_sign_final().unwrap(); assert_eq!(streamed, one_shot); RSASSA_PKCS1_v1_5_SHA256::verify(&pk, msg, None, &streamed).unwrap(); } @@ -227,13 +227,13 @@ fn trait_final_in_the_wrong_role_is_an_error() { let (pk, sk) = fixed_keypair().unwrap(); let mut out = [0u8; SIG_LEN]; - let verifier = RSASSA_PKCS1_v1_5_SHA256::verify_init(&pk, None).unwrap(); - assert!(matches!(verifier.sign_final(), Err(SignatureError::GenericError(_)))); - let verifier = RSASSA_PKCS1_v1_5_SHA256::verify_init(&pk, None).unwrap(); - assert!(matches!(verifier.sign_final_out(&mut out), Err(SignatureError::GenericError(_)))); + let verifier = RSASSA_PKCS1_v1_5_SHA256::do_verify_init(&pk, None).unwrap(); + assert!(matches!(verifier.do_sign_final(), Err(SignatureError::GenericError(_)))); + let verifier = RSASSA_PKCS1_v1_5_SHA256::do_verify_init(&pk, None).unwrap(); + assert!(matches!(verifier.do_sign_final_out(&mut out), Err(SignatureError::GenericError(_)))); - let signer = RSASSA_PKCS1_v1_5_SHA256::sign_init(&sk, None).unwrap(); - assert!(matches!(signer.verify_final(&out), Err(SignatureError::GenericError(_)))); + let signer = RSASSA_PKCS1_v1_5_SHA256::do_sign_init(&sk, None).unwrap(); + assert!(matches!(signer.do_verify_final(&out), Err(SignatureError::GenericError(_)))); } /// All three groups of `rsa_signature_2048_sha256_test.json` (259 vectors; the first group's key diff --git a/crypto/rsa/tests/rsa_2048_pss_sha384_sha512_tests.rs b/crypto/rsa/tests/rsa_2048_pss_sha384_sha512_tests.rs index 3e61843f..3d0bb5f1 100644 --- a/crypto/rsa/tests/rsa_2048_pss_sha384_sha512_tests.rs +++ b/crypto/rsa/tests/rsa_2048_pss_sha384_sha512_tests.rs @@ -20,13 +20,13 @@ use std::fs; use std::path::Path; /// Signs through the streaming trait path with a fixed salt (`set_signer_salt`) -- the -/// deterministic PSS mode, for tests against a known salt. Returns `sign_final`'s `Result`. +/// 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 mut signer = <$ty>::sign_init($sk, None).unwrap(); + let mut signer = <$ty>::do_sign_init($sk, None).unwrap(); signer.set_signer_salt($salt); - signer.sign_update($msg); - signer.sign_final() + signer.do_sign_update($msg); + signer.do_sign_final() }}; } diff --git a/crypto/rsa/tests/rsa_2048_pss_shake128_tests.rs b/crypto/rsa/tests/rsa_2048_pss_shake128_tests.rs index 32d582e6..2b969698 100644 --- a/crypto/rsa/tests/rsa_2048_pss_shake128_tests.rs +++ b/crypto/rsa/tests/rsa_2048_pss_shake128_tests.rs @@ -20,13 +20,13 @@ use std::fs; use std::path::Path; /// Signs through the streaming trait path with a fixed salt (`set_signer_salt`) -- the -/// deterministic PSS mode, for tests against a known salt. Returns `sign_final`'s `Result`. +/// 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 mut signer = <$ty>::sign_init($sk, None).unwrap(); + let mut signer = <$ty>::do_sign_init($sk, None).unwrap(); signer.set_signer_salt($salt); - signer.sign_update($msg); - signer.sign_final() + signer.do_sign_update($msg); + signer.do_sign_final() }}; } @@ -249,11 +249,11 @@ fn set_signer_salt_fixes_the_salt_on_the_streaming_path() { let msg = b"fixed salt, streamed in two chunks"; let salt = [0x42u8; 32]; - let mut signer = RSASSA_PSS_SHAKE128::sign_init(&sk, None).unwrap(); + let mut signer = RSASSA_PSS_SHAKE128::do_sign_init(&sk, None).unwrap(); signer.set_signer_salt(salt); - signer.sign_update(&msg[..11]); - signer.sign_update(&msg[11..]); - let sig = signer.sign_final().unwrap(); + signer.do_sign_update(&msg[..11]); + signer.do_sign_update(&msg[11..]); + let sig = signer.do_sign_final().unwrap(); let mut digest = [0u8; 32]; SHAKE128::default().hash_out(msg, &mut digest); let expected = rsassa_pss_shake::sign_from_hash_with_salt::< @@ -274,15 +274,15 @@ fn set_signer_salt_fixes_the_salt_on_the_streaming_path() { assert_eq!(sig, expected); RSASSA_PSS_SHAKE128::verify(&pk, msg, None, &sig).unwrap(); - let mut fresh = RSASSA_PSS_SHAKE128::sign_init(&sk, None).unwrap(); - fresh.sign_update(msg); - assert_ne!(fresh.sign_final().unwrap(), sig, "without set_signer_salt the salt is fresh"); + let mut fresh = RSASSA_PSS_SHAKE128::do_sign_init(&sk, None).unwrap(); + fresh.do_sign_update(msg); + assert_ne!(fresh.do_sign_final().unwrap(), sig, "without set_signer_salt the salt is fresh"); // On a verify-initialised state it has no effect. - let mut verifier = RSASSA_PSS_SHAKE128::verify_init(&pk, None).unwrap(); + let mut verifier = RSASSA_PSS_SHAKE128::do_verify_init(&pk, None).unwrap(); verifier.set_signer_salt([0xffu8; 32]); - verifier.verify_update(msg); - verifier.verify_final(&sig).unwrap(); + verifier.do_verify_update(msg); + verifier.do_verify_final(&sig).unwrap(); } /// `sign_randomized` draws the salt from the caller's RNG (the ECDSA/SM2 shape): with a diff --git a/crypto/rsa/tests/rsa_2048_pss_tests.rs b/crypto/rsa/tests/rsa_2048_pss_tests.rs index a55375f4..d0a5a932 100644 --- a/crypto/rsa/tests/rsa_2048_pss_tests.rs +++ b/crypto/rsa/tests/rsa_2048_pss_tests.rs @@ -25,13 +25,13 @@ use std::fs; use std::path::Path; /// Signs through the streaming trait path with a fixed salt (`set_signer_salt`) -- the -/// deterministic PSS mode, for tests against a known salt. Returns `sign_final`'s `Result`. +/// 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 mut signer = <$ty>::sign_init($sk, None).unwrap(); + let mut signer = <$ty>::do_sign_init($sk, None).unwrap(); signer.set_signer_salt($salt); - signer.sign_update($msg); - signer.sign_final() + signer.do_sign_update($msg); + signer.do_sign_final() }}; } @@ -254,11 +254,11 @@ fn set_signer_salt_fixes_the_salt_on_the_streaming_path() { let msg = b"fixed salt, streamed in two chunks"; let salt = [0x42u8; 32]; - let mut signer = RSASSA_PSS_SHA256::sign_init(&sk, None).unwrap(); + let mut signer = RSASSA_PSS_SHA256::do_sign_init(&sk, None).unwrap(); signer.set_signer_salt(salt); - signer.sign_update(&msg[..11]); - signer.sign_update(&msg[11..]); - let sig = signer.sign_final().unwrap(); + signer.do_sign_update(&msg[..11]); + signer.do_sign_update(&msg[11..]); + let sig = signer.do_sign_final().unwrap(); let mut digest = [0u8; 32]; SHA256::default().hash_out(msg, &mut digest); let expected = rsassa_pss::sign_from_hash_with_salt::< @@ -280,15 +280,15 @@ fn set_signer_salt_fixes_the_salt_on_the_streaming_path() { assert_eq!(sig, expected); RSASSA_PSS_SHA256::verify(&pk, msg, None, &sig).unwrap(); - let mut fresh = RSASSA_PSS_SHA256::sign_init(&sk, None).unwrap(); - fresh.sign_update(msg); - assert_ne!(fresh.sign_final().unwrap(), sig, "without set_signer_salt the salt is fresh"); + let mut fresh = RSASSA_PSS_SHA256::do_sign_init(&sk, None).unwrap(); + fresh.do_sign_update(msg); + assert_ne!(fresh.do_sign_final().unwrap(), sig, "without set_signer_salt the salt is fresh"); // On a verify-initialised state it has no effect. - let mut verifier = RSASSA_PSS_SHA256::verify_init(&pk, None).unwrap(); + let mut verifier = RSASSA_PSS_SHA256::do_verify_init(&pk, None).unwrap(); verifier.set_signer_salt([0xffu8; 32]); - verifier.verify_update(msg); - verifier.verify_final(&sig).unwrap(); + verifier.do_verify_update(msg); + verifier.do_verify_final(&sig).unwrap(); } /// `sign_randomized` draws the salt from the caller's RNG (the ECDSA/SM2 shape): with a diff --git a/crypto/rsa/tests/rsa_3072_pss_shake128_tests.rs b/crypto/rsa/tests/rsa_3072_pss_shake128_tests.rs index 5bf0b754..4364e591 100644 --- a/crypto/rsa/tests/rsa_3072_pss_shake128_tests.rs +++ b/crypto/rsa/tests/rsa_3072_pss_shake128_tests.rs @@ -16,13 +16,13 @@ use std::fs; use std::path::Path; /// Signs through the streaming trait path with a fixed salt (`set_signer_salt`) -- the -/// deterministic PSS mode, for tests against a known salt. Returns `sign_final`'s `Result`. +/// 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 mut signer = <$ty>::sign_init($sk, None).unwrap(); + let mut signer = <$ty>::do_sign_init($sk, None).unwrap(); signer.set_signer_salt($salt); - signer.sign_update($msg); - signer.sign_final() + signer.do_sign_update($msg); + signer.do_sign_final() }}; } diff --git a/crypto/rsa/tests/rsa_3072_tests.rs b/crypto/rsa/tests/rsa_3072_tests.rs index 92ca507f..3d5a4ecf 100644 --- a/crypto/rsa/tests/rsa_3072_tests.rs +++ b/crypto/rsa/tests/rsa_3072_tests.rs @@ -27,13 +27,13 @@ use std::fs; use std::path::Path; /// Signs through the streaming trait path with a fixed salt (`set_signer_salt`) -- the -/// deterministic PSS mode, for tests against a known salt. Returns `sign_final`'s `Result`. +/// 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 mut signer = <$ty>::sign_init($sk, None).unwrap(); + let mut signer = <$ty>::do_sign_init($sk, None).unwrap(); signer.set_signer_salt($salt); - signer.sign_update($msg); - signer.sign_final() + signer.do_sign_update($msg); + signer.do_sign_final() }}; } diff --git a/crypto/rsa/tests/rsa_4096_pss_shake256_tests.rs b/crypto/rsa/tests/rsa_4096_pss_shake256_tests.rs index bc847896..b47f913e 100644 --- a/crypto/rsa/tests/rsa_4096_pss_shake256_tests.rs +++ b/crypto/rsa/tests/rsa_4096_pss_shake256_tests.rs @@ -12,13 +12,13 @@ use std::fs; use std::path::Path; /// Signs through the streaming trait path with a fixed salt (`set_signer_salt`) -- the -/// deterministic PSS mode, for tests against a known salt. Returns `sign_final`'s `Result`. +/// 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 mut signer = <$ty>::sign_init($sk, None).unwrap(); + let mut signer = <$ty>::do_sign_init($sk, None).unwrap(); signer.set_signer_salt($salt); - signer.sign_update($msg); - signer.sign_final() + signer.do_sign_update($msg); + signer.do_sign_final() }}; } diff --git a/crypto/rsa/tests/rsa_4096_tests.rs b/crypto/rsa/tests/rsa_4096_tests.rs index 475b9dce..617d01f1 100644 --- a/crypto/rsa/tests/rsa_4096_tests.rs +++ b/crypto/rsa/tests/rsa_4096_tests.rs @@ -28,13 +28,13 @@ use std::fs; use std::path::Path; /// Signs through the streaming trait path with a fixed salt (`set_signer_salt`) -- the -/// deterministic PSS mode, for tests against a known salt. Returns `sign_final`'s `Result`. +/// 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 mut signer = <$ty>::sign_init($sk, None).unwrap(); + let mut signer = <$ty>::do_sign_init($sk, None).unwrap(); signer.set_signer_salt($salt); - signer.sign_update($msg); - signer.sign_final() + signer.do_sign_update($msg); + signer.do_sign_final() }}; } @@ -468,10 +468,10 @@ where let msg = b"RSA-4096 trait round trip"; let sig = S::sign(sk, msg, None).unwrap(); S::verify(pk, msg, None, &sig).unwrap(); - let mut signer = S::sign_init(sk, None).unwrap(); - signer.sign_update(&msg[..8]); - signer.sign_update(&msg[8..]); - S::verify(pk, msg, None, &signer.sign_final().unwrap()).unwrap(); + let mut signer = S::do_sign_init(sk, None).unwrap(); + signer.do_sign_update(&msg[..8]); + signer.do_sign_update(&msg[8..]); + S::verify(pk, msg, None, &signer.do_sign_final().unwrap()).unwrap(); assert!(S::verify(pk, b"a different message", None, &sig).is_err()); } diff --git a/crypto/rsa/tests/rsa_8192_tests.rs b/crypto/rsa/tests/rsa_8192_tests.rs index 264ad71e..2a9ad83f 100644 --- a/crypto/rsa/tests/rsa_8192_tests.rs +++ b/crypto/rsa/tests/rsa_8192_tests.rs @@ -38,13 +38,13 @@ use std::fs; use std::path::Path; /// Signs through the streaming trait path with a fixed salt (`set_signer_salt`) -- the -/// deterministic PSS mode, for tests against a known salt. Returns `sign_final`'s `Result`. +/// 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 mut signer = <$ty>::sign_init($sk, None).unwrap(); + let mut signer = <$ty>::do_sign_init($sk, None).unwrap(); signer.set_signer_salt($salt); - signer.sign_update($msg); - signer.sign_final() + signer.do_sign_update($msg); + signer.do_sign_final() }}; } @@ -422,10 +422,10 @@ where let msg = b"RSA-8192 trait round trip"; let sig = S::sign(sk, msg, None).unwrap(); S::verify(pk, msg, None, &sig).unwrap(); - let mut signer = S::sign_init(sk, None).unwrap(); - signer.sign_update(&msg[..8]); - signer.sign_update(&msg[8..]); - S::verify(pk, msg, None, &signer.sign_final().unwrap()).unwrap(); + let mut signer = S::do_sign_init(sk, None).unwrap(); + signer.do_sign_update(&msg[..8]); + signer.do_sign_update(&msg[8..]); + S::verify(pk, msg, None, &signer.do_sign_final().unwrap()).unwrap(); assert!(S::verify(pk, b"a different message", None, &sig).is_err()); } From c6ea90df1f70821a2f7f19bfedd9a907020a4fd3 Mon Sep 17 00:00:00 2001 From: David Hook Date: Tue, 3 Nov 2026 12:14:44 +1100 Subject: [PATCH 24/55] rsa, cli: port the signature schemes onto the key role traits RSASSA-PKCS1-v1_5, RSASSA-PSS and RSASSA-PSS with SHAKE lose their `Signer`/`SignatureVerifier` impls and the `sign_randomized`, `set_signer_salt` and `do_sign_*` surface that came with them; each (scheme, hash, size) type is now an algorithm marker (`Algorithm` + `SignatureAlgorithm`, named "RSASSA-PKCS1-v1_5", "RSASSA-PSS" and "RSASSA-PSS-SHAKE", strength from the modulus length) that `bouncycastle_core::signature_key`'s role traits are implemented over. `RsaPrivateKey` implements `SigningKey` for the PSS markers, whose `create_signer` draws the salt from the caller's RNG, and `DeterministicSigningKey` for PKCS#1 v1.5, which draws nothing; `RsaPublicKey` implements `VerifyingKey` for all three. The workers (`RsaPssSigner`, `RsaPssShakeSigner`, `RsaPkcs1v15Signer` and their verifiers) borrow the key, and the PSS signers keep `set_salt` for a known-answer test. The role impls are bounded on the key's `SignaturePrivateKey`/`SignaturePublicKey` impl, so a 1024- or 1536-bit key still has no signing role, as the `compile_fail` doctest pins. Since one key type serves every marker, a call spells it: `SigningKey::::sign(&sk, &mut rng, msg, None)`. A signature of the wrong length is a `LengthError`, as the other signature crates report it, where it was `SignatureVerificationFailed`. The no-argument `keygen()` goes and `keygen_from_rng` becomes `keygen(rng)` in each size module and in RSASVE, the rule the rest of the library follows; the CLI's keygen draws from `HashDRBG_SHA512::new_from_os()`. The EMSA encoders take `HashOneShot` and call `H::hash_out`. Tests, benches, the stack harness and the CLI move onto the key traits; the state-confusion test of the old `do_sign_init` went with the method it exercised. Assisted-by: Claude:claude-mythos-5-1 --- cli/src/rsa_cmd.rs | 203 +++--- cli/src/rsasve_cmd.rs | 9 +- cli/tests/rsa_cli_tests.rs | 27 +- crypto/rsa/benches/rsa_1024_benches.rs | 6 +- crypto/rsa/benches/rsa_1536_benches.rs | 8 +- crypto/rsa/benches/rsa_2048_benches.rs | 116 +++- crypto/rsa/benches/rsa_3072_benches.rs | 116 +++- crypto/rsa/benches/rsa_4096_benches.rs | 112 +++- crypto/rsa/benches/rsa_8192_benches.rs | 105 ++- crypto/rsa/src/emsa_pkcs1_v1_5.rs | 8 +- crypto/rsa/src/emsa_pss.rs | 12 +- crypto/rsa/src/emsa_pss_shake.rs | 14 +- crypto/rsa/src/keygen.rs | 6 +- crypto/rsa/src/keys.rs | 17 + crypto/rsa/src/lib.rs | 133 ++-- crypto/rsa/src/mgf1.rs | 6 +- crypto/rsa/src/rsa_1024.rs | 21 +- crypto/rsa/src/rsa_2048.rs | 45 +- crypto/rsa/src/rsa_3072.rs | 29 +- crypto/rsa/src/rsa_4096.rs | 29 +- crypto/rsa/src/rsa_8192.rs | 27 +- crypto/rsa/src/rsassa_pkcs1_v1_5.rs | 418 +++++++++--- crypto/rsa/src/rsassa_pss.rs | 601 ++++++++++++++---- crypto/rsa/src/rsassa_pss_shake.rs | 557 ++++++++++++---- crypto/rsa/src/rsasve.rs | 10 +- crypto/rsa/tests/keygen_tests.rs | 80 ++- crypto/rsa/tests/rsa_1024_tests.rs | 21 +- crypto/rsa/tests/rsa_1536_tests.rs | 19 +- ...rsa_2048_pkcs1_v1_5_sha384_sha512_tests.rs | 60 +- crypto/rsa/tests/rsa_2048_pkcs1_v1_5_tests.rs | 96 ++- .../tests/rsa_2048_pss_sha384_sha512_tests.rs | 114 ++-- .../rsa/tests/rsa_2048_pss_shake128_tests.rs | 110 ++-- crypto/rsa/tests/rsa_2048_pss_tests.rs | 111 ++-- .../rsa/tests/rsa_3072_pss_shake128_tests.rs | 50 +- crypto/rsa/tests/rsa_3072_tests.rs | 172 +++-- .../rsa/tests/rsa_4096_pss_shake256_tests.rs | 54 +- crypto/rsa/tests/rsa_4096_tests.rs | 178 +++--- crypto/rsa/tests/rsa_8192_tests.rs | 177 ++++-- crypto/rsa/tests/rsasve_tests.rs | 24 +- dev_scripts/cli_ccm_cfb_examples.sh | 200 ++++++ mem_usage_benches/src/bench_rsa_mem_usage.rs | 41 +- 41 files changed, 2805 insertions(+), 1337 deletions(-) create mode 100755 dev_scripts/cli_ccm_cfb_examples.sh diff --git a/cli/src/rsa_cmd.rs b/cli/src/rsa_cmd.rs index 4d1a5bfc..ba39e1ef 100644 --- a/cli/src/rsa_cmd.rs +++ b/cli/src/rsa_cmd.rs @@ -8,11 +8,12 @@ //! (`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 `Signer`/`SignatureVerifier` -//! types (`rsa_2048::RSASSA_PKCS1_v1_5_SHA256` and siblings), so, as `ecdsa_cmd.rs` does for its -//! curves, a single generic [`rsa_sign_verify_cmd`] bound over those traits is monomorphised once -//! per pairing below, and the message streams from stdin through the traits' `_update` methods in -//! this CLI's usual ~1 KB chunks rather than being read whole. `ctx` (accepted by the traits for +//! Every (size, scheme, hash) pairing is one of `bouncycastle_rsa`'s algorithm marker +//! types (`rsa_2048::RSASSA_PKCS1_v1_5_SHA256` and siblings) that the key role traits are +//! implemented over, 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. `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`. //! @@ -28,14 +29,18 @@ //! //! 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 `SignatureVerifier` -- exactly the trait those sizes' +//! through [`do_verify`], which needs only a `VerifyingKey` -- exactly the trait those sizes' //! types implement. use crate::helpers::{read_from_file, write_bytes_or_hex, write_bytes_or_hex_to_file}; use bouncycastle::core::errors::SignatureError; +use bouncycastle::core::signature_key::{ + DeterministicSigningKey, SignatureAlgorithm, SigningKey, VerifyingKey, +}; use bouncycastle::core::traits::{ - SignaturePrivateKey, SignaturePublicKey, SignatureVerifier, Signer, + RNG, SignaturePrivateKey, SignaturePublicKey, SignatureSigner, SignatureVerifier, }; +use bouncycastle::rng::HashDRBG_SHA512; use bouncycastle::rsa::{rsa_1024, rsa_1536, rsa_2048, rsa_3072, rsa_4096, rsa_8192}; use clap::ValueEnum; use std::io; @@ -138,13 +143,13 @@ fn parse_pk, const PK_LEN: usize>( } } -/// Verifies stdin against `--pkfile`/`--sigfile` through `V`'s streaming `SignatureVerifier` +/// Verifies stdin against `--pkfile`/`--sigfile` through `PK`'s streaming `VerifyingKey` /// impl. Shared by [`rsa_sign_verify_cmd`]'s `Verify` arm, 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< - PK: SignaturePublicKey, - V: SignatureVerifier, + A: SignatureAlgorithm, + PK: SignaturePublicKey + VerifyingKey, const PK_LEN: usize, const SIG_LEN: usize, >( @@ -157,8 +162,8 @@ fn do_verify< // `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 = V::do_verify_init(&pk, None).unwrap(); - stream_stdin_into(|chunk| verifier.do_verify_update(chunk)); + let mut verifier = VerifyingKey::::create_verifier(&pk, None).unwrap(); + stream_stdin_into(|chunk| verifier.do_update(chunk)); if verifier.do_verify_final(&sig).is_ok() { println!("Signature is valid."); @@ -171,16 +176,45 @@ fn do_verify< /// 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_sign_verify_cmd< +fn rsa_keygen_cmd< PK: SignaturePublicKey, SK: SignaturePrivateKey, - S: Signer + SignatureVerifier, + const PK_LEN: usize, + const SK_LEN: usize, +>( + keygen: fn(&mut dyn RNG) -> Result<(PK, SK), SignatureError>, + pkfile: &Option, + output_hex: bool, + alg_name: &str, +) { + 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_bytes_or_hex(&sk.encode(), 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: SignatureAlgorithm, + PK: SignaturePublicKey + VerifyingKey, + SK: SignaturePrivateKey + SigningKey, const PK_LEN: usize, const SK_LEN: usize, const SIG_LEN: usize, >( action: &RSAAction, - keygen: fn() -> Result<(PK, SK), SignatureError>, + keygen: fn(&mut dyn RNG) -> Result<(PK, SK), SignatureError>, skfile: &Option, pkfile: &Option, sigfile: &Option, @@ -189,39 +223,66 @@ fn rsa_sign_verify_cmd< ) { match action { RSAAction::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().unwrap_or_else(|e| { - eprintln!("Error: {alg_name} key generation failed: {e:?}"); + rsa_keygen_cmd::(keygen, pkfile, output_hex, alg_name) + } + RSAAction::Sign => { + let sk = parse_sk::(&require_file(skfile, "skfile"), alg_name); + let mut signer = SigningKey::::create_signer( + &sk, + &mut HashDRBG_SHA512::new_from_os(), + None, + ) + .unwrap(); + stream_stdin_into(|chunk| signer.do_update(chunk)); + let sig = signer.do_final().unwrap_or_else(|_| { + eprintln!("Error: signing failed."); exit(-1); }); - write_bytes_or_hex_to_file(&pk.encode(), pkfile, output_hex); - write_bytes_or_hex(&sk.encode(), output_hex); + 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: SignatureAlgorithm, + PK: SignaturePublicKey + VerifyingKey, + SK: SignaturePrivateKey + DeterministicSigningKey, + const PK_LEN: usize, + const SK_LEN: usize, + const SIG_LEN: usize, +>( + action: &RSAAction, + keygen: fn(&mut dyn RNG) -> Result<(PK, SK), SignatureError>, + skfile: &Option, + pkfile: &Option, + sigfile: &Option, + output_hex: bool, + alg_name: &str, +) { + match action { + RSAAction::Keygen => { + rsa_keygen_cmd::(keygen, pkfile, output_hex, alg_name) } RSAAction::Sign => { let sk = parse_sk::(&require_file(skfile, "skfile"), alg_name); - - // `do_sign_init` is infallible for every `bouncycastle_rsa` signer (see `do_verify`). - let mut signer = S::do_sign_init(&sk, None).unwrap(); - stream_stdin_into(|chunk| signer.do_sign_update(chunk)); - let sig = signer.do_sign_final().unwrap_or_else(|_| { + let mut signer = + DeterministicSigningKey::::create_signer_deterministic(&sk, None) + .unwrap(); + stream_stdin_into(|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), + RSAAction::Verify => do_verify::(pkfile, sigfile, alg_name), } } -/// RSA-1024: verification only (see module docs). No SHA-512 or PSS group exists in Wycheproof at -/// this size (see `bouncycastle_rsa::rsa_1024`'s own docs), so neither is wired up here either. pub(crate) fn rsa_1024_cmd( scheme: &RSAScheme, hash: &RSAHash, @@ -233,14 +294,14 @@ pub(crate) fn rsa_1024_cmd( }; match (scheme, hash) { (RSAScheme::Pkcs1v15, RSAHash::Sha256) => { - do_verify::( + do_verify::( pkfile, sigfile, "RSA-1024/PKCS#1v1.5/SHA-256", ) } (RSAScheme::Pkcs1v15, RSAHash::Sha384) => { - do_verify::( + do_verify::( pkfile, sigfile, "RSA-1024/PKCS#1v1.5/SHA-384", @@ -263,21 +324,21 @@ pub(crate) fn rsa_1536_cmd( }; match (scheme, hash) { (RSAScheme::Pkcs1v15, RSAHash::Sha256) => { - do_verify::( + do_verify::( pkfile, sigfile, "RSA-1536/PKCS#1v1.5/SHA-256", ) } (RSAScheme::Pkcs1v15, RSAHash::Sha384) => { - do_verify::( + do_verify::( pkfile, sigfile, "RSA-1536/PKCS#1v1.5/SHA-384", ) } (RSAScheme::Pkcs1v15, RSAHash::Sha512) => { - do_verify::( + do_verify::( pkfile, sigfile, "RSA-1536/PKCS#1v1.5/SHA-512", @@ -308,7 +369,7 @@ pub(crate) fn rsa_2048_cmd( let run = |name: &str, f: fn( &RSAAction, - fn() -> Result<(PK, SK), SignatureError>, + fn(&mut dyn RNG) -> Result<(PK, SK), SignatureError>, &Option, &Option, &Option, @@ -318,31 +379,31 @@ pub(crate) fn rsa_2048_cmd( match (scheme, hash) { (RSAScheme::Pkcs1v15, RSAHash::Sha256) => run( "RSA-2048/PKCS#1v1.5/SHA-256", - rsa_sign_verify_cmd::, + rsa_pkcs1_cmd::, ), (RSAScheme::Pkcs1v15, RSAHash::Sha384) => run( "RSA-2048/PKCS#1v1.5/SHA-384", - rsa_sign_verify_cmd::, + rsa_pkcs1_cmd::, ), (RSAScheme::Pkcs1v15, RSAHash::Sha512) => run( "RSA-2048/PKCS#1v1.5/SHA-512", - rsa_sign_verify_cmd::, + rsa_pkcs1_cmd::, ), (RSAScheme::Pss, RSAHash::Sha256) => run( "RSA-2048/PSS/SHA-256", - rsa_sign_verify_cmd::, + rsa_pss_cmd::, ), (RSAScheme::Pss, RSAHash::Sha384) => run( "RSA-2048/PSS/SHA-384", - rsa_sign_verify_cmd::, + rsa_pss_cmd::, ), (RSAScheme::Pss, RSAHash::Sha512) => run( "RSA-2048/PSS/SHA-512", - rsa_sign_verify_cmd::, + rsa_pss_cmd::, ), (RSAScheme::Pss, RSAHash::Shake128) => run( "RSA-2048/PSS-SHAKE128", - rsa_sign_verify_cmd::, + rsa_pss_cmd::, ), (scheme, hash) => unsupported(scheme, hash, "RSA-2048"), } @@ -368,7 +429,7 @@ pub(crate) fn rsa_3072_cmd( let run = |name: &str, f: fn( &RSAAction, - fn() -> Result<(PK, SK), SignatureError>, + fn(&mut dyn RNG) -> Result<(PK, SK), SignatureError>, &Option, &Option, &Option, @@ -378,31 +439,31 @@ pub(crate) fn rsa_3072_cmd( match (scheme, hash) { (RSAScheme::Pkcs1v15, RSAHash::Sha256) => run( "RSA-3072/PKCS#1v1.5/SHA-256", - rsa_sign_verify_cmd::, + rsa_pkcs1_cmd::, ), (RSAScheme::Pkcs1v15, RSAHash::Sha384) => run( "RSA-3072/PKCS#1v1.5/SHA-384", - rsa_sign_verify_cmd::, + rsa_pkcs1_cmd::, ), (RSAScheme::Pkcs1v15, RSAHash::Sha512) => run( "RSA-3072/PKCS#1v1.5/SHA-512", - rsa_sign_verify_cmd::, + rsa_pkcs1_cmd::, ), (RSAScheme::Pss, RSAHash::Sha256) => run( "RSA-3072/PSS/SHA-256", - rsa_sign_verify_cmd::, + rsa_pss_cmd::, ), (RSAScheme::Pss, RSAHash::Sha384) => run( "RSA-3072/PSS/SHA-384", - rsa_sign_verify_cmd::, + rsa_pss_cmd::, ), (RSAScheme::Pss, RSAHash::Sha512) => run( "RSA-3072/PSS/SHA-512", - rsa_sign_verify_cmd::, + rsa_pss_cmd::, ), (RSAScheme::Pss, RSAHash::Shake128) => run( "RSA-3072/PSS-SHAKE128", - rsa_sign_verify_cmd::, + rsa_pss_cmd::, ), (scheme, hash) => unsupported(scheme, hash, "RSA-3072"), } @@ -429,7 +490,7 @@ pub(crate) fn rsa_4096_cmd( let run = |name: &str, f: fn( &RSAAction, - fn() -> Result<(PK, SK), SignatureError>, + fn(&mut dyn RNG) -> Result<(PK, SK), SignatureError>, &Option, &Option, &Option, @@ -439,31 +500,31 @@ pub(crate) fn rsa_4096_cmd( match (scheme, hash) { (RSAScheme::Pkcs1v15, RSAHash::Sha256) => run( "RSA-4096/PKCS#1v1.5/SHA-256", - rsa_sign_verify_cmd::, + rsa_pkcs1_cmd::, ), (RSAScheme::Pkcs1v15, RSAHash::Sha384) => run( "RSA-4096/PKCS#1v1.5/SHA-384", - rsa_sign_verify_cmd::, + rsa_pkcs1_cmd::, ), (RSAScheme::Pkcs1v15, RSAHash::Sha512) => run( "RSA-4096/PKCS#1v1.5/SHA-512", - rsa_sign_verify_cmd::, + rsa_pkcs1_cmd::, ), (RSAScheme::Pss, RSAHash::Sha256) => run( "RSA-4096/PSS/SHA-256", - rsa_sign_verify_cmd::, + rsa_pss_cmd::, ), (RSAScheme::Pss, RSAHash::Sha384) => run( "RSA-4096/PSS/SHA-384", - rsa_sign_verify_cmd::, + rsa_pss_cmd::, ), (RSAScheme::Pss, RSAHash::Sha512) => run( "RSA-4096/PSS/SHA-512", - rsa_sign_verify_cmd::, + rsa_pss_cmd::, ), (RSAScheme::Pss, RSAHash::Shake256) => run( "RSA-4096/PSS-SHAKE256", - rsa_sign_verify_cmd::, + rsa_pss_cmd::, ), (scheme, hash) => unsupported(scheme, hash, "RSA-4096"), } @@ -491,7 +552,7 @@ pub(crate) fn rsa_8192_cmd( let run = |name: &str, f: fn( &RSAAction, - fn() -> Result<(PK, SK), SignatureError>, + fn(&mut dyn RNG) -> Result<(PK, SK), SignatureError>, &Option, &Option, &Option, @@ -501,27 +562,27 @@ pub(crate) fn rsa_8192_cmd( match (scheme, hash) { (RSAScheme::Pkcs1v15, RSAHash::Sha256) => run( "RSA-8192/PKCS#1v1.5/SHA-256", - rsa_sign_verify_cmd::, + rsa_pkcs1_cmd::, ), (RSAScheme::Pkcs1v15, RSAHash::Sha384) => run( "RSA-8192/PKCS#1v1.5/SHA-384", - rsa_sign_verify_cmd::, + rsa_pkcs1_cmd::, ), (RSAScheme::Pkcs1v15, RSAHash::Sha512) => run( "RSA-8192/PKCS#1v1.5/SHA-512", - rsa_sign_verify_cmd::, + rsa_pkcs1_cmd::, ), (RSAScheme::Pss, RSAHash::Sha256) => run( "RSA-8192/PSS/SHA-256", - rsa_sign_verify_cmd::, + rsa_pss_cmd::, ), (RSAScheme::Pss, RSAHash::Sha384) => run( "RSA-8192/PSS/SHA-384", - rsa_sign_verify_cmd::, + rsa_pss_cmd::, ), (RSAScheme::Pss, RSAHash::Sha512) => run( "RSA-8192/PSS/SHA-512", - rsa_sign_verify_cmd::, + rsa_pss_cmd::, ), (scheme, hash) => unsupported(scheme, hash, "RSA-8192"), } diff --git a/cli/src/rsasve_cmd.rs b/cli/src/rsasve_cmd.rs index e50f313f..a9421dfc 100644 --- a/cli/src/rsasve_cmd.rs +++ b/cli/src/rsasve_cmd.rs @@ -23,7 +23,10 @@ use crate::helpers::{ }; use bouncycastle::core::errors::KEMError; use bouncycastle::core::key_material::KeyMaterialTrait; -use bouncycastle::core::traits::{KEMDecapsulator, KEMEncapsulator, KEMPrivateKey, KEMPublicKey}; +use bouncycastle::core::traits::{ + KEMDecapsulator, KEMEncapsulator, KEMPrivateKey, KEMPublicKey, RNG, +}; +use bouncycastle::rng::HashDRBG_SHA512; use bouncycastle::rsa::{rsa_2048, rsa_3072, rsa_4096, rsa_8192}; use clap::ValueEnum; use std::process::exit; @@ -63,7 +66,7 @@ fn rsasve_cmd< const SS_LEN: usize, >( action: &RSASVEAction, - keygen: fn() -> Result<(PK, SK), KEMError>, + keygen: fn(&mut dyn RNG) -> Result<(PK, SK), KEMError>, skfile: &Option, pkfile: &Option, ctfile: &Option, @@ -79,7 +82,7 @@ fn rsasve_cmd< ); exit(-1); }; - let (pk, sk) = keygen().unwrap_or_else(|e| { + let (pk, sk) = keygen(&mut HashDRBG_SHA512::new_from_os()).unwrap_or_else(|e| { eprintln!("Error: {alg_name} key generation failed: {e:?}"); exit(-1); }); diff --git a/cli/tests/rsa_cli_tests.rs b/cli/tests/rsa_cli_tests.rs index c799dc5a..115728b8 100644 --- a/cli/tests/rsa_cli_tests.rs +++ b/cli/tests/rsa_cli_tests.rs @@ -3,16 +3,17 @@ //! 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 -//! `SignatureVerifier` impls (and, for the deterministic PKCS#1 v1.5 case, comparing bytes). +//! `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::traits::{ - SignaturePrivateKey, SignaturePublicKey, SignatureVerifier, Signer, +use bouncycastle::core::signature_key::{ + DeterministicSigningKey, SignatureAlgorithm, VerifyingKey, }; +use bouncycastle::core::traits::{SignaturePrivateKey, SignaturePublicKey}; use bouncycastle::rsa::rsa_2048::{ - PK_LEN, RSA2048PrivateKey, RSA2048PublicKey, RSASSA_PKCS1_v1_5_SHA256, RSASSA_PSS_SHA256, + RSA2048PrivateKey, RSA2048PublicKey, RSASSA_PKCS1_v1_5_SHA256, RSASSA_PSS_SHA256, RSASSA_PSS_SHAKE128, SIG_LEN, }; use std::io::{ErrorKind, Write}; @@ -208,7 +209,12 @@ fn rsa_1024_verifies_a_wycheproof_signature_and_rejects_another_message() { 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 = RSASSA_PKCS1_v1_5_SHA256::sign(&sk_2048(), &msg, None).unwrap(); + let expected = DeterministicSigningKey::::sign_deterministic( + &sk_2048(), + &msg, + None, + ) + .unwrap(); assert_eq!(sig, expected.to_vec()); let out = rsa_2048_verify("pkcs1v15", "sha256", &msg, &sig); @@ -228,14 +234,17 @@ fn rsa_2048_pkcs1v15_signature_matches_the_library_and_verifies() { } /// One PSS pairing: two CLI signatures of one message differ (a fresh salt each), and both -/// verify -- through the library's `SignatureVerifier` `V` and through the CLI. -fn pss_case>(hash: &str, msg: &[u8]) { +/// verify -- through the library's `VerifyingKey` impl for `PK` and through the CLI. +fn pss_case(hash: &str, msg: &[u8]) +where + RSA2048PublicKey: VerifyingKey, +{ let pk = pk_2048(); 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] { - V::verify(&pk, msg, None, sig) + VerifyingKey::::verify(&pk, 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)); @@ -345,7 +354,7 @@ fn rsa_2048_keygen_then_sign_and_verify() { &msg, ); assert!(String::from_utf8_lossy(&out).contains("Signature is valid.")); - RSASSA_PSS_SHA256::verify(&pk, &msg, None, &sig).unwrap(); + VerifyingKey::::verify(&pk, &msg, None, &sig).unwrap(); let err = run_err(&["rsa-2048", "keygen", "--scheme", "pkcs1v15", "--hash", "sha256"], &[]); assert!(err.contains("--pkfile"), "stderr: {err}"); diff --git a/crypto/rsa/benches/rsa_1024_benches.rs b/crypto/rsa/benches/rsa_1024_benches.rs index 9bcd67e7..82a393d0 100644 --- a/crypto/rsa/benches/rsa_1024_benches.rs +++ b/crypto/rsa/benches/rsa_1024_benches.rs @@ -3,7 +3,7 @@ //! `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::traits::SignatureVerifier; +use bouncycastle_core::signature_key::VerifyingKey; use criterion::{Criterion, criterion_group, criterion_main}; use std::hint::black_box; @@ -46,7 +46,7 @@ fn bench_rsa_1024(c: &mut Criterion) { let mut group = c.benchmark_group("rsa_1024"); group.bench_function("pkcs1v15_verify_sha256", |b| { b.iter(|| { - RSASSA_PKCS1_v1_5_SHA256::verify( + VerifyingKey::::verify( black_box(&pk_sha256), black_box(&msg_sha256), None, @@ -57,7 +57,7 @@ fn bench_rsa_1024(c: &mut Criterion) { }); group.bench_function("pkcs1v15_verify_sha384", |b| { b.iter(|| { - RSASSA_PKCS1_v1_5_SHA384::verify( + VerifyingKey::::verify( black_box(&pk_sha384), black_box(&msg_sha384), None, diff --git a/crypto/rsa/benches/rsa_1536_benches.rs b/crypto/rsa/benches/rsa_1536_benches.rs index 4c3e058e..ac56c3ed 100644 --- a/crypto/rsa/benches/rsa_1536_benches.rs +++ b/crypto/rsa/benches/rsa_1536_benches.rs @@ -3,7 +3,7 @@ //! `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::traits::SignatureVerifier; +use bouncycastle_core::signature_key::VerifyingKey; use criterion::{Criterion, criterion_group, criterion_main}; use std::hint::black_box; @@ -65,7 +65,7 @@ fn bench_rsa_1536(c: &mut Criterion) { let mut group = c.benchmark_group("rsa_1536"); group.bench_function("pkcs1v15_verify_sha256", |b| { b.iter(|| { - RSASSA_PKCS1_v1_5_SHA256::verify( + VerifyingKey::::verify( black_box(&pk_sha256), black_box(&msg), None, @@ -76,7 +76,7 @@ fn bench_rsa_1536(c: &mut Criterion) { }); group.bench_function("pkcs1v15_verify_sha384", |b| { b.iter(|| { - RSASSA_PKCS1_v1_5_SHA384::verify( + VerifyingKey::::verify( black_box(&pk_sha384), black_box(&msg), None, @@ -87,7 +87,7 @@ fn bench_rsa_1536(c: &mut Criterion) { }); group.bench_function("pkcs1v15_verify_sha512", |b| { b.iter(|| { - RSASSA_PKCS1_v1_5_SHA512::verify( + VerifyingKey::::verify( black_box(&pk_sha512), black_box(&msg), None, diff --git a/crypto/rsa/benches/rsa_2048_benches.rs b/crypto/rsa/benches/rsa_2048_benches.rs index 58765bd7..65878ae5 100644 --- a/crypto/rsa/benches/rsa_2048_benches.rs +++ b/crypto/rsa/benches/rsa_2048_benches.rs @@ -4,9 +4,10 @@ //! 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::signature_key::{DeterministicSigningKey, SigningKey, VerifyingKey}; use bouncycastle_core::traits::{ KEMDecapsulator, KEMEncapsulator, KEMPrivateKey, KEMPublicKey, SignaturePrivateKey, - SignaturePublicKey, SignatureVerifier, Signer, + SignaturePublicKey, }; use bouncycastle_rsa::rsa_2048::{RSA2048KEMPrivateKey, RSA2048KEMPublicKey, RSASVE}; use criterion::{Criterion, criterion_group, criterion_main}; @@ -62,24 +63,44 @@ fn bench_rsa_2048(c: &mut Criterion) { let pk = RSA2048PublicKey::new(sk.n(), 0x10001).unwrap(); let mut rng = DefaultRNG::default(); - let sig_pkcs1_256 = RSASSA_PKCS1_v1_5_SHA256::sign(&sk, MSG, None).unwrap(); - let sig_pkcs1_384 = RSASSA_PKCS1_v1_5_SHA384::sign(&sk, MSG, None).unwrap(); - let sig_pkcs1_512 = RSASSA_PKCS1_v1_5_SHA512::sign(&sk, MSG, None).unwrap(); - let sig_pss_256 = RSASSA_PSS_SHA256::sign_randomized(&sk, MSG, &mut rng).unwrap(); - let sig_pss_384 = RSASSA_PSS_SHA384::sign_randomized(&sk, MSG, &mut rng).unwrap(); - let sig_pss_512 = RSASSA_PSS_SHA512::sign_randomized(&sk, MSG, &mut rng).unwrap(); - let sig_pss_shake128 = RSASSA_PSS_SHAKE128::sign_randomized(&sk, MSG, &mut rng).unwrap(); + let sig_pkcs1_256 = + DeterministicSigningKey::::sign_deterministic( + &sk, MSG, None, + ) + .unwrap(); + let sig_pkcs1_384 = + DeterministicSigningKey::::sign_deterministic( + &sk, MSG, None, + ) + .unwrap(); + let sig_pkcs1_512 = + DeterministicSigningKey::::sign_deterministic( + &sk, MSG, None, + ) + .unwrap(); + let sig_pss_256 = SigningKey::::sign(&sk, &mut rng, MSG, None).unwrap(); + let sig_pss_384 = SigningKey::::sign(&sk, &mut rng, MSG, None).unwrap(); + let sig_pss_512 = SigningKey::::sign(&sk, &mut rng, MSG, None).unwrap(); + let sig_pss_shake128 = + SigningKey::::sign(&sk, &mut rng, MSG, None).unwrap(); let mut group = c.benchmark_group("rsa_2048"); group.bench_function("pkcs1v15_sign_sha256", |b| { b.iter(|| { - black_box(RSASSA_PKCS1_v1_5_SHA256::sign(black_box(&sk), black_box(MSG), None).unwrap()) + black_box( + DeterministicSigningKey::::sign_deterministic( + black_box(&sk), + black_box(MSG), + None, + ) + .unwrap(), + ) }) }); group.bench_function("pkcs1v15_verify_sha256", |b| { b.iter(|| { - RSASSA_PKCS1_v1_5_SHA256::verify( + VerifyingKey::::verify( black_box(&pk), black_box(MSG), None, @@ -90,12 +111,19 @@ fn bench_rsa_2048(c: &mut Criterion) { }); group.bench_function("pkcs1v15_sign_sha384", |b| { b.iter(|| { - black_box(RSASSA_PKCS1_v1_5_SHA384::sign(black_box(&sk), black_box(MSG), None).unwrap()) + black_box( + DeterministicSigningKey::::sign_deterministic( + black_box(&sk), + black_box(MSG), + None, + ) + .unwrap(), + ) }) }); group.bench_function("pkcs1v15_verify_sha384", |b| { b.iter(|| { - RSASSA_PKCS1_v1_5_SHA384::verify( + VerifyingKey::::verify( black_box(&pk), black_box(MSG), None, @@ -106,12 +134,19 @@ fn bench_rsa_2048(c: &mut Criterion) { }); group.bench_function("pkcs1v15_sign_sha512", |b| { b.iter(|| { - black_box(RSASSA_PKCS1_v1_5_SHA512::sign(black_box(&sk), black_box(MSG), None).unwrap()) + black_box( + DeterministicSigningKey::::sign_deterministic( + black_box(&sk), + black_box(MSG), + None, + ) + .unwrap(), + ) }) }); group.bench_function("pkcs1v15_verify_sha512", |b| { b.iter(|| { - RSASSA_PKCS1_v1_5_SHA512::verify( + VerifyingKey::::verify( black_box(&pk), black_box(MSG), None, @@ -123,10 +158,11 @@ fn bench_rsa_2048(c: &mut Criterion) { group.bench_function("pss_sign_sha256", |b| { b.iter(|| { black_box( - RSASSA_PSS_SHA256::sign_randomized( + SigningKey::::sign( black_box(&sk), - black_box(MSG), &mut DefaultRNG::default(), + black_box(MSG), + None, ) .unwrap(), ) @@ -134,17 +170,23 @@ fn bench_rsa_2048(c: &mut Criterion) { }); group.bench_function("pss_verify_sha256", |b| { b.iter(|| { - RSASSA_PSS_SHA256::verify(black_box(&pk), black_box(MSG), None, black_box(&sig_pss_256)) - .unwrap() + VerifyingKey::::verify( + black_box(&pk), + black_box(MSG), + None, + black_box(&sig_pss_256), + ) + .unwrap() }) }); group.bench_function("pss_sign_sha384", |b| { b.iter(|| { black_box( - RSASSA_PSS_SHA384::sign_randomized( + SigningKey::::sign( black_box(&sk), - black_box(MSG), &mut DefaultRNG::default(), + black_box(MSG), + None, ) .unwrap(), ) @@ -152,17 +194,23 @@ fn bench_rsa_2048(c: &mut Criterion) { }); group.bench_function("pss_verify_sha384", |b| { b.iter(|| { - RSASSA_PSS_SHA384::verify(black_box(&pk), black_box(MSG), None, black_box(&sig_pss_384)) - .unwrap() + VerifyingKey::::verify( + black_box(&pk), + black_box(MSG), + None, + black_box(&sig_pss_384), + ) + .unwrap() }) }); group.bench_function("pss_sign_sha512", |b| { b.iter(|| { black_box( - RSASSA_PSS_SHA512::sign_randomized( + SigningKey::::sign( black_box(&sk), - black_box(MSG), &mut DefaultRNG::default(), + black_box(MSG), + None, ) .unwrap(), ) @@ -170,17 +218,23 @@ fn bench_rsa_2048(c: &mut Criterion) { }); group.bench_function("pss_verify_sha512", |b| { b.iter(|| { - RSASSA_PSS_SHA512::verify(black_box(&pk), black_box(MSG), None, black_box(&sig_pss_512)) - .unwrap() + VerifyingKey::::verify( + black_box(&pk), + black_box(MSG), + None, + black_box(&sig_pss_512), + ) + .unwrap() }) }); group.bench_function("pss_sign_shake128", |b| { b.iter(|| { black_box( - RSASSA_PSS_SHAKE128::sign_randomized( + SigningKey::::sign( black_box(&sk), - black_box(MSG), &mut DefaultRNG::default(), + black_box(MSG), + None, ) .unwrap(), ) @@ -188,7 +242,7 @@ fn bench_rsa_2048(c: &mut Criterion) { }); group.bench_function("pss_verify_shake128", |b| { b.iter(|| { - RSASSA_PSS_SHAKE128::verify( + VerifyingKey::::verify( black_box(&pk), black_box(MSG), None, @@ -217,7 +271,9 @@ fn bench_rsa_2048(c: &mut Criterion) { // 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(keygen().unwrap()))); + keygen_group.bench_function("keygen", |b| { + b.iter(|| black_box(keygen(&mut DefaultRNG::default()).unwrap())) + }); keygen_group.finish(); } diff --git a/crypto/rsa/benches/rsa_3072_benches.rs b/crypto/rsa/benches/rsa_3072_benches.rs index fc2b2026..c88256df 100644 --- a/crypto/rsa/benches/rsa_3072_benches.rs +++ b/crypto/rsa/benches/rsa_3072_benches.rs @@ -2,9 +2,10 @@ //! key is the same one `tests/rsa_3072_tests.rs` recovers from Wycheproof's //! `rsa_pkcs1_3072_sig_gen_test.json`. +use bouncycastle_core::signature_key::{DeterministicSigningKey, SigningKey, VerifyingKey}; use bouncycastle_core::traits::{ KEMDecapsulator, KEMEncapsulator, KEMPrivateKey, KEMPublicKey, SignaturePrivateKey, - SignaturePublicKey, SignatureVerifier, Signer, + SignaturePublicKey, }; use bouncycastle_rsa::rsa_3072::{RSA3072KEMPrivateKey, RSA3072KEMPublicKey, RSASVE}; use criterion::{Criterion, criterion_group, criterion_main}; @@ -70,24 +71,44 @@ fn bench_rsa_3072(c: &mut Criterion) { let pk = RSA3072PublicKey::new(sk.n(), 0x10001).unwrap(); let mut rng = DefaultRNG::default(); - let sig_pkcs1_256 = RSASSA_PKCS1_v1_5_SHA256::sign(&sk, MSG, None).unwrap(); - let sig_pkcs1_384 = RSASSA_PKCS1_v1_5_SHA384::sign(&sk, MSG, None).unwrap(); - let sig_pkcs1_512 = RSASSA_PKCS1_v1_5_SHA512::sign(&sk, MSG, None).unwrap(); - let sig_pss_256 = RSASSA_PSS_SHA256::sign_randomized(&sk, MSG, &mut rng).unwrap(); - let sig_pss_384 = RSASSA_PSS_SHA384::sign_randomized(&sk, MSG, &mut rng).unwrap(); - let sig_pss_512 = RSASSA_PSS_SHA512::sign_randomized(&sk, MSG, &mut rng).unwrap(); - let sig_pss_shake128 = RSASSA_PSS_SHAKE128::sign_randomized(&sk, MSG, &mut rng).unwrap(); + let sig_pkcs1_256 = + DeterministicSigningKey::::sign_deterministic( + &sk, MSG, None, + ) + .unwrap(); + let sig_pkcs1_384 = + DeterministicSigningKey::::sign_deterministic( + &sk, MSG, None, + ) + .unwrap(); + let sig_pkcs1_512 = + DeterministicSigningKey::::sign_deterministic( + &sk, MSG, None, + ) + .unwrap(); + let sig_pss_256 = SigningKey::::sign(&sk, &mut rng, MSG, None).unwrap(); + let sig_pss_384 = SigningKey::::sign(&sk, &mut rng, MSG, None).unwrap(); + let sig_pss_512 = SigningKey::::sign(&sk, &mut rng, MSG, None).unwrap(); + let sig_pss_shake128 = + SigningKey::::sign(&sk, &mut rng, MSG, None).unwrap(); let mut group = c.benchmark_group("rsa_3072"); group.bench_function("pkcs1v15_sign_sha256", |b| { b.iter(|| { - black_box(RSASSA_PKCS1_v1_5_SHA256::sign(black_box(&sk), black_box(MSG), None).unwrap()) + black_box( + DeterministicSigningKey::::sign_deterministic( + black_box(&sk), + black_box(MSG), + None, + ) + .unwrap(), + ) }) }); group.bench_function("pkcs1v15_verify_sha256", |b| { b.iter(|| { - RSASSA_PKCS1_v1_5_SHA256::verify( + VerifyingKey::::verify( black_box(&pk), black_box(MSG), None, @@ -98,12 +119,19 @@ fn bench_rsa_3072(c: &mut Criterion) { }); group.bench_function("pkcs1v15_sign_sha384", |b| { b.iter(|| { - black_box(RSASSA_PKCS1_v1_5_SHA384::sign(black_box(&sk), black_box(MSG), None).unwrap()) + black_box( + DeterministicSigningKey::::sign_deterministic( + black_box(&sk), + black_box(MSG), + None, + ) + .unwrap(), + ) }) }); group.bench_function("pkcs1v15_verify_sha384", |b| { b.iter(|| { - RSASSA_PKCS1_v1_5_SHA384::verify( + VerifyingKey::::verify( black_box(&pk), black_box(MSG), None, @@ -114,12 +142,19 @@ fn bench_rsa_3072(c: &mut Criterion) { }); group.bench_function("pkcs1v15_sign_sha512", |b| { b.iter(|| { - black_box(RSASSA_PKCS1_v1_5_SHA512::sign(black_box(&sk), black_box(MSG), None).unwrap()) + black_box( + DeterministicSigningKey::::sign_deterministic( + black_box(&sk), + black_box(MSG), + None, + ) + .unwrap(), + ) }) }); group.bench_function("pkcs1v15_verify_sha512", |b| { b.iter(|| { - RSASSA_PKCS1_v1_5_SHA512::verify( + VerifyingKey::::verify( black_box(&pk), black_box(MSG), None, @@ -131,10 +166,11 @@ fn bench_rsa_3072(c: &mut Criterion) { group.bench_function("pss_sign_sha256", |b| { b.iter(|| { black_box( - RSASSA_PSS_SHA256::sign_randomized( + SigningKey::::sign( black_box(&sk), - black_box(MSG), &mut DefaultRNG::default(), + black_box(MSG), + None, ) .unwrap(), ) @@ -142,17 +178,23 @@ fn bench_rsa_3072(c: &mut Criterion) { }); group.bench_function("pss_verify_sha256", |b| { b.iter(|| { - RSASSA_PSS_SHA256::verify(black_box(&pk), black_box(MSG), None, black_box(&sig_pss_256)) - .unwrap() + VerifyingKey::::verify( + black_box(&pk), + black_box(MSG), + None, + black_box(&sig_pss_256), + ) + .unwrap() }) }); group.bench_function("pss_sign_sha384", |b| { b.iter(|| { black_box( - RSASSA_PSS_SHA384::sign_randomized( + SigningKey::::sign( black_box(&sk), - black_box(MSG), &mut DefaultRNG::default(), + black_box(MSG), + None, ) .unwrap(), ) @@ -160,17 +202,23 @@ fn bench_rsa_3072(c: &mut Criterion) { }); group.bench_function("pss_verify_sha384", |b| { b.iter(|| { - RSASSA_PSS_SHA384::verify(black_box(&pk), black_box(MSG), None, black_box(&sig_pss_384)) - .unwrap() + VerifyingKey::::verify( + black_box(&pk), + black_box(MSG), + None, + black_box(&sig_pss_384), + ) + .unwrap() }) }); group.bench_function("pss_sign_sha512", |b| { b.iter(|| { black_box( - RSASSA_PSS_SHA512::sign_randomized( + SigningKey::::sign( black_box(&sk), - black_box(MSG), &mut DefaultRNG::default(), + black_box(MSG), + None, ) .unwrap(), ) @@ -178,17 +226,23 @@ fn bench_rsa_3072(c: &mut Criterion) { }); group.bench_function("pss_verify_sha512", |b| { b.iter(|| { - RSASSA_PSS_SHA512::verify(black_box(&pk), black_box(MSG), None, black_box(&sig_pss_512)) - .unwrap() + VerifyingKey::::verify( + black_box(&pk), + black_box(MSG), + None, + black_box(&sig_pss_512), + ) + .unwrap() }) }); group.bench_function("pss_sign_shake128", |b| { b.iter(|| { black_box( - RSASSA_PSS_SHAKE128::sign_randomized( + SigningKey::::sign( black_box(&sk), - black_box(MSG), &mut DefaultRNG::default(), + black_box(MSG), + None, ) .unwrap(), ) @@ -196,7 +250,7 @@ fn bench_rsa_3072(c: &mut Criterion) { }); group.bench_function("pss_verify_shake128", |b| { b.iter(|| { - RSASSA_PSS_SHAKE128::verify( + VerifyingKey::::verify( black_box(&pk), black_box(MSG), None, @@ -225,7 +279,9 @@ fn bench_rsa_3072(c: &mut Criterion) { // 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(keygen().unwrap()))); + keygen_group.bench_function("keygen", |b| { + b.iter(|| black_box(keygen(&mut DefaultRNG::default()).unwrap())) + }); keygen_group.finish(); } diff --git a/crypto/rsa/benches/rsa_4096_benches.rs b/crypto/rsa/benches/rsa_4096_benches.rs index db41417e..bedbe96c 100644 --- a/crypto/rsa/benches/rsa_4096_benches.rs +++ b/crypto/rsa/benches/rsa_4096_benches.rs @@ -3,9 +3,10 @@ //! `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::signature_key::{DeterministicSigningKey, SigningKey, VerifyingKey}; use bouncycastle_core::traits::{ KEMDecapsulator, KEMEncapsulator, KEMPrivateKey, KEMPublicKey, SignaturePrivateKey, - SignaturePublicKey, SignatureVerifier, Signer, + SignaturePublicKey, }; use bouncycastle_rsa::rsa_4096::{RSA4096KEMPrivateKey, RSA4096KEMPublicKey, RSASVE}; use criterion::{Criterion, criterion_group, criterion_main}; @@ -80,24 +81,44 @@ fn bench_rsa_4096(c: &mut Criterion) { let pk = RSA4096PublicKey::new(sk.n(), 0x10001).unwrap(); let mut rng = DefaultRNG::default(); - let sig_pkcs1_256 = RSASSA_PKCS1_v1_5_SHA256::sign(&sk, MSG, None).unwrap(); - let sig_pkcs1_384 = RSASSA_PKCS1_v1_5_SHA384::sign(&sk, MSG, None).unwrap(); - let sig_pkcs1_512 = RSASSA_PKCS1_v1_5_SHA512::sign(&sk, MSG, None).unwrap(); - let sig_pss_256 = RSASSA_PSS_SHA256::sign_randomized(&sk, MSG, &mut rng).unwrap(); - let sig_pss_384 = RSASSA_PSS_SHA384::sign_randomized(&sk, MSG, &mut rng).unwrap(); - let sig_pss_512 = RSASSA_PSS_SHA512::sign_randomized(&sk, MSG, &mut rng).unwrap(); - let sig_pss_shake256 = RSASSA_PSS_SHAKE256::sign_randomized(&sk, MSG, &mut rng).unwrap(); + let sig_pkcs1_256 = + DeterministicSigningKey::::sign_deterministic( + &sk, MSG, None, + ) + .unwrap(); + let sig_pkcs1_384 = + DeterministicSigningKey::::sign_deterministic( + &sk, MSG, None, + ) + .unwrap(); + let sig_pkcs1_512 = + DeterministicSigningKey::::sign_deterministic( + &sk, MSG, None, + ) + .unwrap(); + let sig_pss_256 = SigningKey::::sign(&sk, &mut rng, MSG, None).unwrap(); + let sig_pss_384 = SigningKey::::sign(&sk, &mut rng, MSG, None).unwrap(); + let sig_pss_512 = SigningKey::::sign(&sk, &mut rng, MSG, None).unwrap(); + let sig_pss_shake256 = + SigningKey::::sign(&sk, &mut rng, MSG, None).unwrap(); let mut group = c.benchmark_group("rsa_4096"); group.bench_function("pkcs1v15_sign_sha256", |b| { b.iter(|| { - black_box(RSASSA_PKCS1_v1_5_SHA256::sign(black_box(&sk), black_box(MSG), None).unwrap()) + black_box( + DeterministicSigningKey::::sign_deterministic( + black_box(&sk), + black_box(MSG), + None, + ) + .unwrap(), + ) }) }); group.bench_function("pkcs1v15_verify_sha256", |b| { b.iter(|| { - RSASSA_PKCS1_v1_5_SHA256::verify( + VerifyingKey::::verify( black_box(&pk), black_box(MSG), None, @@ -108,12 +129,19 @@ fn bench_rsa_4096(c: &mut Criterion) { }); group.bench_function("pkcs1v15_sign_sha384", |b| { b.iter(|| { - black_box(RSASSA_PKCS1_v1_5_SHA384::sign(black_box(&sk), black_box(MSG), None).unwrap()) + black_box( + DeterministicSigningKey::::sign_deterministic( + black_box(&sk), + black_box(MSG), + None, + ) + .unwrap(), + ) }) }); group.bench_function("pkcs1v15_verify_sha384", |b| { b.iter(|| { - RSASSA_PKCS1_v1_5_SHA384::verify( + VerifyingKey::::verify( black_box(&pk), black_box(MSG), None, @@ -124,12 +152,19 @@ fn bench_rsa_4096(c: &mut Criterion) { }); group.bench_function("pkcs1v15_sign_sha512", |b| { b.iter(|| { - black_box(RSASSA_PKCS1_v1_5_SHA512::sign(black_box(&sk), black_box(MSG), None).unwrap()) + black_box( + DeterministicSigningKey::::sign_deterministic( + black_box(&sk), + black_box(MSG), + None, + ) + .unwrap(), + ) }) }); group.bench_function("pkcs1v15_verify_sha512", |b| { b.iter(|| { - RSASSA_PKCS1_v1_5_SHA512::verify( + VerifyingKey::::verify( black_box(&pk), black_box(MSG), None, @@ -141,10 +176,11 @@ fn bench_rsa_4096(c: &mut Criterion) { group.bench_function("pss_sign_sha256", |b| { b.iter(|| { black_box( - RSASSA_PSS_SHA256::sign_randomized( + SigningKey::::sign( black_box(&sk), - black_box(MSG), &mut DefaultRNG::default(), + black_box(MSG), + None, ) .unwrap(), ) @@ -152,17 +188,23 @@ fn bench_rsa_4096(c: &mut Criterion) { }); group.bench_function("pss_verify_sha256", |b| { b.iter(|| { - RSASSA_PSS_SHA256::verify(black_box(&pk), black_box(MSG), None, black_box(&sig_pss_256)) - .unwrap() + VerifyingKey::::verify( + black_box(&pk), + black_box(MSG), + None, + black_box(&sig_pss_256), + ) + .unwrap() }) }); group.bench_function("pss_sign_sha384", |b| { b.iter(|| { black_box( - RSASSA_PSS_SHA384::sign_randomized( + SigningKey::::sign( black_box(&sk), - black_box(MSG), &mut DefaultRNG::default(), + black_box(MSG), + None, ) .unwrap(), ) @@ -170,17 +212,23 @@ fn bench_rsa_4096(c: &mut Criterion) { }); group.bench_function("pss_verify_sha384", |b| { b.iter(|| { - RSASSA_PSS_SHA384::verify(black_box(&pk), black_box(MSG), None, black_box(&sig_pss_384)) - .unwrap() + VerifyingKey::::verify( + black_box(&pk), + black_box(MSG), + None, + black_box(&sig_pss_384), + ) + .unwrap() }) }); group.bench_function("pss_sign_sha512", |b| { b.iter(|| { black_box( - RSASSA_PSS_SHA512::sign_randomized( + SigningKey::::sign( black_box(&sk), - black_box(MSG), &mut DefaultRNG::default(), + black_box(MSG), + None, ) .unwrap(), ) @@ -188,17 +236,23 @@ fn bench_rsa_4096(c: &mut Criterion) { }); group.bench_function("pss_verify_sha512", |b| { b.iter(|| { - RSASSA_PSS_SHA512::verify(black_box(&pk), black_box(MSG), None, black_box(&sig_pss_512)) - .unwrap() + VerifyingKey::::verify( + black_box(&pk), + black_box(MSG), + None, + black_box(&sig_pss_512), + ) + .unwrap() }) }); group.bench_function("pss_sign_shake256", |b| { b.iter(|| { black_box( - RSASSA_PSS_SHAKE256::sign_randomized( + SigningKey::::sign( black_box(&sk), - black_box(MSG), &mut DefaultRNG::default(), + black_box(MSG), + None, ) .unwrap(), ) @@ -206,7 +260,7 @@ fn bench_rsa_4096(c: &mut Criterion) { }); group.bench_function("pss_verify_shake256", |b| { b.iter(|| { - RSASSA_PSS_SHAKE256::verify( + VerifyingKey::::verify( black_box(&pk), black_box(MSG), None, diff --git a/crypto/rsa/benches/rsa_8192_benches.rs b/crypto/rsa/benches/rsa_8192_benches.rs index 166ee354..cb20348e 100644 --- a/crypto/rsa/benches/rsa_8192_benches.rs +++ b/crypto/rsa/benches/rsa_8192_benches.rs @@ -3,9 +3,10 @@ //! 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::signature_key::{DeterministicSigningKey, SigningKey, VerifyingKey}; use bouncycastle_core::traits::{ KEMDecapsulator, KEMEncapsulator, KEMPrivateKey, KEMPublicKey, SignaturePrivateKey, - SignaturePublicKey, SignatureVerifier, Signer, + SignaturePublicKey, }; use bouncycastle_rsa::rsa_8192::{RSA8192KEMPrivateKey, RSA8192KEMPublicKey, RSASVE}; use criterion::{Criterion, criterion_group, criterion_main}; @@ -119,23 +120,45 @@ fn bench_rsa_8192(c: &mut Criterion) { let pk = RSA8192PublicKey::new(sk.n(), 0x10001).unwrap(); let mut rng = DefaultRNG::default(); - let sig_pkcs1_256 = RSASSA_PKCS1_v1_5_SHA256::sign(&sk, MSG, None).unwrap(); - let sig_pkcs1_384 = RSASSA_PKCS1_v1_5_SHA384::sign(&sk, MSG, None).unwrap(); - let sig_pkcs1_512 = RSASSA_PKCS1_v1_5_SHA512::sign(&sk, MSG, None).unwrap(); - let sig_pss_256 = RSASSA_PSS_SHA256::sign_randomized(&sk, MSG, &mut rng).unwrap(); - let sig_pss_384 = RSASSA_PSS_SHA384::sign_randomized(&sk, MSG, &mut rng).unwrap(); - let sig_pss_512 = RSASSA_PSS_SHA512::sign_randomized(&sk, MSG, &mut rng).unwrap(); + let sig_pkcs1_256 = + DeterministicSigningKey::::sign_deterministic( + &sk, MSG, None, + ) + .unwrap(); + let sig_pkcs1_384 = + DeterministicSigningKey::::sign_deterministic( + &sk, MSG, None, + ) + .unwrap(); + let sig_pkcs1_512 = + DeterministicSigningKey::::sign_deterministic( + &sk, MSG, None, + ) + .unwrap(); + let sig_pss_256 = + SigningKey::::sign(&sk, &mut rng, MSG, None).unwrap(); + let sig_pss_384 = + SigningKey::::sign(&sk, &mut rng, MSG, None).unwrap(); + let sig_pss_512 = + SigningKey::::sign(&sk, &mut rng, MSG, None).unwrap(); let mut group = c.benchmark_group("rsa_8192"); group.bench_function("pkcs1v15_sign_sha256", |b| { b.iter(|| { - black_box(RSASSA_PKCS1_v1_5_SHA256::sign(black_box(&sk), black_box(MSG), None).unwrap()) + black_box( + DeterministicSigningKey::::sign_deterministic( + black_box(&sk), + black_box(MSG), + None, + ) + .unwrap(), + ) }) }); group.bench_function("pkcs1v15_verify_sha256", |b| { b.iter(|| { - RSASSA_PKCS1_v1_5_SHA256::verify( + VerifyingKey::::verify( black_box(&pk), black_box(MSG), None, @@ -146,12 +169,19 @@ fn bench_rsa_8192(c: &mut Criterion) { }); group.bench_function("pkcs1v15_sign_sha384", |b| { b.iter(|| { - black_box(RSASSA_PKCS1_v1_5_SHA384::sign(black_box(&sk), black_box(MSG), None).unwrap()) + black_box( + DeterministicSigningKey::::sign_deterministic( + black_box(&sk), + black_box(MSG), + None, + ) + .unwrap(), + ) }) }); group.bench_function("pkcs1v15_verify_sha384", |b| { b.iter(|| { - RSASSA_PKCS1_v1_5_SHA384::verify( + VerifyingKey::::verify( black_box(&pk), black_box(MSG), None, @@ -162,12 +192,19 @@ fn bench_rsa_8192(c: &mut Criterion) { }); group.bench_function("pkcs1v15_sign_sha512", |b| { b.iter(|| { - black_box(RSASSA_PKCS1_v1_5_SHA512::sign(black_box(&sk), black_box(MSG), None).unwrap()) + black_box( + DeterministicSigningKey::::sign_deterministic( + black_box(&sk), + black_box(MSG), + None, + ) + .unwrap(), + ) }) }); group.bench_function("pkcs1v15_verify_sha512", |b| { b.iter(|| { - RSASSA_PKCS1_v1_5_SHA512::verify( + VerifyingKey::::verify( black_box(&pk), black_box(MSG), None, @@ -179,10 +216,11 @@ fn bench_rsa_8192(c: &mut Criterion) { group.bench_function("pss_sign_sha256", |b| { b.iter(|| { black_box( - RSASSA_PSS_SHA256::sign_randomized( + SigningKey::::sign( black_box(&sk), - black_box(MSG), &mut DefaultRNG::default(), + black_box(MSG), + None, ) .unwrap(), ) @@ -190,17 +228,23 @@ fn bench_rsa_8192(c: &mut Criterion) { }); group.bench_function("pss_verify_sha256", |b| { b.iter(|| { - RSASSA_PSS_SHA256::verify(black_box(&pk), black_box(MSG), None, black_box(&sig_pss_256)) - .unwrap() + VerifyingKey::::verify( + black_box(&pk), + black_box(MSG), + None, + black_box(&sig_pss_256), + ) + .unwrap() }) }); group.bench_function("pss_sign_sha384", |b| { b.iter(|| { black_box( - RSASSA_PSS_SHA384::sign_randomized( + SigningKey::::sign( black_box(&sk), - black_box(MSG), &mut DefaultRNG::default(), + black_box(MSG), + None, ) .unwrap(), ) @@ -208,17 +252,23 @@ fn bench_rsa_8192(c: &mut Criterion) { }); group.bench_function("pss_verify_sha384", |b| { b.iter(|| { - RSASSA_PSS_SHA384::verify(black_box(&pk), black_box(MSG), None, black_box(&sig_pss_384)) - .unwrap() + VerifyingKey::::verify( + black_box(&pk), + black_box(MSG), + None, + black_box(&sig_pss_384), + ) + .unwrap() }) }); group.bench_function("pss_sign_sha512", |b| { b.iter(|| { black_box( - RSASSA_PSS_SHA512::sign_randomized( + SigningKey::::sign( black_box(&sk), - black_box(MSG), &mut DefaultRNG::default(), + black_box(MSG), + None, ) .unwrap(), ) @@ -226,8 +276,13 @@ fn bench_rsa_8192(c: &mut Criterion) { }); group.bench_function("pss_verify_sha512", |b| { b.iter(|| { - RSASSA_PSS_SHA512::verify(black_box(&pk), black_box(MSG), None, black_box(&sig_pss_512)) - .unwrap() + VerifyingKey::::verify( + black_box(&pk), + black_box(MSG), + None, + black_box(&sig_pss_512), + ) + .unwrap() }) }); diff --git a/crypto/rsa/src/emsa_pkcs1_v1_5.rs b/crypto/rsa/src/emsa_pkcs1_v1_5.rs index 48fb7323..f52a13a8 100644 --- a/crypto/rsa/src/emsa_pkcs1_v1_5.rs +++ b/crypto/rsa/src/emsa_pkcs1_v1_5.rs @@ -206,7 +206,7 @@ mod tests { //! SHA-256/384/512. use super::*; - use bouncycastle_core::traits::Hash; + 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 @@ -214,14 +214,14 @@ mod tests { /// locally so these tests can speak in terms of messages. fn encode(message: &[u8]) -> [u8; K_LEN] { let mut digest = [0u8; 32]; - SHA256::default().hash_out(message, &mut digest); + 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::default().hash_out(message, &mut digest); + SHA256::hash_out(message, &mut digest); emsa_pkcs1_v1_5_verify_from_hash::(&digest, em) } @@ -306,7 +306,7 @@ mod tests { #[test] fn verify_accepts_digest_info_with_null_parameters_absent() { let mut digest = [0u8; 32]; - SHA256::default().hash_out(b"hello", &mut digest); + 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. diff --git a/crypto/rsa/src/emsa_pss.rs b/crypto/rsa/src/emsa_pss.rs index c3aec041..f5292bee 100644 --- a/crypto/rsa/src/emsa_pss.rs +++ b/crypto/rsa/src/emsa_pss.rs @@ -11,7 +11,7 @@ //! generic bit-count parameter through for a case that cannot arise. use crate::mgf1::mgf1; -use bouncycastle_core::traits::Hash; +use bouncycastle_core::traits::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 @@ -23,7 +23,7 @@ use bouncycastle_core::traits::Hash; /// pairing this crate wires up has a modulus far wider than any hash-plus-salt combination it /// offers. pub fn emsa_pss_encode_from_hash< - H: Hash + Default, + H: HashOneShot, const H_LEN: usize, const SEED_LEN: usize, const S_LEN: usize, @@ -46,7 +46,7 @@ pub fn emsa_pss_encode_from_hash< m_prime[8..8 + H_LEN].copy_from_slice(m_hash); m_prime[8 + H_LEN..].copy_from_slice(salt); let mut h = [0u8; H_LEN]; - H::default().hash_out(&m_prime, &mut h); + H::hash_out(&m_prime, &mut h); // Steps 7-8: DB = PS || 0x01 || salt (PS is all-zero, already the array's initial value). let mut db = [0u8; DB_LEN]; @@ -74,7 +74,7 @@ pub fn emsa_pss_encode_from_hash< /// same way. Step 1's message-length limit and step 3's minimum-`emLen` check are not reachable /// for this crate's fixed sizes, for the same reasons given there. pub fn emsa_pss_verify_from_hash< - H: Hash + Default, + H: HashOneShot, const H_LEN: usize, const SEED_LEN: usize, const S_LEN: usize, @@ -123,7 +123,7 @@ pub fn emsa_pss_verify_from_hash< m_prime[8..8 + H_LEN].copy_from_slice(m_hash); m_prime[8 + H_LEN..].copy_from_slice(&salt); let mut h_prime = [0u8; H_LEN]; - H::default().hash_out(&m_prime, &mut h_prime); + H::hash_out(&m_prime, &mut h_prime); h == h_prime } @@ -169,7 +169,7 @@ mod tests { fn m_hash(message: &[u8]) -> [u8; 32] { let mut m_hash = [0u8; 32]; - SHA256::default().hash_out(message, &mut m_hash); + SHA256::hash_out(message, &mut m_hash); m_hash } diff --git a/crypto/rsa/src/emsa_pss_shake.rs b/crypto/rsa/src/emsa_pss_shake.rs index a7fe1582..d0056e34 100644 --- a/crypto/rsa/src/emsa_pss_shake.rs +++ b/crypto/rsa/src/emsa_pss_shake.rs @@ -13,14 +13,14 @@ //! SHAKE256) -- already this crate's own "typical" salt-length convention for MGF1-based PSS, so //! no new relationship needs stating. -use bouncycastle_core::traits::XOF; +use bouncycastle_core::traits::{HashOneShot, XOF}; /// EMSA-PSS-ENCODE (RFC 8017 §9.1.1) from step 3 onward with the mask generation function /// replaced by native SHAKE output (RFC 8702 §3.2.1), given steps 1-2's `mHash = Hash(M)` by the /// caller exactly as [`crate::emsa_pss::emsa_pss_encode_from_hash`] is. See the module docs for /// `emBits` and the salt argument. pub fn emsa_pss_encode_shake_from_hash< - X: XOF + Default, + X: XOF + HashOneShot, const H_LEN: usize, const S_LEN: usize, const M_PRIME_LEN: usize, @@ -42,7 +42,7 @@ pub fn emsa_pss_encode_shake_from_hash< m_prime[8..8 + H_LEN].copy_from_slice(m_hash); m_prime[8 + H_LEN..].copy_from_slice(salt); let mut h = [0u8; H_LEN]; - X::default().hash_out(&m_prime, &mut h); + X::hash_out(&m_prime, &mut h); // Steps 7-8: DB = PS || 0x01 || salt (PS is all-zero, already the array's initial value). let mut db = [0u8; DB_LEN]; @@ -71,7 +71,7 @@ pub fn emsa_pss_encode_shake_from_hash< /// replaced by native SHAKE output, as [`emsa_pss_encode_shake_from_hash`], and step 2's /// `mHash = Hash(M)` supplied by the caller the same way. pub fn emsa_pss_verify_shake_from_hash< - X: XOF + Default, + X: XOF + HashOneShot, const H_LEN: usize, const S_LEN: usize, const M_PRIME_LEN: usize, @@ -120,7 +120,7 @@ pub fn emsa_pss_verify_shake_from_hash< m_prime[8..8 + H_LEN].copy_from_slice(m_hash); m_prime[8 + H_LEN..].copy_from_slice(&salt); let mut h_prime = [0u8; H_LEN]; - X::default().hash_out(&m_prime, &mut h_prime); + X::hash_out(&m_prime, &mut h_prime); h == h_prime } @@ -136,7 +136,7 @@ mod tests { //! `mHash = Hash(M)` back on top, so the tests can speak in terms of messages. use super::*; - use bouncycastle_core::traits::Hash; + use bouncycastle_sha3::SHAKE128; const SALT: [u8; 32] = [ @@ -147,7 +147,7 @@ mod tests { fn m_hash(message: &[u8]) -> [u8; 32] { let mut m_hash = [0u8; 32]; - SHAKE128::default().hash_out(message, &mut m_hash); + SHAKE128::hash_out(message, &mut m_hash); m_hash } diff --git a/crypto/rsa/src/keygen.rs b/crypto/rsa/src/keygen.rs index bd158726..20cd5aa1 100644 --- a/crypto/rsa/src/keygen.rs +++ b/crypto/rsa/src/keygen.rs @@ -6,7 +6,7 @@ //! (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`/`keygen_from_rng` in their own modules +//! The concrete sizes wire this up as `keygen(rng)` in their own modules //! (`crate::rsa_2048::keygen` and siblings): `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. @@ -142,7 +142,7 @@ fn inv_mod_u64_prime(r: u64, e: u64) -> u64 { 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_from_rng` discards any `p` (or `q`) with + // `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); @@ -490,7 +490,7 @@ fn primes_too_close(p: &[u64; N], q: &[u64; N]) -> bool { /// 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 `crate::rsa_2048::keygen_from_rng` for the RSA-2048 values. +/// fix all three; see `crate::rsa_2048::keygen` 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 diff --git a/crypto/rsa/src/keys.rs b/crypto/rsa/src/keys.rs index ffb3a735..63a79359 100644 --- a/crypto/rsa/src/keys.rs +++ b/crypto/rsa/src/keys.rs @@ -18,6 +18,7 @@ use crate::codec::{be_bytes_from_limbs, limbs_from_be_bytes}; use bouncycastle_core::errors::SignatureError; +use bouncycastle_core::security_strength::SecurityStrength; use bouncycastle_ec::montgomery; use bouncycastle_ec::nat; use bouncycastle_utils::secret::Secret; @@ -299,3 +300,19 @@ impl RsaPrivateKey { Self::from_crt_components(&p, &q, &d_p, &d_q, &q_inv) } } + +/// The security strength SP 800-57 Part 1 Rev. 5 Table 2 assigns a modulus of `limbs` 64-bit +/// limbs: 2048 bits give 112, 3072 give 128 (4096 rounds down to the same), 7680 and above give +/// 192; anything narrower is below the table and reports [`SecurityStrength::None`]. +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 + } +} diff --git a/crypto/rsa/src/lib.rs b/crypto/rsa/src/lib.rs index eff46487..f12c5206 100644 --- a/crypto/rsa/src/lib.rs +++ b/crypto/rsa/src/lib.rs @@ -12,21 +12,25 @@ //! RSAES-PKCS1-v1_5 encryption, and so no KTS-OAEP. Modulus sizes 2048 //! through 8192 bits ([`rsa_2048`], [`rsa_3072`], [`rsa_4096`], [`rsa_8192`]) support both signing //! and verification; 1024- and 1536-bit moduli ([`rsa_1024`], [`rsa_1536`]) support verification -//! only, enforced by the absence of a private-key type (and so of any `Signer` impl) for those -//! sizes rather than a runtime check. -//! -//! Every (scheme, hash, modulus size) pairing is a type implementing [`bouncycastle_core`]'s -//! [`Signer`](bouncycastle_core::traits::Signer)/[`SignatureVerifier`](bouncycastle_core::traits::SignatureVerifier) -//! traits (`RSASSA_PKCS1_v1_5_SHA256` and siblings in each size module), one-shot or streaming -//! (`_init`/`_update`/`_final`), the same API shape as this workspace's ECDSA, SM2 and ML-DSA -//! crates. RSASSA-PSS's salt comes from the library's default RNG through `Signer::sign`, from -//! a caller-supplied RNG through `sign_randomized`, or is fixed through `set_signer_salt` on a -//! streaming state. The key types implement +//! only, enforced by the absence of a private-key type (and so of any signing-role impl) for +//! those sizes rather than a runtime check. +//! +//! Every (scheme, hash, modulus size) pairing is an algorithm marker type +//! (`RSASSA_PKCS1_v1_5_SHA256` and siblings in each size module) that the key role traits of +//! [`bouncycastle_core::signature_key`] are implemented over: the private key signs through +//! [`SigningKey`](bouncycastle_core::signature_key::SigningKey) for RSASSA-PSS (a fresh salt from +//! the caller's RNG per signer) and +//! [`DeterministicSigningKey`](bouncycastle_core::signature_key::DeterministicSigningKey) for +//! RSASSA-PKCS1-v1_5, and the public key verifies through +//! [`VerifyingKey`](bouncycastle_core::signature_key::VerifyingKey); one-shot or streaming, the +//! same API shape as this workspace's ECDSA, SM2 and ML-DSA crates. One key type serves every +//! scheme and hash, so a call names the marker: `SigningKey::::sign(&sk, +//! &mut rng, msg, None)`. The key types implement //! [`SignaturePrivateKey`](bouncycastle_core::traits::SignaturePrivateKey)/[`SignaturePublicKey`](bouncycastle_core::traits::SignaturePublicKey) -//! per size, and each signing size's module offers `keygen`/`keygen_from_rng` (FIPS 186-5 -//! Appendix A.1.3, in [`keygen`]), the same pair the ECDSA crate's curves offer. The generic -//! `rsassa_*` modules also expose `*_from_hash` entry points that take the message hash rather -//! than the message, for a caller that already holds the digest. +//! per size, and each signing size's module offers `keygen(rng)` (FIPS 186-5 Appendix A.1.3, in +//! [`keygen`]), as the ECDSA crate's curves do. The generic `rsassa_*` modules also expose +//! `*_from_hash` entry points that take the message hash rather than the message, for a caller +//! that already holds the digest. //! //! 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` in each of the 2048/3072/4096/8192 size modules. @@ -34,20 +38,22 @@ //! [`KEMEncapsulator`](bouncycastle_core::traits::KEMEncapsulator)/[`KEMDecapsulator`](bouncycastle_core::traits::KEMDecapsulator) //! over its own key types (`RSA2048KEMPrivateKey`/`RSA2048KEMPublicKey` and siblings), which are //! kept apart from the signing key types; see [`rsasve`]'s `# Key separation`. Key generation is -//! `RSASVE::keygen`/`keygen_from_rng`, the same FIPS 186-5 generator the signature keys use. The +//! `RSASVE::keygen(rng)`, the same FIPS 186-5 generator the signature keys use. The //! shared secret is RSASVE's raw secret value `Z`, the full modulus length. It is not a derived key. //! //! # Usage Examples //! -//! RSA-2048 with SHA-256 through the `bouncycastle_core` signature traits ([`rsa_2048`]), the -//! way code written against those traits (and this workspace's CLI) uses every signature scheme: +//! RSA-2048 with SHA-256 through the `bouncycastle_core` key role traits ([`rsa_2048`]), the way +//! code written against those traits (and this workspace's CLI) uses every signature scheme: //! //! ``` -//! use bouncycastle_core::traits::{SignaturePrivateKey, SignaturePublicKey, SignatureVerifier, Signer}; -//! use bouncycastle_rsa::rsa_2048::{RSASSA_PKCS1_v1_5_SHA256, RSASSA_PSS_SHA256, RSA2048PrivateKey, RSA2048PublicKey}; +//! use bouncycastle_core::signature_key::{DeterministicSigningKey, SigningKey, VerifyingKey}; +//! use bouncycastle_core::traits::{SignaturePrivateKey, SignaturePublicKey, SignatureSigner, SignatureVerifier}; +//! use bouncycastle_rng::HashDRBG_SHA512; +//! use bouncycastle_rsa::rsa_2048::{RSASSA_PKCS1_v1_5_SHA256, RSASSA_PSS_SHA256, RSA2048PrivateKey, RSA2048PublicKey, SIG_LEN}; //! # // 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 `bouncycastle_rsa::rsa_2048::keygen()?` instead -- a few seconds of +//! # // pair comes from `bouncycastle_rsa::rsa_2048::keygen(&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]; @@ -56,50 +62,47 @@ //! # const Q_INV: [u64; 16] = [0x552fe4bfce945f7b, 0x67e50c999c67247b, 0xfb54ef17be3b2853, 0x241f5921b5ad3983, 0x02de5eccd143cf31, 0x74e45f6fcc60f216, 0xafa5428a74f12708, 0x88d42294b6a2759b, 0xe923e1097c0c562f, 0xc968b48a91c38b5b, 0x933e85179c0320b0, 0x7993d0445f758d51, 0x9bfc042ee0924b1b, 0x41f956d90fa8a793, 0xee7a87b6483a66ee, 0x2640fbfbcfefb163]; //! let sk = RSA2048PrivateKey::from_crt_components(&P, &Q, &D_P, &D_Q, &Q_INV)?; //! let pk = RSA2048PublicKey::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). -//! let signature = RSASSA_PKCS1_v1_5_SHA256::sign(&sk, b"the message to sign", None)?; -//! RSASSA_PKCS1_v1_5_SHA256::verify(&pk, b"the message to sign", None, &signature)?; +//! // PKCS#1 v1.5 draws nothing, so it is the deterministic role. +//! let signature = DeterministicSigningKey::::sign_deterministic(&sk, b"the message to sign", None)?; +//! VerifyingKey::::verify(&pk, b"the message to sign", None, &signature)?; //! //! // Streaming: the message arrives in chunks and is hashed as it goes. -//! let mut signer = RSASSA_PKCS1_v1_5_SHA256::do_sign_init(&sk, None)?; -//! signer.do_sign_update(b"the message "); -//! signer.do_sign_update(b"to sign"); -//! let streamed = signer.do_sign_final()?; +//! let mut signer = DeterministicSigningKey::::create_signer_deterministic(&sk, 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 = RSASSA_PKCS1_v1_5_SHA256::do_verify_init(&pk, None)?; -//! verifier.do_verify_update(b"the message to sign"); +//! let mut verifier = VerifyingKey::::create_verifier(&pk, 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 as invalid -//! // (RFC 8017 §8.2.2 step 1), as is one over a different message. -//! assert!(RSASSA_PKCS1_v1_5_SHA256::verify(&pk, b"the message to sign", None, &signature[1..]).is_err()); -//! assert!(RSASSA_PKCS1_v1_5_SHA256::verify(&pk, b"a different message", None, &signature).is_err()); +//! // `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!(VerifyingKey::::verify(&pk, b"the message to sign", None, &signature[1..]).is_err()); +//! assert!(VerifyingKey::::verify(&pk, b"a different message", None, &signature).is_err()); //! -//! // RSASSA-PSS through the same traits draws its salt from the library's default RNG. -//! let sig_a = RSASSA_PSS_SHA256::sign(&sk, b"the message to sign", None)?; -//! let sig_b = RSASSA_PSS_SHA256::sign(&sk, b"the message to sign", None)?; +//! // RSASSA-PSS draws its salt from the RNG handed to the signer, so two signatures differ. +//! let sig_a = SigningKey::::sign(&sk, &mut rng, b"the message to sign", None)?; +//! let sig_b = SigningKey::::sign(&sk, &mut rng, b"the message to sign", None)?; //! assert_ne!(sig_a, sig_b); -//! RSASSA_PSS_SHA256::verify(&pk, b"the message to sign", None, &sig_a)?; -//! RSASSA_PSS_SHA256::verify(&pk, b"the message to sign", None, &sig_b)?; -//! -//! // ... or from a caller-supplied RNG (as ECDSA's and SM2's `sign_randomized`), ... -//! use bouncycastle_rng::DefaultRNG; -//! let sig_c = RSASSA_PSS_SHA256::sign_randomized(&sk, b"the message to sign", &mut DefaultRNG::default())?; -//! RSASSA_PSS_SHA256::verify(&pk, b"the message to sign", None, &sig_c)?; -//! -//! // ... or fixed on a streaming state (as ML-DSA's `set_signer_rnd`), which makes PSS -//! // deterministic -- for a caller with its own randomness source, or a test against a known salt. -//! let mut signer = RSASSA_PSS_SHA256::do_sign_init(&sk, None)?; -//! signer.set_signer_salt([0x42u8; 32]); -//! signer.do_sign_update(b"the message to sign"); -//! let sig_d = signer.do_sign_final()?; -//! let mut signer = RSASSA_PSS_SHA256::do_sign_init(&sk, None)?; -//! signer.set_signer_salt([0x42u8; 32]); -//! signer.do_sign_update(b"the message to sign"); -//! assert_eq!(signer.do_sign_final()?, sig_d); -//! RSASSA_PSS_SHA256::verify(&pk, b"the message to sign", None, &sig_d)?; +//! VerifyingKey::::verify(&pk, b"the message to sign", None, &sig_a)?; +//! VerifyingKey::::verify(&pk, 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 = SigningKey::::create_signer(&sk, &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 = SigningKey::::create_signer(&sk, &mut rng, None)?; +//! signer.set_salt([0x42u8; 32]); +//! signer.do_update(b"the message to sign"); +//! assert_eq!(signer.do_final()?, sig_d); +//! VerifyingKey::::verify(&pk, b"the message to sign", None, &sig_d)?; //! //! // Keys round-trip through the traits' raw fixed-width encoding (see `keys`'s docs). //! let pk_again = RSA2048PublicKey::from_bytes(&pk.encode())?; @@ -109,19 +112,19 @@ //! # Ok::<(), bouncycastle_core::errors::SignatureError>(()) //! ``` //! -//! RSA-1024 verification, the other major usage pattern: no private key or `Signer` exists for -//! this size at all (see `# Scope` above), only a `SignatureVerifier` for signatures produced +//! 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` 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::traits::SignatureVerifier; -//! use bouncycastle_rsa::rsa_1024::{RSASSA_PKCS1_v1_5_SHA256, RSA1024PublicKey}; +//! use bouncycastle_core::signature_key::VerifyingKey; +//! use bouncycastle_rsa::rsa_1024::{RSASSA_PKCS1_v1_5_SHA256, RSA1024PublicKey, SIG_LEN}; //! # 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 = RSA1024PublicKey::new(&N, 0x10001)?; -//! RSASSA_PKCS1_v1_5_SHA256::verify(&pk, &msg, None, &sig)?; +//! VerifyingKey::::verify(&pk, &msg, None, &sig)?; //! # Ok::<(), bouncycastle_core::errors::SignatureError>(()) //! ``` //! @@ -166,9 +169,8 @@ //! //! 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, `sign_randomized` and -//! `set_signer_salt` included -- see [`rsa_2048`]'s own docs rather than a second, near-identical -//! example here. +//! 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 //! @@ -256,16 +258,15 @@ //! 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.** `Signer::sign` draws it from the -//! library's default OS-backed RNG; `sign_randomized` takes the caller's RNG and -//! `set_signer_salt` takes the salt itself. Unlike ECDSA's per-message secret `k`, a repeated +//! - **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; `Signer`/`SignatureVerifier`'s `ctx` parameter is accepted for trait +//! 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. diff --git a/crypto/rsa/src/mgf1.rs b/crypto/rsa/src/mgf1.rs index 69e29d17..0c36b761 100644 --- a/crypto/rsa/src/mgf1.rs +++ b/crypto/rsa/src/mgf1.rs @@ -3,7 +3,7 @@ //! always the hash's own `hLen`-byte output) rather than MGF1's fully general arbitrary-length //! seed: `mgfSeed` here is always exactly `H_LEN` bytes. -use bouncycastle_core::traits::Hash; +use bouncycastle_core::traits::HashOneShot; /// 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 @@ -13,7 +13,7 @@ use bouncycastle_core::traits::Hash; /// (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. -pub fn mgf1( +pub fn mgf1( seed: &[u8; H_LEN], ) -> [u8; MASK_LEN] { debug_assert_eq!(SEED_LEN, H_LEN + 4, "mgf1 needs SEED_LEN == H_LEN + 4"); @@ -27,7 +27,7 @@ pub fn mgf1` does not (no size module -//! declares it). Enforced by the compiler, as this doctest pins: +//! ([`RSASSA_PKCS1_v1_5_SHA256`], [`RSASSA_PKCS1_v1_5_SHA384`]): [`RSA1024PublicKey`] implements +//! `VerifyingKey` for them, but no key implements `DeterministicSigningKey`, because the signing +//! role is only implemented where the private key type implements `SignaturePrivateKey`, and +//! `RsaPrivateKey<16, 8>` does not (no size module declares it). Enforced by the compiler, as +//! this doctest pins: //! -//! ```compile_fail -//! use bouncycastle_core::traits::Signer; +//! ```compile_fail,E0277 +//! use bouncycastle_core::signature_key::DeterministicSigningKey; //! use bouncycastle_rsa::keys::RsaPrivateKey; -//! use bouncycastle_rsa::rsa_1024::RSASSA_PKCS1_v1_5_SHA256; +//! use bouncycastle_rsa::rsa_1024::{RSASSA_PKCS1_v1_5_SHA256, SIG_LEN}; //! //! fn sign_1024(sk: &RsaPrivateKey<16, 8>) { -//! // error: no function or associated item named `sign` -- there is no `Signer` impl. -//! let _ = RSASSA_PKCS1_v1_5_SHA256::sign(sk, b"", None); +//! // error: the trait bound `RsaPrivateKey<16, 8>: DeterministicSigningKey<..>` is not satisfied. +//! let _ = DeterministicSigningKey::::sign_deterministic(sk, b"", None); //! } //! ``` @@ -64,7 +65,7 @@ impl SignaturePublicKey for RSA1024PublicKey { /// [`RSASSA_PKCS1_v1_5`] at this size's widths. The signing-side /// widths the generic type also needs (`HALF = 8`, `HALF2 = 16`, `HALF21 = 17`, `SK_LEN = 320`) /// are what an RSA-1024 CRT key would have if one existed; they name the type but nothing uses -/// them, since the `Signer` impl they would feed does not exist for `RsaPrivateKey<16, 8>`. +/// them, since the signing-role impl they would feed does not exist for `RsaPrivateKey<16, 8>`. #[allow(non_camel_case_types)] pub type RSASSA_PKCS1_v1_5_SHA256 = RSASSA_PKCS1_v1_5; diff --git a/crypto/rsa/src/rsa_2048.rs b/crypto/rsa/src/rsa_2048.rs index 78c44f7b..c2884492 100644 --- a/crypto/rsa/src/rsa_2048.rs +++ b/crypto/rsa/src/rsa_2048.rs @@ -7,10 +7,10 @@ //! matching RFC 8017 §9.1 note 4's "typical" choice and Wycheproof's own //! `rsa_pss_2048_sha256_mgf1_32_test.json`/`..._sha384_mgf1_48_test.json`. //! -//! Each (scheme, hash) pairing is a type implementing `bouncycastle_core`'s -//! `Signer`/`SignatureVerifier` traits ([`RSASSA_PKCS1_v1_5_SHA256`], [`RSASSA_PSS_SHA256`], -//! [`RSASSA_PSS_SHAKE128`], ...): one-shot or streaming, with PSS's salt from the default RNG or -//! under the caller's control via `sign_randomized`/`set_signer_salt`. The key types implement +//! Each (scheme, hash) pairing is an algorithm marker the key role traits are implemented over +//! ([`RSASSA_PKCS1_v1_5_SHA256`], [`RSASSA_PSS_SHA256`], [`RSASSA_PSS_SHAKE128`], ...): one-shot +//! or streaming, with PSS's salt from the RNG handed to `create_signer` or fixed through `set_salt` +//! on the signer. The key types implement //! `SignaturePrivateKey`/`SignaturePublicKey` here, at this size's [`SK_LEN`]/[`PK_LEN`]. use crate::keys::{RsaPrivateKey, RsaPublicKey}; @@ -23,7 +23,6 @@ use bouncycastle_core::security_strength::SecurityStrength; use bouncycastle_core::traits::{ KEMPrivateKey, KEMPublicKey, RNG, SignaturePrivateKey, SignaturePublicKey, }; -use bouncycastle_rng::DefaultRNG; use bouncycastle_sha2::{SHA256, SHA384, SHA512}; use bouncycastle_sha3::SHAKE128; use core::num::NonZeroUsize; @@ -42,18 +41,10 @@ pub const PK_LEN: usize = 260; /// Signature length: `k`, the modulus length in octets (RFC 8017 §8.1.1/§8.2.1 step 2.c). pub const SIG_LEN: usize = 256; -/// FIPS 186-5 Appendix A.1.3 key pair generation for RSA-2048 (see [`crate::keygen`]), sourcing -/// the candidates from the library's default OS-backed RNG. `e` is [`crate::keygen::PUBLIC_EXPONENT`]. -pub fn keygen() -> Result<(RSA2048PublicKey, RSA2048PrivateKey), SignatureError> { - keygen_from_rng(&mut DefaultRNG::default()) -} - /// As [`keygen`], but sourcing the candidates from the caller-provided RNG, which must offer a /// security strength of at least 112 bits (SP 800-57 Part 1 Rev. 5, Table 2, `k = 2048`). Each /// candidate prime gets 5 Miller-Rabin rounds: FIPS 186-5 Table B.1's row for 1024-bit `p` and `q` at an error probability of `2^-112`, RSA-2048's security strength (SP 800-57 Part 1 Rev. 5, Table 2). -pub fn keygen_from_rng( - rng: &mut dyn RNG, -) -> Result<(RSA2048PublicKey, RSA2048PrivateKey), SignatureError> { +pub fn keygen(rng: &mut dyn RNG) -> Result<(RSA2048PublicKey, RSA2048PrivateKey), SignatureError> { crate::keygen::keygen_from_rng::<16, 32, 33>( rng, NonZeroUsize::new(5).expect("nonzero literal"), @@ -97,9 +88,9 @@ impl SignaturePublicKey for RSA2048PublicKey { } } -/// RSASSA-PKCS1-v1_5/SHA-256 over RSA-2048 as a `Signer`/`SignatureVerifier`: [`RSASSA_PKCS1_v1_5`] -/// at this size's widths. Deterministic: PKCS#1 v1.5 has no randomness, so `Signer::sign` -/// always reproduces the same signature. +/// RSASSA-PKCS1-v1_5/SHA-256 over RSA-2048 through the key role traits: [`RSASSA_PKCS1_v1_5`] +/// at this size's widths. Deterministic: PKCS#1 v1.5 has no randomness, so it is the +/// `DeterministicSigningKey` role and always reproduces the same signature. #[allow(non_camel_case_types)] pub type RSASSA_PKCS1_v1_5_SHA256 = RSASSA_PKCS1_v1_5; @@ -112,9 +103,9 @@ pub type RSASSA_PKCS1_v1_5_SHA384 = pub type RSASSA_PKCS1_v1_5_SHA512 = RSASSA_PKCS1_v1_5; -/// RSASSA-PSS/SHA-256 (MGF1-SHA-256, 32-byte salt) over RSA-2048 as a `Signer`/`SignatureVerifier`: -/// [`RSASSA_PSS`] at this size's widths, drawing its salt from the library's default RNG unless -/// `sign_randomized`/`set_signer_salt` supply it (see that type's docs). +/// RSASSA-PSS/SHA-256 (MGF1-SHA-256, 32-byte salt) over RSA-2048 through the key role traits: +/// [`RSASSA_PSS`] at this size's widths, drawing its salt from the RNG handed to `SigningKey::create_signer` +/// unless `set_salt` on the signer replaces it (see that type's docs). #[allow(non_camel_case_types)] pub type RSASSA_PSS_SHA256 = RSASSA_PSS; @@ -126,7 +117,7 @@ pub type RSASSA_PSS_SHA384 = #[allow(non_camel_case_types)] pub type RSASSA_PSS_SHA512 = RSASSA_PSS; -/// RSASSA-PSS-SHAKE128 (RFC 8702 §3.2.1) over RSA-2048 as a `Signer`/`SignatureVerifier`: +/// RSASSA-PSS-SHAKE128 (RFC 8702 §3.2.1) over RSA-2048 through the key role traits: /// [`RSASSA_PSS_SHAKE`] at this size's widths. #[allow(non_camel_case_types)] pub type RSASSA_PSS_SHAKE128 = @@ -152,18 +143,12 @@ pub const SS_LEN: usize = 256; pub type RSASVE = crate::rsasve::RSASVE<32, 64, 65, 16, 32, 33, 256, 112>; impl RSASVE { - /// Generates a key-establishment key pair with [`keygen`] (FIPS 186-5 Appendix A.1.3, - /// `e = 65537`), sourcing the candidates from the library's default OS-backed RNG. - pub fn keygen() -> Result<(RSA2048KEMPublicKey, RSA2048KEMPrivateKey), KEMError> { - Self::keygen_from_rng(&mut DefaultRNG::default()) - } - /// As [`Self::keygen`], but sourcing the candidates from the caller-provided RNG, with the - /// same RNG requirements as [`keygen_from_rng`]. - pub fn keygen_from_rng( + /// same RNG requirements as [`keygen`]. + pub fn keygen( rng: &mut dyn RNG, ) -> Result<(RSA2048KEMPublicKey, RSA2048KEMPrivateKey), KEMError> { - crate::rsasve::keygen_from(keygen_from_rng(rng)) + crate::rsasve::keygen_from(keygen(rng)) } } diff --git a/crypto/rsa/src/rsa_3072.rs b/crypto/rsa/src/rsa_3072.rs index 7c1f2b76..bbeed231 100644 --- a/crypto/rsa/src/rsa_3072.rs +++ b/crypto/rsa/src/rsa_3072.rs @@ -11,7 +11,6 @@ use bouncycastle_core::security_strength::SecurityStrength; use bouncycastle_core::traits::{ KEMPrivateKey, KEMPublicKey, RNG, SignaturePrivateKey, SignaturePublicKey, }; -use bouncycastle_rng::DefaultRNG; use bouncycastle_sha2::{SHA256, SHA384, SHA512}; use bouncycastle_sha3::SHAKE128; use core::num::NonZeroUsize; @@ -30,18 +29,10 @@ pub const PK_LEN: usize = 388; /// Signature length: `k`, the modulus length in octets (RFC 8017 §8.1.1/§8.2.1 step 2.c). pub const SIG_LEN: usize = 384; -/// FIPS 186-5 Appendix A.1.3 key pair generation for RSA-3072 (see [`crate::keygen`]), sourcing -/// the candidates from the library's default OS-backed RNG. `e` is [`crate::keygen::PUBLIC_EXPONENT`]. -pub fn keygen() -> Result<(RSA3072PublicKey, RSA3072PrivateKey), SignatureError> { - keygen_from_rng(&mut DefaultRNG::default()) -} - /// As [`keygen`], but sourcing the candidates from the caller-provided RNG, which must offer a /// security strength of at least 128 bits (SP 800-57 Part 1 Rev. 5, Table 2, `k = 3072`). Each /// candidate prime gets 4 Miller-Rabin rounds: FIPS 186-5 Table B.1's row for 1536-bit `p` and `q` at an error probability of `2^-128`, RSA-3072's security strength (SP 800-57 Part 1 Rev. 5, Table 2). -pub fn keygen_from_rng( - rng: &mut dyn RNG, -) -> Result<(RSA3072PublicKey, RSA3072PrivateKey), SignatureError> { +pub fn keygen(rng: &mut dyn RNG) -> Result<(RSA3072PublicKey, RSA3072PrivateKey), SignatureError> { crate::keygen::keygen_from_rng::<24, 48, 49>( rng, NonZeroUsize::new(4).expect("nonzero literal"), @@ -85,7 +76,7 @@ impl SignaturePublicKey for RSA3072PublicKey { } } -/// RSASSA-PKCS1-v1_5/SHA-256 over RSA-3072 as a `Signer`/`SignatureVerifier`; see +/// RSASSA-PKCS1-v1_5/SHA-256 over RSA-3072 through the key role traits; see /// [`crate::rsa_2048::RSASSA_PKCS1_v1_5_SHA256`] for the pattern. #[allow(non_camel_case_types)] pub type RSASSA_PKCS1_v1_5_SHA256 = @@ -99,7 +90,7 @@ pub type RSASSA_PKCS1_v1_5_SHA384 = pub type RSASSA_PKCS1_v1_5_SHA512 = RSASSA_PKCS1_v1_5; -/// RSASSA-PSS/SHA-256 over RSA-3072 as a `Signer`/`SignatureVerifier`; see +/// RSASSA-PSS/SHA-256 over RSA-3072 through the key role traits; see /// [`crate::rsa_2048::RSASSA_PSS_SHA256`] for the pattern (including where the salt comes from). #[allow(non_camel_case_types)] pub type RSASSA_PSS_SHA256 = @@ -112,7 +103,7 @@ pub type RSASSA_PSS_SHA384 = #[allow(non_camel_case_types)] pub type RSASSA_PSS_SHA512 = RSASSA_PSS; -/// RSASSA-PSS-SHAKE128 (RFC 8702 §3.2.1) over RSA-3072 as a `Signer`/`SignatureVerifier`. +/// RSASSA-PSS-SHAKE128 (RFC 8702 §3.2.1) over RSA-3072 through the key role traits. #[allow(non_camel_case_types)] pub type RSASSA_PSS_SHAKE128 = RSASSA_PSS_SHAKE; @@ -137,18 +128,12 @@ pub const SS_LEN: usize = 384; pub type RSASVE = crate::rsasve::RSASVE<48, 96, 97, 24, 48, 49, 384, 128>; impl RSASVE { - /// Generates a key-establishment key pair with [`keygen`] (FIPS 186-5 Appendix A.1.3, - /// `e = 65537`), sourcing the candidates from the library's default OS-backed RNG. - pub fn keygen() -> Result<(RSA3072KEMPublicKey, RSA3072KEMPrivateKey), KEMError> { - Self::keygen_from_rng(&mut DefaultRNG::default()) - } - /// As [`Self::keygen`], but sourcing the candidates from the caller-provided RNG, with the - /// same RNG requirements as [`keygen_from_rng`]. - pub fn keygen_from_rng( + /// same RNG requirements as [`keygen`]. + pub fn keygen( rng: &mut dyn RNG, ) -> Result<(RSA3072KEMPublicKey, RSA3072KEMPrivateKey), KEMError> { - crate::rsasve::keygen_from(keygen_from_rng(rng)) + crate::rsasve::keygen_from(keygen(rng)) } } diff --git a/crypto/rsa/src/rsa_4096.rs b/crypto/rsa/src/rsa_4096.rs index 18530600..b631e350 100644 --- a/crypto/rsa/src/rsa_4096.rs +++ b/crypto/rsa/src/rsa_4096.rs @@ -11,7 +11,6 @@ use bouncycastle_core::security_strength::SecurityStrength; use bouncycastle_core::traits::{ KEMPrivateKey, KEMPublicKey, RNG, SignaturePrivateKey, SignaturePublicKey, }; -use bouncycastle_rng::DefaultRNG; use bouncycastle_sha2::{SHA256, SHA384, SHA512}; use bouncycastle_sha3::SHAKE256; use core::num::NonZeroUsize; @@ -30,18 +29,10 @@ pub const PK_LEN: usize = 516; /// Signature length: `k`, the modulus length in octets (RFC 8017 §8.1.1/§8.2.1 step 2.c). pub const SIG_LEN: usize = 512; -/// FIPS 186-5 Appendix A.1.3 key pair generation for RSA-4096 (see [`crate::keygen`]), sourcing -/// the candidates from the library's default OS-backed RNG. `e` is [`crate::keygen::PUBLIC_EXPONENT`]. -pub fn keygen() -> Result<(RSA4096PublicKey, RSA4096PrivateKey), SignatureError> { - keygen_from_rng(&mut DefaultRNG::default()) -} - /// As [`keygen`], but sourcing the candidates from the caller-provided RNG, which must offer a /// security strength of at least 128 bits: SP 800-57 Part 1 Rev. 5, Table 2 lists 128 for `k = 3072` and 192 for `k = 7680`, so 4096 is at least 128. Each /// candidate prime gets 4 Miller-Rabin rounds: FIPS 186-5 Table B.1's row for 2048-bit `p` and `q` at an error probability of `2^-144` (the strength Table B.1 itself pairs with this size). -pub fn keygen_from_rng( - rng: &mut dyn RNG, -) -> Result<(RSA4096PublicKey, RSA4096PrivateKey), SignatureError> { +pub fn keygen(rng: &mut dyn RNG) -> Result<(RSA4096PublicKey, RSA4096PrivateKey), SignatureError> { crate::keygen::keygen_from_rng::<32, 64, 65>( rng, NonZeroUsize::new(4).expect("nonzero literal"), @@ -85,7 +76,7 @@ impl SignaturePublicKey for RSA4096PublicKey { } } -/// RSASSA-PKCS1-v1_5/SHA-256 over RSA-4096 as a `Signer`/`SignatureVerifier`; see +/// RSASSA-PKCS1-v1_5/SHA-256 over RSA-4096 through the key role traits; see /// [`crate::rsa_2048::RSASSA_PKCS1_v1_5_SHA256`] for the pattern. #[allow(non_camel_case_types)] pub type RSASSA_PKCS1_v1_5_SHA256 = @@ -99,7 +90,7 @@ pub type RSASSA_PKCS1_v1_5_SHA384 = pub type RSASSA_PKCS1_v1_5_SHA512 = RSASSA_PKCS1_v1_5; -/// RSASSA-PSS/SHA-256 over RSA-4096 as a `Signer`/`SignatureVerifier`; see +/// RSASSA-PSS/SHA-256 over RSA-4096 through the key role traits; see /// [`crate::rsa_2048::RSASSA_PSS_SHA256`] for the pattern (including where the salt comes from). #[allow(non_camel_case_types)] pub type RSASSA_PSS_SHA256 = @@ -112,7 +103,7 @@ pub type RSASSA_PSS_SHA384 = #[allow(non_camel_case_types)] pub type RSASSA_PSS_SHA512 = RSASSA_PSS; -/// RSASSA-PSS-SHAKE256 (RFC 8702 §3.2.1) over RSA-4096 as a `Signer`/`SignatureVerifier`. +/// RSASSA-PSS-SHAKE256 (RFC 8702 §3.2.1) over RSA-4096 through the key role traits. #[allow(non_camel_case_types)] pub type RSASSA_PSS_SHAKE256 = RSASSA_PSS_SHAKE; @@ -137,18 +128,12 @@ pub const SS_LEN: usize = 512; pub type RSASVE = crate::rsasve::RSASVE<64, 128, 129, 32, 64, 65, 512, 128>; impl RSASVE { - /// Generates a key-establishment key pair with [`keygen`] (FIPS 186-5 Appendix A.1.3, - /// `e = 65537`), sourcing the candidates from the library's default OS-backed RNG. - pub fn keygen() -> Result<(RSA4096KEMPublicKey, RSA4096KEMPrivateKey), KEMError> { - Self::keygen_from_rng(&mut DefaultRNG::default()) - } - /// As [`Self::keygen`], but sourcing the candidates from the caller-provided RNG, with the - /// same RNG requirements as [`keygen_from_rng`]. - pub fn keygen_from_rng( + /// same RNG requirements as [`keygen`]. + pub fn keygen( rng: &mut dyn RNG, ) -> Result<(RSA4096KEMPublicKey, RSA4096KEMPrivateKey), KEMError> { - crate::rsasve::keygen_from(keygen_from_rng(rng)) + crate::rsasve::keygen_from(keygen(rng)) } } diff --git a/crypto/rsa/src/rsa_8192.rs b/crypto/rsa/src/rsa_8192.rs index 4e268a41..a4b97e18 100644 --- a/crypto/rsa/src/rsa_8192.rs +++ b/crypto/rsa/src/rsa_8192.rs @@ -10,7 +10,6 @@ use bouncycastle_core::security_strength::SecurityStrength; use bouncycastle_core::traits::{ KEMPrivateKey, KEMPublicKey, RNG, SignaturePrivateKey, SignaturePublicKey, }; -use bouncycastle_rng::DefaultRNG; use bouncycastle_sha2::{SHA256, SHA384, SHA512}; use core::num::NonZeroUsize; @@ -28,18 +27,10 @@ pub const PK_LEN: usize = 1028; /// Signature length: `k`, the modulus length in octets (RFC 8017 §8.1.1/§8.2.1 step 2.c). pub const SIG_LEN: usize = 1024; -/// FIPS 186-5 Appendix A.1.3 key pair generation for RSA-8192 (see [`crate::keygen`]), sourcing -/// the candidates from the library's default OS-backed RNG. `e` is [`crate::keygen::PUBLIC_EXPONENT`]. -pub fn keygen() -> Result<(RSA8192PublicKey, RSA8192PrivateKey), SignatureError> { - keygen_from_rng(&mut DefaultRNG::default()) -} - /// As [`keygen`], but sourcing the candidates from the caller-provided RNG, which must offer a /// security strength of at least 192 bits (SP 800-57 Part 1 Rev. 5, Table 2: `k = 7680` gives 192, and 8192 exceeds it). Each /// candidate prime gets 4 Miller-Rabin rounds: FIPS 186-5 Table B.1 stops at 2048-bit primes; Appendix C.1's formula (2), which reproduces every entry of that table, gives 3 rounds for 4096-bit primes at `2^-192` (RSA-8192 exceeds SP 800-57's 7680-bit/192-bit row) and 5 at `2^-256`, so 4 is taken, matching the table's last row with margin. -pub fn keygen_from_rng( - rng: &mut dyn RNG, -) -> Result<(RSA8192PublicKey, RSA8192PrivateKey), SignatureError> { +pub fn keygen(rng: &mut dyn RNG) -> Result<(RSA8192PublicKey, RSA8192PrivateKey), SignatureError> { crate::keygen::keygen_from_rng::<64, 128, 129>( rng, NonZeroUsize::new(4).expect("nonzero literal"), @@ -83,7 +74,7 @@ impl SignaturePublicKey for RSA8192PublicKey { } } -/// RSASSA-PKCS1-v1_5/SHA-256 over RSA-8192 as a `Signer`/`SignatureVerifier`; see +/// RSASSA-PKCS1-v1_5/SHA-256 over RSA-8192 through the key role traits; see /// [`crate::rsa_2048::RSASSA_PKCS1_v1_5_SHA256`] for the pattern. #[allow(non_camel_case_types)] pub type RSASSA_PKCS1_v1_5_SHA256 = @@ -97,7 +88,7 @@ pub type RSASSA_PKCS1_v1_5_SHA384 = pub type RSASSA_PKCS1_v1_5_SHA512 = RSASSA_PKCS1_v1_5; -/// RSASSA-PSS/SHA-256 over RSA-8192 as a `Signer`/`SignatureVerifier`; see +/// RSASSA-PSS/SHA-256 over RSA-8192 through the key role traits; see /// [`crate::rsa_2048::RSASSA_PSS_SHA256`] for the pattern (including where the salt comes from). #[allow(non_camel_case_types)] pub type RSASSA_PSS_SHA256 = @@ -131,18 +122,12 @@ pub const SS_LEN: usize = 1024; pub type RSASVE = crate::rsasve::RSASVE<128, 256, 257, 64, 128, 129, 1024, 192>; impl RSASVE { - /// Generates a key-establishment key pair with [`keygen`] (FIPS 186-5 Appendix A.1.3, - /// `e = 65537`), sourcing the candidates from the library's default OS-backed RNG. - pub fn keygen() -> Result<(RSA8192KEMPublicKey, RSA8192KEMPrivateKey), KEMError> { - Self::keygen_from_rng(&mut DefaultRNG::default()) - } - /// As [`Self::keygen`], but sourcing the candidates from the caller-provided RNG, with the - /// same RNG requirements as [`keygen_from_rng`]. - pub fn keygen_from_rng( + /// same RNG requirements as [`keygen`]. + pub fn keygen( rng: &mut dyn RNG, ) -> Result<(RSA8192KEMPublicKey, RSA8192KEMPrivateKey), KEMError> { - crate::rsasve::keygen_from(keygen_from_rng(rng)) + crate::rsasve::keygen_from(keygen(rng)) } } diff --git a/crypto/rsa/src/rsassa_pkcs1_v1_5.rs b/crypto/rsa/src/rsassa_pkcs1_v1_5.rs index e6bc5697..41ec71d1 100644 --- a/crypto/rsa/src/rsassa_pkcs1_v1_5.rs +++ b/crypto/rsa/src/rsassa_pkcs1_v1_5.rs @@ -5,41 +5,33 @@ //! the hash function `H` (`H_LEN`/`T_LEN` sized to it) -- a concrete modulus size wires these to //! literals (e.g. RSA-2048/SHA-256 in [`crate::rsa_2048`]) rather than a caller choosing them. //! -//! [`RSASSA_PKCS1_v1_5`] implements `bouncycastle_core`'s [`Signer`]/[`SignatureVerifier`] traits -//! over those widths -- one-shot and streaming (`do_sign_init`/`do_sign_update`/`do_sign_final`), with a +//! [`RSASSA_PKCS1_v1_5`] is the algorithm marker the key role traits ([`DeterministicSigningKey`], +//! [`VerifyingKey`]) are implemented over at those widths -- one-shot and streaming, with a //! `&[u8]`-typed signature on the verify side -- on top of [`sign_from_hash`]/[`verify_from_hash`], //! which take the message hash rather than the message and are the pre-hash entry points for a //! caller that has already computed it. use crate::codec::{be_bytes_from_limbs, limbs_from_be_bytes}; use crate::emsa_pkcs1_v1_5::{emsa_pkcs1_v1_5_encode_from_hash, emsa_pkcs1_v1_5_verify_from_hash}; -use crate::keys::{RsaPrivateKey, RsaPublicKey}; +use crate::keys::{RsaPrivateKey, RsaPublicKey, modulus_strength}; use crate::rsa_core::{rsasp1, rsavp1}; use bouncycastle_core::errors::SignatureError; +use bouncycastle_core::security_strength::SecurityStrength; +use bouncycastle_core::signature_key::{DeterministicSigningKey, SignatureAlgorithm, VerifyingKey}; use bouncycastle_core::traits::{ - AlgorithmOID, Hash, HashAlgParams, SignaturePrivateKey, SignaturePublicKey, SignatureVerifier, - Signer, + Algorithm, AlgorithmInfo, AlgorithmOID, HashAlgParams, HashOneShot, SignaturePrivateKey, + SignaturePublicKey, SignatureSigner, SignatureVerifier, }; +use core::marker::PhantomData; -/// Streaming state for RSASSA-PKCS1-v1_5's [`Signer`] and [`SignatureVerifier`] impls, at the -/// widths the const parameters fix (the list [`sign_from_hash`] takes, plus the key encoding lengths -/// `SK_LEN`/`PK_LEN` the key traits are indexed by). One type serves both roles, mirroring -/// `bouncycastle_ecdsa::ecdsa_p256::ECDSAP256`: exactly one of `sk`/`pk` is `Some`, chosen by -/// which trait's `_init` constructed this value, and calling the other trait's `_final` on it is -/// reported as [`SignatureError::GenericError`] rather than silently doing the wrong operation. -/// -/// Concrete (hash, modulus size) pairings are type aliases in the per-size modules -- -/// `crate::rsa_2048::RSASSA_PKCS1_v1_5_SHA256` and siblings -- so a caller never spells out the -/// width list. The spec's own spelling `RSASSA-PKCS1-v1_5` is kept (hyphens as underscores), per -/// this repo's naming convention for identifiers a specification names. -/// -/// `ctx` is accepted but ignored by every method: RSASSA-PKCS1-v1_5 (RFC 8017 §8.2) has no -/// context-string input, the same position `bouncycastle_ecdsa` takes for ECDSA. -/// -/// The key is cloned into this state by `do_sign_init`/`do_verify_init` (the traits leave no room for a -/// borrow), so a signing state for the largest modulus size holds a copy of its -/// `RsaPrivateKey`'s `Secret` fields for as long as the state lives -- see the crate docs' -/// `# Memory Usage`. +/// RSASSA-PKCS1-v1_5 (RFC 8017 §8.2) over `H`, at a modulus of `L` limbs: the algorithm marker the key role +/// traits are implemented over, with every width fixed by the aliases in the size modules +/// (`rsa_2048::RSASSA_PKCS1_v1_5_SHA256` and siblings). +/// `RsaPrivateKey` signs through [`DeterministicSigningKey`]: PKCS#1 v1.5 draws nothing, so the +/// same key and message always give the same signature. +/// `RsaPublicKey` verifies through [`VerifyingKey`]. One key type serves every scheme and hash, so +/// a call names the marker: `DeterministicSigningKey::::...(&sk, ..)`. `ctx` is +/// accepted and ignored, since RSA has no context string. #[allow(non_camel_case_types)] pub struct RSASSA_PKCS1_v1_5< H, @@ -55,13 +47,32 @@ pub struct RSASSA_PKCS1_v1_5< const SK_LEN: usize, const PK_LEN: usize, > { - hash: H, - sk: Option>, - pk: Option>, + _hash: PhantomData, +} + +impl< + H, + const H_LEN: usize, + const T_LEN: usize, + const L: usize, + const L2: usize, + const L21: usize, + const HALF: usize, + const HALF2: usize, + const HALF21: usize, + const K_LEN: usize, + const SK_LEN: usize, + const PK_LEN: usize, +> Algorithm + for RSASSA_PKCS1_v1_5 +{ + const ALG_NAME: &'static str = "RSASSA-PKCS1-v1_5"; + /// From the modulus width, by SP 800-57 Part 1 Rev. 5 Table 2; see [`modulus_strength`]. + const MAX_SECURITY_STRENGTH: SecurityStrength = modulus_strength(L); } impl< - H: Hash + HashAlgParams + AlgorithmOID + Default, + H, const H_LEN: usize, const T_LEN: usize, const L: usize, @@ -73,67 +84,241 @@ impl< const K_LEN: usize, const SK_LEN: usize, const PK_LEN: usize, -> Signer, SK_LEN, K_LEN> +> SignatureAlgorithm for RSASSA_PKCS1_v1_5 +{ +} + +/// The signer the key hands out; it hashes the message and finishes with [`RSASSA_PKCS1_v1_5`]'s encoding and +/// RSASP1. +pub struct RsaPkcs1v15Signer< + 'k, + H, + const H_LEN: usize, + const T_LEN: usize, + const L: usize, + const L2: usize, + const L21: usize, + const HALF: usize, + const HALF2: usize, + const HALF21: usize, + const K_LEN: usize, + const SK_LEN: usize, + const PK_LEN: usize, +> { + sk: &'k RsaPrivateKey, + hash: H, +} + +/// The verifier the key hands out: hashes the message and finishes with RSAVP1 and the +/// encoding's verification. +pub struct RsaPkcs1v15Verifier< + 'k, + H, + const H_LEN: usize, + const T_LEN: usize, + const L: usize, + const L2: usize, + const L21: usize, + const HALF: usize, + const HALF2: usize, + const HALF21: usize, + const K_LEN: usize, + const SK_LEN: usize, + const PK_LEN: usize, +> { + pk: &'k RsaPublicKey, + hash: H, +} + +impl< + H: HashOneShot + HashAlgParams + AlgorithmOID, + const H_LEN: usize, + const T_LEN: usize, + const L: usize, + const L2: usize, + const L21: usize, + const HALF: usize, + const HALF2: usize, + const HALF21: usize, + const K_LEN: usize, + const SK_LEN: usize, + const PK_LEN: usize, +> + DeterministicSigningKey< + RSASSA_PKCS1_v1_5, + K_LEN, + > for RsaPrivateKey where // Only a private key type this crate has declared signable (a `SignaturePrivateKey` impl in - // its size module) gets a `Signer`: the verify-only sizes, RSA-1024/1536, have none, so this - // impl does not exist for them and there is nothing to call -- compile-time enforcement of the - // crate's `# Scope`, not a runtime check. + // its size module) signs: the verify-only sizes, RSA-1024/1536, have none, so this impl does + // not exist for them -- compile-time enforcement of the crate's `# Scope`. RsaPrivateKey: SignaturePrivateKey, { - fn sign( - sk: &RsaPrivateKey, - msg: &[u8], - ctx: Option<&[u8]>, - ) -> Result<[u8; K_LEN], SignatureError> { - let mut s = Self::do_sign_init(sk, ctx)?; - s.do_sign_update(msg); - s.do_sign_final() - } + type Signer<'k> + = RsaPkcs1v15Signer< + 'k, + H, + H_LEN, + T_LEN, + L, + L2, + L21, + HALF, + HALF2, + HALF21, + K_LEN, + SK_LEN, + PK_LEN, + > + where + Self: 'k; - fn sign_out( - sk: &RsaPrivateKey, - msg: &[u8], - ctx: Option<&[u8]>, - output: &mut [u8; K_LEN], - ) -> Result { - output.fill(0); - *output = Self::sign(sk, msg, ctx)?; - Ok(K_LEN) + fn create_signer_deterministic<'k>( + &'k self, + _ctx: Option<&[u8]>, + ) -> Result, SignatureError> { + Ok(RsaPkcs1v15Signer { sk: self, hash: H::default() }) } +} + +impl< + H: HashOneShot + HashAlgParams + AlgorithmOID, + const H_LEN: usize, + const T_LEN: usize, + const L: usize, + const L2: usize, + const L21: usize, + const HALF: usize, + const HALF2: usize, + const HALF21: usize, + const K_LEN: usize, + const SK_LEN: usize, + const PK_LEN: usize, +> + VerifyingKey< + RSASSA_PKCS1_v1_5, + K_LEN, + > for RsaPublicKey +where + RsaPublicKey: SignaturePublicKey, +{ + type Verifier<'k> + = RsaPkcs1v15Verifier< + 'k, + H, + H_LEN, + T_LEN, + L, + L2, + L21, + HALF, + HALF2, + HALF21, + K_LEN, + SK_LEN, + PK_LEN, + > + where + Self: 'k; - fn do_sign_init( - sk: &RsaPrivateKey, + fn create_verifier<'k>( + &'k self, _ctx: Option<&[u8]>, - ) -> Result { - // ctx ignored -- see the type's docs. - Ok(Self { hash: H::default(), sk: Some(sk.clone()), pk: None }) + ) -> Result, SignatureError> { + Ok(RsaPkcs1v15Verifier { pk: self, hash: H::default() }) + } +} + +impl< + H: HashOneShot + HashAlgParams + AlgorithmOID, + const H_LEN: usize, + const T_LEN: usize, + const L: usize, + const L2: usize, + const L21: usize, + const HALF: usize, + const HALF2: usize, + const HALF21: usize, + const K_LEN: usize, + const SK_LEN: usize, + const PK_LEN: usize, +> AlgorithmInfo + for RsaPkcs1v15Signer< + '_, + H, + H_LEN, + T_LEN, + L, + L2, + L21, + HALF, + HALF2, + HALF21, + K_LEN, + SK_LEN, + PK_LEN, + > +{ + fn alg_name(&self) -> &'static str { + as Algorithm>::ALG_NAME } - fn do_sign_update(&mut self, msg_chunk: &[u8]) { + fn max_security_strength(&self) -> SecurityStrength { + as Algorithm>::MAX_SECURITY_STRENGTH + } +} + +impl< + H: HashOneShot + HashAlgParams + AlgorithmOID, + const H_LEN: usize, + const T_LEN: usize, + const L: usize, + const L2: usize, + const L21: usize, + const HALF: usize, + const HALF2: usize, + const HALF21: usize, + const K_LEN: usize, + const SK_LEN: usize, + const PK_LEN: usize, +> SignatureSigner + for RsaPkcs1v15Signer< + '_, + H, + H_LEN, + T_LEN, + L, + L2, + L21, + HALF, + HALF2, + HALF21, + K_LEN, + SK_LEN, + PK_LEN, + > +{ + fn do_update(&mut self, msg_chunk: &[u8]) { self.hash.do_update(msg_chunk); } - fn do_sign_final(self) -> Result<[u8; K_LEN], SignatureError> { - let sk = self.sk.ok_or(SignatureError::GenericError( - "do_sign_final called on a verify-initialized RSASSA_PKCS1_v1_5; call do_verify_final instead", - ))?; - // EMSA-PKCS1-v1_5 step 1, `H = Hash(M)`, completed here over the streamed chunks. - let mut digest = [0u8; H_LEN]; - self.hash.do_final_out(&mut digest); - sign_from_hash::(&sk, &digest) + fn do_final(self) -> Result<[u8; K_LEN], SignatureError> { + // The encoding's first step, `Hash(M)`, completed here over the streamed chunks. + let mut m_hash = [0u8; H_LEN]; + self.hash.do_final_out(&mut m_hash); + sign_from_hash::(self.sk, &m_hash) } - fn do_sign_final_out(self, output: &mut [u8; K_LEN]) -> Result { + fn do_final_out(self, output: &mut [u8; K_LEN]) -> Result { output.fill(0); - *output = self.do_sign_final()?; + *output = self.do_final()?; Ok(K_LEN) } } impl< - H: Hash + HashAlgParams + AlgorithmOID + Default, + H: HashOneShot + HashAlgParams + AlgorithmOID, const H_LEN: usize, const T_LEN: usize, const L: usize, @@ -145,47 +330,78 @@ impl< const K_LEN: usize, const SK_LEN: usize, const PK_LEN: usize, -> SignatureVerifier, PK_LEN, K_LEN> - for RSASSA_PKCS1_v1_5 -where - RsaPublicKey: SignaturePublicKey, +> AlgorithmInfo + for RsaPkcs1v15Verifier< + '_, + H, + H_LEN, + T_LEN, + L, + L2, + L21, + HALF, + HALF2, + HALF21, + K_LEN, + SK_LEN, + PK_LEN, + > { - fn verify( - pk: &RsaPublicKey, - msg: &[u8], - ctx: Option<&[u8]>, - sig: &[u8], - ) -> Result<(), SignatureError> { - let mut v = Self::do_verify_init(pk, ctx)?; - v.do_verify_update(msg); - v.do_verify_final(sig) + fn alg_name(&self) -> &'static str { + as Algorithm>::ALG_NAME } - fn do_verify_init(pk: &RsaPublicKey, _ctx: Option<&[u8]>) -> Result { - Ok(Self { hash: H::default(), sk: None, pk: Some(pk.clone()) }) + fn max_security_strength(&self) -> SecurityStrength { + as Algorithm>::MAX_SECURITY_STRENGTH } +} - fn do_verify_update(&mut self, msg_chunk: &[u8]) { +impl< + H: HashOneShot + HashAlgParams + AlgorithmOID, + const H_LEN: usize, + const T_LEN: usize, + const L: usize, + const L2: usize, + const L21: usize, + const HALF: usize, + const HALF2: usize, + const HALF21: usize, + const K_LEN: usize, + const SK_LEN: usize, + const PK_LEN: usize, +> SignatureVerifier + for RsaPkcs1v15Verifier< + '_, + H, + H_LEN, + T_LEN, + L, + L2, + L21, + HALF, + HALF2, + HALF21, + K_LEN, + SK_LEN, + PK_LEN, + > +{ + fn do_update(&mut self, msg_chunk: &[u8]) { self.hash.do_update(msg_chunk); } fn do_verify_final(self, sig: &[u8]) -> Result<(), SignatureError> { - let pk = self.pk.ok_or(SignatureError::GenericError( - "do_verify_final called on a sign-initialized RSASSA_PKCS1_v1_5; call do_sign_final instead", - ))?; - // RFC 8017 §8.2.2 step 1: "Length checking: If the length of the signature S is not k - // octets, output "invalid signature" and stop." -- the one place in this crate that step - // is a runtime check, since the trait hands over a `&[u8]` rather than the `[u8; K_LEN]` - // [`verify_from_hash`] takes. - let sig: &[u8; K_LEN] = - sig.try_into().map_err(|_| SignatureError::SignatureVerificationFailed)?; - let mut digest = [0u8; H_LEN]; - self.hash.do_final_out(&mut digest); - // Step 2.b: "If RSAVP1 outputs "signature representative out of range", output "invalid - // signature" and stop." [`verify_from_hash`] deliberately lets RSAVP1's own error through - // instead (see its docs); the trait's contract is the RFC's -- one "invalid signature" - // answer for every way a signature can fail -- so it is folded in here. - verify_from_hash::(&pk, &digest, sig) + // RFC 8017 §8.1.2 / §8.2.2 step 1, "Length checking: If the length of the signature S is + // not k octets, output "invalid signature" and stop", reported as the length error the + // shared suite expects for a signature of the wrong size. + let sig: &[u8; K_LEN] = sig.try_into().map_err(|_| { + SignatureError::LengthError("RSA signature must be exactly the modulus length") + })?; + let mut m_hash = [0u8; H_LEN]; + self.hash.do_final_out(&mut m_hash); + // 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, sig) .map_err(|_| SignatureError::SignatureVerificationFailed) } } @@ -193,7 +409,7 @@ where /// RSASSA-PKCS1-V1_5-SIGN (RFC 8017 §8.2.1), `S = I2OSP(RSASP1(K, OS2IP(EM)), k)` with /// `EM = EMSA-PKCS1-V1_5-ENCODE(M, k)`, given the message's hash `digest` (`H`'s output over `M`) /// rather than `M` itself: the entry point for a caller that hashed the message incrementally -/// (the [`Signer`] impl) or already holds the digest. Step 1's two errors ("message too long" -- +/// (the [`DeterministicSigningKey`] impl) or already holds the digest. Step 1's two errors ("message too long" -- /// unreachable, since the encoding's length is fixed at compile time by `K_LEN` -- and "RSA /// modulus too short") are folded into [`emsa_pkcs1_v1_5_encode_from_hash`]'s `debug_assert`, not /// raised here as a runtime error, for the reason given there. The `H` bound is only what [`emsa_pkcs1_v1_5_encode_from_hash`] needs to build the @@ -227,7 +443,7 @@ pub fn sign_from_hash< /// otherwise-valid signature whose `DigestInfo` omits the `AlgorithmIdentifier`'s `NULL` /// parameters -- a real-world leniency that function's docs explain. Step 1's length check (`S` /// must be exactly `k` octets) doesn't apply here: `signature` is a fixed `K_LEN`-byte array, so a -/// wrong length is a type error at the call site; the [`SignatureVerifier`] impl, which takes a +/// wrong length is a type error at the call site; the [`VerifyingKey`] impl, which takes a /// `&[u8]`, performs it. Step 2's "signature representative out of range" surfaces as /// [`rsavp1`]'s own `Err`, propagated directly rather than folded into "invalid signature": a /// caller working through CAVP/wycheproof-style vectors needs to tell "malformed input" apart from diff --git a/crypto/rsa/src/rsassa_pss.rs b/crypto/rsa/src/rsassa_pss.rs index 7cafe702..0e4b2185 100644 --- a/crypto/rsa/src/rsassa_pss.rs +++ b/crypto/rsa/src/rsassa_pss.rs @@ -4,38 +4,32 @@ //! (`8 + H_LEN + S_LEN`); a concrete modulus size wires these to literals (RSA-2048/SHA-256 in //! [`crate::rsa_2048`]). //! -//! As in [`crate::rsassa_pkcs1_v1_5`], [`RSASSA_PSS`] implements `bouncycastle_core`'s -//! [`Signer`]/[`SignatureVerifier`] traits over those widths on top of the `*_from_hash` -//! functions, which take the message hash rather than the message; the salt comes from the -//! library's default RNG unless the caller supplies one ([`RSASSA_PSS::sign_randomized`], -//! [`RSASSA_PSS::set_signer_salt`]). +//! As in [`crate::rsassa_pkcs1_v1_5`], [`RSASSA_PSS`] is the algorithm marker the key role +//! traits are implemented over, on top of the `*_from_hash` functions, which take the message +//! hash rather than the message; the salt comes from the RNG handed to +//! [`SigningKey::create_signer`], and [`RsaPssSigner::set_salt`] replaces it for a known answer. use crate::codec::{be_bytes_from_limbs, limbs_from_be_bytes}; use crate::emsa_pss::{emsa_pss_encode_from_hash, emsa_pss_verify_from_hash}; -use crate::keys::{RsaPrivateKey, RsaPublicKey}; +use crate::keys::{RsaPrivateKey, RsaPublicKey, modulus_strength}; use crate::rsa_core::{rsasp1, rsavp1}; use bouncycastle_core::errors::SignatureError; +use bouncycastle_core::security_strength::SecurityStrength; +use bouncycastle_core::signature_key::{SignatureAlgorithm, SigningKey, VerifyingKey}; use bouncycastle_core::traits::{ - Hash, RNG, SignaturePrivateKey, SignaturePublicKey, SignatureVerifier, Signer, + Algorithm, AlgorithmInfo, HashOneShot, RNG, SignaturePrivateKey, SignaturePublicKey, + SignatureSigner, SignatureVerifier, }; -use bouncycastle_rng::DefaultRNG; +use core::marker::PhantomData; -/// Streaming state for RSASSA-PSS's [`Signer`] and [`SignatureVerifier`] impls, at the widths the -/// const parameters fix (the list [`sign_from_hash`] takes, plus the key encoding lengths `SK_LEN`/`PK_LEN` -/// the key traits are indexed by). The same one-type-both-roles shape as -/// [`crate::rsassa_pkcs1_v1_5::RSASSA_PKCS1_v1_5`], whose docs cover the `sk`/`pk` arrangement, -/// the ignored `ctx`, the naming, and the cloned key; concrete pairings are aliases such as -/// `crate::rsa_2048::RSASSA_PSS_SHA256`. -/// -/// [`Signer::sign`] has no RNG parameter, and that trait's docs define it as sourcing any -/// randomness it needs from the library's default OS-backed RNG, so `do_sign_final` draws the salt -/// (EMSA-PSS-ENCODE step 4) from a fresh [`DefaultRNG`] unless the caller fixed one. Two -/// `Signer::sign` calls over the same key and message therefore produce different, both valid, -/// signatures. Control over that randomness follows the workspace's other signature crates: -/// [`Self::sign_randomized`] takes a caller-supplied RNG (as `bouncycastle_ecdsa`'s and -/// `bouncycastle_sm2`'s `sign_randomized` do), and [`Self::set_signer_salt`] fixes the salt on a -/// streaming state (as `bouncycastle_mldsa`'s `set_signer_rnd` fixes its nonce), which makes the -/// signature deterministic. +/// RSASSA-PSS (RFC 8017 §8.1) over `H`, with MGF1 over `H`, at a modulus of `L` limbs: the algorithm marker the key role +/// traits are implemented over, with every width fixed by the aliases in the size modules +/// (`rsa_2048::RSASSA_PSS_SHA256` and siblings). +/// `RsaPrivateKey` signs through [`SigningKey`]: a fresh `S_LEN`-byte salt from the caller's RNG +/// per signer (EMSA-PSS-ENCODE step 4), so two signatures of one message differ. +/// `RsaPublicKey` verifies through [`VerifyingKey`]. One key type serves every scheme and hash, so +/// a call names the marker: `SigningKey::::...(&sk, ..)`. `ctx` is +/// accepted and ignored, since RSA has no context string. #[allow(non_camel_case_types)] pub struct RSASSA_PSS< H, @@ -54,16 +48,114 @@ pub struct RSASSA_PSS< const SK_LEN: usize, const PK_LEN: usize, > { + _hash: PhantomData, +} + +impl< + H, + const H_LEN: usize, + const SEED_LEN: usize, + const S_LEN: usize, + const M_PRIME_LEN: usize, + const DB_LEN: usize, + const L: usize, + const L2: usize, + const L21: usize, + const HALF: usize, + const HALF2: usize, + const HALF21: usize, + const K_LEN: usize, + const SK_LEN: usize, + const PK_LEN: usize, +> Algorithm + for RSASSA_PSS< + H, + H_LEN, + SEED_LEN, + S_LEN, + M_PRIME_LEN, + DB_LEN, + L, + L2, + L21, + HALF, + HALF2, + HALF21, + K_LEN, + SK_LEN, + PK_LEN, + > +{ + const ALG_NAME: &'static str = "RSASSA-PSS"; + /// From the modulus width, by SP 800-57 Part 1 Rev. 5 Table 2; see [`modulus_strength`]. + const MAX_SECURITY_STRENGTH: SecurityStrength = modulus_strength(L); +} + +impl< + H, + const H_LEN: usize, + const SEED_LEN: usize, + const S_LEN: usize, + const M_PRIME_LEN: usize, + const DB_LEN: usize, + const L: usize, + const L2: usize, + const L21: usize, + const HALF: usize, + const HALF2: usize, + const HALF21: usize, + const K_LEN: usize, + const SK_LEN: usize, + const PK_LEN: usize, +> SignatureAlgorithm + for RSASSA_PSS< + H, + H_LEN, + SEED_LEN, + S_LEN, + M_PRIME_LEN, + DB_LEN, + L, + L2, + L21, + HALF, + HALF2, + HALF21, + K_LEN, + SK_LEN, + PK_LEN, + > +{ +} + +/// The signer the key hands out; it hashes the message and finishes with [`RSASSA_PSS`]'s encoding and +/// RSASP1. `set_salt` replaces the drawn salt, for a known-answer test; the signature then depends on the key and message alone. +pub struct RsaPssSigner< + 'k, + H, + const H_LEN: usize, + const SEED_LEN: usize, + const S_LEN: usize, + const M_PRIME_LEN: usize, + const DB_LEN: usize, + const L: usize, + const L2: usize, + const L21: usize, + const HALF: usize, + const HALF2: usize, + const HALF21: usize, + const K_LEN: usize, + const SK_LEN: usize, + const PK_LEN: usize, +> { + sk: &'k RsaPrivateKey, hash: H, - sk: Option>, - pk: Option>, - /// The salt `do_sign_final` will use, if [`Self::set_signer_salt`] fixed one; `None` means a - /// fresh one from [`DefaultRNG`]. - salt: Option<[u8; S_LEN]>, + salt: [u8; S_LEN], } impl< - H: Hash + Default, + 'k, + H: HashOneShot, const H_LEN: usize, const SEED_LEN: usize, const S_LEN: usize, @@ -79,7 +171,8 @@ impl< const SK_LEN: usize, const PK_LEN: usize, > - RSASSA_PSS< + RsaPssSigner< + 'k, H, H_LEN, SEED_LEN, @@ -96,40 +189,187 @@ impl< SK_LEN, PK_LEN, > +{ + /// Replaces the salt drawn at creation with `salt`, for a known-answer test against a + /// published salt; the signature then depends on the key and message alone. + pub fn set_salt(&mut self, salt: [u8; S_LEN]) { + self.salt = salt; + } +} + +/// The verifier the key hands out: hashes the message and finishes with RSAVP1 and the +/// encoding's verification. +pub struct RsaPssVerifier< + 'k, + H, + const H_LEN: usize, + const SEED_LEN: usize, + const S_LEN: usize, + const M_PRIME_LEN: usize, + const DB_LEN: usize, + const L: usize, + const L2: usize, + const L21: usize, + const HALF: usize, + const HALF2: usize, + const HALF21: usize, + const K_LEN: usize, + const SK_LEN: usize, + const PK_LEN: usize, +> { + pk: &'k RsaPublicKey, + hash: H, +} + +impl< + H: HashOneShot, + const H_LEN: usize, + const SEED_LEN: usize, + const S_LEN: usize, + const M_PRIME_LEN: usize, + const DB_LEN: usize, + const L: usize, + const L2: usize, + const L21: usize, + const HALF: usize, + const HALF2: usize, + const HALF21: usize, + const K_LEN: usize, + const SK_LEN: usize, + const PK_LEN: usize, +> + SigningKey< + RSASSA_PSS< + H, + H_LEN, + SEED_LEN, + S_LEN, + M_PRIME_LEN, + DB_LEN, + L, + L2, + L21, + HALF, + HALF2, + HALF21, + K_LEN, + SK_LEN, + PK_LEN, + >, + K_LEN, + > for RsaPrivateKey where + // Only a private key type this crate has declared signable (a `SignaturePrivateKey` impl in + // its size module) signs: the verify-only sizes, RSA-1024/1536, have none, so this impl does + // not exist for them -- compile-time enforcement of the crate's `# Scope`. RsaPrivateKey: SignaturePrivateKey, { - /// RSASSA-PSS-SIGN (RFC 8017 §8.1.1) with the salt drawn from the caller's `rng` rather than - /// the library's default -- an additional capability alongside [`Signer::sign`], the same - /// shape as `bouncycastle_ecdsa`'s `ECDSAP256::sign_randomized` and `bouncycastle_sm2`'s - /// `SM2::sign_randomized`. `ctx` is not taken: it is ignored throughout this type. - pub fn sign_randomized( - sk: &RsaPrivateKey, - msg: &[u8], + type Signer<'k> + = RsaPssSigner< + 'k, + H, + H_LEN, + SEED_LEN, + S_LEN, + M_PRIME_LEN, + DB_LEN, + L, + L2, + L21, + HALF, + HALF2, + HALF21, + K_LEN, + SK_LEN, + PK_LEN, + > + where + Self: 'k; + + fn create_signer<'k>( + &'k self, rng: &mut dyn RNG, - ) -> Result<[u8; K_LEN], SignatureError> { + _ctx: Option<&[u8]>, + ) -> Result, SignatureError> { + // EMSA-PSS-ENCODE step 4's salt, drawn when the signer is created, as ECDSA draws `k`. let mut salt = [0u8; S_LEN]; rng.next_bytes_out(&mut salt).map_err(SignatureError::RNGError)?; - let mut signer = Self::do_sign_init(sk, None)?; - signer.set_signer_salt(salt); - signer.do_sign_update(msg); - signer.do_sign_final() + Ok(RsaPssSigner { sk: self, hash: H::default(), salt }) } +} + +impl< + H: HashOneShot, + const H_LEN: usize, + const SEED_LEN: usize, + const S_LEN: usize, + const M_PRIME_LEN: usize, + const DB_LEN: usize, + const L: usize, + const L2: usize, + const L21: usize, + const HALF: usize, + const HALF2: usize, + const HALF21: usize, + const K_LEN: usize, + const SK_LEN: usize, + const PK_LEN: usize, +> + VerifyingKey< + RSASSA_PSS< + H, + H_LEN, + SEED_LEN, + S_LEN, + M_PRIME_LEN, + DB_LEN, + L, + L2, + L21, + HALF, + HALF2, + HALF21, + K_LEN, + SK_LEN, + PK_LEN, + >, + K_LEN, + > for RsaPublicKey +where + RsaPublicKey: SignaturePublicKey, +{ + type Verifier<'k> + = RsaPssVerifier< + 'k, + H, + H_LEN, + SEED_LEN, + S_LEN, + M_PRIME_LEN, + DB_LEN, + L, + L2, + L21, + HALF, + HALF2, + HALF21, + K_LEN, + SK_LEN, + PK_LEN, + > + where + Self: 'k; - /// Fixes the salt [`Signer::do_sign_final`] will use (EMSA-PSS-ENCODE step 4) instead of drawing - /// one from the default RNG -- the counterpart of `bouncycastle_mldsa`'s `set_signer_rnd`, for - /// a caller with its own randomness source, a device without an RNG, or a test against a known - /// salt. With the salt fixed, signing is deterministic; PSS's security argument assumes a - /// fresh, unpredictable salt per signature (see the crate docs' `# Security Considerations`), - /// so a fixed salt should itself be fresh randomness the caller obtained elsewhere. Has no - /// effect on a verify-initialised state. - pub fn set_signer_salt(&mut self, salt: [u8; S_LEN]) { - self.salt = Some(salt); + fn create_verifier<'k>( + &'k self, + _ctx: Option<&[u8]>, + ) -> Result, SignatureError> { + Ok(RsaPssVerifier { pk: self, hash: H::default() }) } } impl< - H: Hash + Default, + H: HashOneShot, const H_LEN: usize, const SEED_LEN: usize, const S_LEN: usize, @@ -144,8 +384,9 @@ impl< const K_LEN: usize, const SK_LEN: usize, const PK_LEN: usize, -> Signer, SK_LEN, K_LEN> - for RSASSA_PSS< +> AlgorithmInfo + for RsaPssSigner< + '_, H, H_LEN, SEED_LEN, @@ -162,62 +403,92 @@ impl< SK_LEN, PK_LEN, > -where - // See `RSASSA_PKCS1_v1_5`'s `Signer` impl: no `SignaturePrivateKey`, no `Signer`. - RsaPrivateKey: SignaturePrivateKey, { - fn sign( - sk: &RsaPrivateKey, - msg: &[u8], - ctx: Option<&[u8]>, - ) -> Result<[u8; K_LEN], SignatureError> { - let mut s = Self::do_sign_init(sk, ctx)?; - s.do_sign_update(msg); - s.do_sign_final() - } - - fn sign_out( - sk: &RsaPrivateKey, - msg: &[u8], - ctx: Option<&[u8]>, - output: &mut [u8; K_LEN], - ) -> Result { - output.fill(0); - *output = Self::sign(sk, msg, ctx)?; - Ok(K_LEN) + fn alg_name(&self) -> &'static str { + as Algorithm>::ALG_NAME } - fn do_sign_init( - sk: &RsaPrivateKey, - _ctx: Option<&[u8]>, - ) -> Result { - // ctx ignored -- see the type's docs. - Ok(Self { hash: H::default(), sk: Some(sk.clone()), pk: None, salt: None }) + fn max_security_strength(&self) -> SecurityStrength { + as Algorithm>::MAX_SECURITY_STRENGTH } +} - fn do_sign_update(&mut self, msg_chunk: &[u8]) { +impl< + H: HashOneShot, + const H_LEN: usize, + const SEED_LEN: usize, + const S_LEN: usize, + const M_PRIME_LEN: usize, + const DB_LEN: usize, + const L: usize, + const L2: usize, + const L21: usize, + const HALF: usize, + const HALF2: usize, + const HALF21: usize, + const K_LEN: usize, + const SK_LEN: usize, + const PK_LEN: usize, +> SignatureSigner + for RsaPssSigner< + '_, + H, + H_LEN, + SEED_LEN, + S_LEN, + M_PRIME_LEN, + DB_LEN, + L, + L2, + L21, + HALF, + HALF2, + HALF21, + K_LEN, + SK_LEN, + PK_LEN, + > +{ + fn do_update(&mut self, msg_chunk: &[u8]) { self.hash.do_update(msg_chunk); } - fn do_sign_final(self) -> Result<[u8; K_LEN], SignatureError> { - let sk = self.sk.ok_or(SignatureError::GenericError( - "do_sign_final called on a verify-initialized RSASSA_PSS; call do_verify_final instead", - ))?; - // EMSA-PSS step 2, `mHash = Hash(M)`, completed here over the streamed chunks. + fn do_final(self) -> Result<[u8; K_LEN], SignatureError> { + // The encoding's first step, `Hash(M)`, completed here over the streamed chunks. let mut m_hash = [0u8; H_LEN]; self.hash.do_final_out(&mut m_hash); - // EMSA-PSS-ENCODE step 4's salt: the one `set_signer_salt` fixed, else fresh from the - // library's default RNG (see the type's docs). - let salt = match self.salt { - Some(salt) => salt, - None => { - let mut salt = [0u8; S_LEN]; - DefaultRNG::default() - .next_bytes_out(&mut salt) - .map_err(SignatureError::RNGError)?; - salt - } - }; sign_from_hash_with_salt::< H, H_LEN, @@ -232,18 +503,18 @@ where HALF2, HALF21, K_LEN, - >(&sk, &m_hash, &salt) + >(self.sk, &m_hash, &self.salt) } - fn do_sign_final_out(self, output: &mut [u8; K_LEN]) -> Result { + fn do_final_out(self, output: &mut [u8; K_LEN]) -> Result { output.fill(0); - *output = self.do_sign_final()?; + *output = self.do_final()?; Ok(K_LEN) } } impl< - H: Hash + Default, + H: HashOneShot, const H_LEN: usize, const SEED_LEN: usize, const S_LEN: usize, @@ -258,8 +529,9 @@ impl< const K_LEN: usize, const SK_LEN: usize, const PK_LEN: usize, -> SignatureVerifier, PK_LEN, K_LEN> - for RSASSA_PSS< +> AlgorithmInfo + for RsaPssVerifier< + '_, H, H_LEN, SEED_LEN, @@ -276,42 +548,101 @@ impl< SK_LEN, PK_LEN, > -where - RsaPublicKey: SignaturePublicKey, { - fn verify( - pk: &RsaPublicKey, - msg: &[u8], - ctx: Option<&[u8]>, - sig: &[u8], - ) -> Result<(), SignatureError> { - let mut v = Self::do_verify_init(pk, ctx)?; - v.do_verify_update(msg); - v.do_verify_final(sig) + fn alg_name(&self) -> &'static str { + as Algorithm>::ALG_NAME } - fn do_verify_init(pk: &RsaPublicKey, _ctx: Option<&[u8]>) -> Result { - Ok(Self { hash: H::default(), sk: None, pk: Some(pk.clone()), salt: None }) + fn max_security_strength(&self) -> SecurityStrength { + as Algorithm>::MAX_SECURITY_STRENGTH } +} - fn do_verify_update(&mut self, msg_chunk: &[u8]) { +impl< + H: HashOneShot, + const H_LEN: usize, + const SEED_LEN: usize, + const S_LEN: usize, + const M_PRIME_LEN: usize, + const DB_LEN: usize, + const L: usize, + const L2: usize, + const L21: usize, + const HALF: usize, + const HALF2: usize, + const HALF21: usize, + const K_LEN: usize, + const SK_LEN: usize, + const PK_LEN: usize, +> SignatureVerifier + for RsaPssVerifier< + '_, + H, + H_LEN, + SEED_LEN, + S_LEN, + M_PRIME_LEN, + DB_LEN, + L, + L2, + L21, + HALF, + HALF2, + HALF21, + K_LEN, + SK_LEN, + PK_LEN, + > +{ + fn do_update(&mut self, msg_chunk: &[u8]) { self.hash.do_update(msg_chunk); } fn do_verify_final(self, sig: &[u8]) -> Result<(), SignatureError> { - let pk = self.pk.ok_or(SignatureError::GenericError( - "do_verify_final called on a sign-initialized RSASSA_PSS; call do_sign_final instead", - ))?; - // RFC 8017 §8.1.2 step 1: "Length checking: If the length of the signature S is not k - // octets, output "invalid signature" and stop." (See `RSASSA_PKCS1_v1_5::do_verify_final`.) - let sig: &[u8; K_LEN] = - sig.try_into().map_err(|_| SignatureError::SignatureVerificationFailed)?; + // RFC 8017 §8.1.2 / §8.2.2 step 1, "Length checking: If the length of the signature S is + // not k octets, output "invalid signature" and stop", reported as the length error the + // shared suite expects for a signature of the wrong size. + let sig: &[u8; K_LEN] = sig.try_into().map_err(|_| { + SignatureError::LengthError("RSA signature must be exactly the modulus length") + })?; let mut m_hash = [0u8; H_LEN]; self.hash.do_final_out(&mut m_hash); - // Step 2.b: RSAVP1's "signature representative out of range" is "invalid signature" here - // (see `RSASSA_PKCS1_v1_5::do_verify_final`). + // 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::( - &pk, &m_hash, sig, + self.pk, &m_hash, sig, ) .map_err(|_| SignatureError::SignatureVerificationFailed) } @@ -319,11 +650,11 @@ where /// RSASSA-PSS-SIGN (RFC 8017 §8.1.1) with the salt supplied directly rather than drawn from an /// RNG, given the message's hash `m_hash` (`H`'s output over the message) rather than the message -/// itself -- what the [`Signer`] impl's `do_sign_final` calls once it has hashed the streamed +/// itself -- what [`RsaPssSigner`]'s `do_final` calls once it has hashed the streamed /// message and settled the salt. EMSA-PSS is randomized only in its choice of salt (§9.1's own /// note 5), so a fixed salt makes this deterministic and directly testable against a known salt. pub fn sign_from_hash_with_salt< - H: Hash + Default, + H: HashOneShot, const H_LEN: usize, const SEED_LEN: usize, const S_LEN: usize, @@ -353,7 +684,7 @@ pub fn sign_from_hash_with_salt< /// draws a fresh `S_LEN`-byte salt from `rng` (EMSA-PSS-ENCODE step 4) and hands both to /// [`sign_from_hash_with_salt`]. pub fn sign_from_hash< - H: Hash + Default, + H: HashOneShot, const H_LEN: usize, const SEED_LEN: usize, const S_LEN: usize, @@ -396,7 +727,7 @@ pub fn sign_from_hash< /// itself (§9.1.2) rather than needing it supplied. RSAVP1's range error propagates as its own /// `Err`, as in [`crate::rsassa_pkcs1_v1_5::verify_from_hash`]. pub fn verify_from_hash< - H: Hash + Default, + H: HashOneShot, const H_LEN: usize, const SEED_LEN: usize, const S_LEN: usize, diff --git a/crypto/rsa/src/rsassa_pss_shake.rs b/crypto/rsa/src/rsassa_pss_shake.rs index 3d9441d1..f8f4da7f 100644 --- a/crypto/rsa/src/rsassa_pss_shake.rs +++ b/crypto/rsa/src/rsassa_pss_shake.rs @@ -2,26 +2,30 @@ //! generation function -- `id-RSASSA-PSS-SHAKE128`/`id-RSASSA-PSS-SHAKE256` (RFC 8702 §3.2.1). //! Otherwise identical to [`crate::rsassa_pss`] (RFC 8017 §8.1): same RSASP1/RSAVP1 orchestration, //! same fresh-salt-per-signature approach, just built on [`crate::emsa_pss_shake`] in place of -//! [`crate::emsa_pss`] -- and the same [`RSASSA_PSS_SHAKE`] trait type over `*_from_hash` -//! functions, with `X: XOF` in place of `H: Hash` and no `SEED_LEN` (there is no MGF1 counter to -//! size). +//! [`crate::emsa_pss`] -- and the same [`RSASSA_PSS_SHAKE`] marker over `*_from_hash` functions, +//! with `X: XOF` in place of `H: Hash` and no `SEED_LEN` (there is no MGF1 counter to size). use crate::codec::{be_bytes_from_limbs, limbs_from_be_bytes}; use crate::emsa_pss_shake::{emsa_pss_encode_shake_from_hash, emsa_pss_verify_shake_from_hash}; -use crate::keys::{RsaPrivateKey, RsaPublicKey}; +use crate::keys::{RsaPrivateKey, RsaPublicKey, modulus_strength}; use crate::rsa_core::{rsasp1, rsavp1}; use bouncycastle_core::errors::SignatureError; +use bouncycastle_core::security_strength::SecurityStrength; +use bouncycastle_core::signature_key::{SignatureAlgorithm, SigningKey, VerifyingKey}; use bouncycastle_core::traits::{ - RNG, SignaturePrivateKey, SignaturePublicKey, SignatureVerifier, Signer, XOF, + Algorithm, AlgorithmInfo, HashOneShot, RNG, SignaturePrivateKey, SignaturePublicKey, + SignatureSigner, SignatureVerifier, XOF, }; -use bouncycastle_rng::DefaultRNG; +use core::marker::PhantomData; -/// Streaming state for RSASSA-PSS-SHAKE's [`Signer`] and [`SignatureVerifier`] impls: exactly -/// [`crate::rsassa_pss::RSASSA_PSS`] (whose docs cover the shared behaviour, including where the -/// salt comes from and the [`Self::sign_randomized`]/[`Self::set_signer_salt`] ways to control -/// it) built on the SHAKE-native encoding instead. `X`'s `Hash` methods (a `XOF` is a `Hash`) -/// absorb the streamed message; its `H_LEN`-byte output is `mHash`. -/// Concrete pairings are aliases such as `crate::rsa_2048::RSASSA_PSS_SHAKE128`. +/// RSASSA-PSS with a SHAKE XOF `X` as both hash and mask (RFC 8702 §3.2.1), at a modulus of `L` limbs: the algorithm marker the key role +/// traits are implemented over, with every width fixed by the aliases in the size modules +/// (`rsa_2048::RSASSA_PSS_SHAKE_SHA256` and siblings). +/// `RsaPrivateKey` signs through [`SigningKey`]: a fresh `S_LEN`-byte salt from the caller's RNG +/// per signer (EMSA-PSS-ENCODE step 4), so two signatures of one message differ. +/// `RsaPublicKey` verifies through [`VerifyingKey`]. One key type serves every scheme and hash, so +/// a call names the marker: `SigningKey::::...(&sk, ..)`. `ctx` is +/// accepted and ignored, since RSA has no context string. #[allow(non_camel_case_types)] pub struct RSASSA_PSS_SHAKE< X, @@ -39,15 +43,109 @@ pub struct RSASSA_PSS_SHAKE< const SK_LEN: usize, const PK_LEN: usize, > { + _hash: PhantomData, +} + +impl< + X, + const H_LEN: usize, + const S_LEN: usize, + const M_PRIME_LEN: usize, + const DB_LEN: usize, + const L: usize, + const L2: usize, + const L21: usize, + const HALF: usize, + const HALF2: usize, + const HALF21: usize, + const K_LEN: usize, + const SK_LEN: usize, + const PK_LEN: usize, +> Algorithm + for RSASSA_PSS_SHAKE< + X, + H_LEN, + S_LEN, + M_PRIME_LEN, + DB_LEN, + L, + L2, + L21, + HALF, + HALF2, + HALF21, + K_LEN, + SK_LEN, + PK_LEN, + > +{ + const ALG_NAME: &'static str = "RSASSA-PSS-SHAKE"; + /// From the modulus width, by SP 800-57 Part 1 Rev. 5 Table 2; see [`modulus_strength`]. + const MAX_SECURITY_STRENGTH: SecurityStrength = modulus_strength(L); +} + +impl< + X, + const H_LEN: usize, + const S_LEN: usize, + const M_PRIME_LEN: usize, + const DB_LEN: usize, + const L: usize, + const L2: usize, + const L21: usize, + const HALF: usize, + const HALF2: usize, + const HALF21: usize, + const K_LEN: usize, + const SK_LEN: usize, + const PK_LEN: usize, +> SignatureAlgorithm + for RSASSA_PSS_SHAKE< + X, + H_LEN, + S_LEN, + M_PRIME_LEN, + DB_LEN, + L, + L2, + L21, + HALF, + HALF2, + HALF21, + K_LEN, + SK_LEN, + PK_LEN, + > +{ +} + +/// The signer the key hands out; it hashes the message and finishes with [`RSASSA_PSS_SHAKE`]'s encoding and +/// RSASP1. `set_salt` replaces the drawn salt, for a known-answer test; the signature then depends on the key and message alone. +pub struct RsaPssShakeSigner< + 'k, + X, + const H_LEN: usize, + const S_LEN: usize, + const M_PRIME_LEN: usize, + const DB_LEN: usize, + const L: usize, + const L2: usize, + const L21: usize, + const HALF: usize, + const HALF2: usize, + const HALF21: usize, + const K_LEN: usize, + const SK_LEN: usize, + const PK_LEN: usize, +> { + sk: &'k RsaPrivateKey, hash: X, - sk: Option>, - pk: Option>, - /// See `RSASSA_PSS`'s field of the same name. - salt: Option<[u8; S_LEN]>, + salt: [u8; S_LEN], } impl< - X: XOF + Default, + 'k, + X: XOF + HashOneShot, const H_LEN: usize, const S_LEN: usize, const M_PRIME_LEN: usize, @@ -62,7 +160,8 @@ impl< const SK_LEN: usize, const PK_LEN: usize, > - RSASSA_PSS_SHAKE< + RsaPssShakeSigner< + 'k, X, H_LEN, S_LEN, @@ -78,31 +177,180 @@ impl< SK_LEN, PK_LEN, > +{ + /// Replaces the salt drawn at creation with `salt`, for a known-answer test against a + /// published salt; the signature then depends on the key and message alone. + pub fn set_salt(&mut self, salt: [u8; S_LEN]) { + self.salt = salt; + } +} + +/// The verifier the key hands out: hashes the message and finishes with RSAVP1 and the +/// encoding's verification. +pub struct RsaPssShakeVerifier< + 'k, + X, + const H_LEN: usize, + const S_LEN: usize, + const M_PRIME_LEN: usize, + const DB_LEN: usize, + const L: usize, + const L2: usize, + const L21: usize, + const HALF: usize, + const HALF2: usize, + const HALF21: usize, + const K_LEN: usize, + const SK_LEN: usize, + const PK_LEN: usize, +> { + pk: &'k RsaPublicKey, + hash: X, +} + +impl< + X: XOF + HashOneShot, + const H_LEN: usize, + const S_LEN: usize, + const M_PRIME_LEN: usize, + const DB_LEN: usize, + const L: usize, + const L2: usize, + const L21: usize, + const HALF: usize, + const HALF2: usize, + const HALF21: usize, + const K_LEN: usize, + const SK_LEN: usize, + const PK_LEN: usize, +> + SigningKey< + RSASSA_PSS_SHAKE< + X, + H_LEN, + S_LEN, + M_PRIME_LEN, + DB_LEN, + L, + L2, + L21, + HALF, + HALF2, + HALF21, + K_LEN, + SK_LEN, + PK_LEN, + >, + K_LEN, + > for RsaPrivateKey where + // Only a private key type this crate has declared signable (a `SignaturePrivateKey` impl in + // its size module) signs: the verify-only sizes, RSA-1024/1536, have none, so this impl does + // not exist for them -- compile-time enforcement of the crate's `# Scope`. RsaPrivateKey: SignaturePrivateKey, { - /// As [`crate::rsassa_pss::RSASSA_PSS::sign_randomized`]: the salt from the caller's `rng`. - pub fn sign_randomized( - sk: &RsaPrivateKey, - msg: &[u8], + type Signer<'k> + = RsaPssShakeSigner< + 'k, + X, + H_LEN, + S_LEN, + M_PRIME_LEN, + DB_LEN, + L, + L2, + L21, + HALF, + HALF2, + HALF21, + K_LEN, + SK_LEN, + PK_LEN, + > + where + Self: 'k; + + fn create_signer<'k>( + &'k self, rng: &mut dyn RNG, - ) -> Result<[u8; K_LEN], SignatureError> { + _ctx: Option<&[u8]>, + ) -> Result, SignatureError> { + // EMSA-PSS-ENCODE step 4's salt, drawn when the signer is created, as ECDSA draws `k`. let mut salt = [0u8; S_LEN]; rng.next_bytes_out(&mut salt).map_err(SignatureError::RNGError)?; - let mut signer = Self::do_sign_init(sk, None)?; - signer.set_signer_salt(salt); - signer.do_sign_update(msg); - signer.do_sign_final() + Ok(RsaPssShakeSigner { sk: self, hash: X::default(), salt }) } +} + +impl< + X: XOF + HashOneShot, + const H_LEN: usize, + const S_LEN: usize, + const M_PRIME_LEN: usize, + const DB_LEN: usize, + const L: usize, + const L2: usize, + const L21: usize, + const HALF: usize, + const HALF2: usize, + const HALF21: usize, + const K_LEN: usize, + const SK_LEN: usize, + const PK_LEN: usize, +> + VerifyingKey< + RSASSA_PSS_SHAKE< + X, + H_LEN, + S_LEN, + M_PRIME_LEN, + DB_LEN, + L, + L2, + L21, + HALF, + HALF2, + HALF21, + K_LEN, + SK_LEN, + PK_LEN, + >, + K_LEN, + > for RsaPublicKey +where + RsaPublicKey: SignaturePublicKey, +{ + type Verifier<'k> + = RsaPssShakeVerifier< + 'k, + X, + H_LEN, + S_LEN, + M_PRIME_LEN, + DB_LEN, + L, + L2, + L21, + HALF, + HALF2, + HALF21, + K_LEN, + SK_LEN, + PK_LEN, + > + where + Self: 'k; - /// As [`crate::rsassa_pss::RSASSA_PSS::set_signer_salt`]: fixes the salt `do_sign_final` uses. - pub fn set_signer_salt(&mut self, salt: [u8; S_LEN]) { - self.salt = Some(salt); + fn create_verifier<'k>( + &'k self, + _ctx: Option<&[u8]>, + ) -> Result, SignatureError> { + Ok(RsaPssShakeVerifier { pk: self, hash: X::default() }) } } impl< - X: XOF + Default, + X: XOF + HashOneShot, const H_LEN: usize, const S_LEN: usize, const M_PRIME_LEN: usize, @@ -116,8 +364,9 @@ impl< const K_LEN: usize, const SK_LEN: usize, const PK_LEN: usize, -> Signer, SK_LEN, K_LEN> - for RSASSA_PSS_SHAKE< +> AlgorithmInfo + for RsaPssShakeSigner< + '_, X, H_LEN, S_LEN, @@ -133,62 +382,88 @@ impl< SK_LEN, PK_LEN, > -where - // See `RSASSA_PKCS1_v1_5`'s `Signer` impl: no `SignaturePrivateKey`, no `Signer`. - RsaPrivateKey: SignaturePrivateKey, { - fn sign( - sk: &RsaPrivateKey, - msg: &[u8], - ctx: Option<&[u8]>, - ) -> Result<[u8; K_LEN], SignatureError> { - let mut s = Self::do_sign_init(sk, ctx)?; - s.do_sign_update(msg); - s.do_sign_final() - } - - fn sign_out( - sk: &RsaPrivateKey, - msg: &[u8], - ctx: Option<&[u8]>, - output: &mut [u8; K_LEN], - ) -> Result { - output.fill(0); - *output = Self::sign(sk, msg, ctx)?; - Ok(K_LEN) + fn alg_name(&self) -> &'static str { + as Algorithm>::ALG_NAME } - fn do_sign_init( - sk: &RsaPrivateKey, - _ctx: Option<&[u8]>, - ) -> Result { - // ctx ignored -- see `RSASSA_PKCS1_v1_5`'s docs. - Ok(Self { hash: X::default(), sk: Some(sk.clone()), pk: None, salt: None }) + fn max_security_strength(&self) -> SecurityStrength { + as Algorithm>::MAX_SECURITY_STRENGTH } +} - fn do_sign_update(&mut self, msg_chunk: &[u8]) { +impl< + X: XOF + HashOneShot, + const H_LEN: usize, + const S_LEN: usize, + const M_PRIME_LEN: usize, + const DB_LEN: usize, + const L: usize, + const L2: usize, + const L21: usize, + const HALF: usize, + const HALF2: usize, + const HALF21: usize, + const K_LEN: usize, + const SK_LEN: usize, + const PK_LEN: usize, +> SignatureSigner + for RsaPssShakeSigner< + '_, + X, + H_LEN, + S_LEN, + M_PRIME_LEN, + DB_LEN, + L, + L2, + L21, + HALF, + HALF2, + HALF21, + K_LEN, + SK_LEN, + PK_LEN, + > +{ + fn do_update(&mut self, msg_chunk: &[u8]) { self.hash.do_update(msg_chunk); } - fn do_sign_final(self) -> Result<[u8; K_LEN], SignatureError> { - let sk = self.sk.ok_or(SignatureError::GenericError( - "do_sign_final called on a verify-initialized RSASSA_PSS_SHAKE; call do_verify_final instead", - ))?; - // EMSA-PSS step 2, `mHash = Hash(M)`, completed here over the streamed chunks. + fn do_final(self) -> Result<[u8; K_LEN], SignatureError> { + // The encoding's first step, `Hash(M)`, completed here over the streamed chunks. let mut m_hash = [0u8; H_LEN]; self.hash.do_final_out(&mut m_hash); - // EMSA-PSS-ENCODE step 4's salt: fixed by `set_signer_salt`, else fresh from the default - // RNG (see `RSASSA_PSS`). - let salt = match self.salt { - Some(salt) => salt, - None => { - let mut salt = [0u8; S_LEN]; - DefaultRNG::default() - .next_bytes_out(&mut salt) - .map_err(SignatureError::RNGError)?; - salt - } - }; sign_from_hash_with_salt::< X, H_LEN, @@ -202,18 +477,18 @@ where HALF2, HALF21, K_LEN, - >(&sk, &m_hash, &salt) + >(self.sk, &m_hash, &self.salt) } - fn do_sign_final_out(self, output: &mut [u8; K_LEN]) -> Result { + fn do_final_out(self, output: &mut [u8; K_LEN]) -> Result { output.fill(0); - *output = self.do_sign_final()?; + *output = self.do_final()?; Ok(K_LEN) } } impl< - X: XOF + Default, + X: XOF + HashOneShot, const H_LEN: usize, const S_LEN: usize, const M_PRIME_LEN: usize, @@ -227,8 +502,9 @@ impl< const K_LEN: usize, const SK_LEN: usize, const PK_LEN: usize, -> SignatureVerifier, PK_LEN, K_LEN> - for RSASSA_PSS_SHAKE< +> AlgorithmInfo + for RsaPssShakeVerifier< + '_, X, H_LEN, S_LEN, @@ -244,42 +520,97 @@ impl< SK_LEN, PK_LEN, > -where - RsaPublicKey: SignaturePublicKey, { - fn verify( - pk: &RsaPublicKey, - msg: &[u8], - ctx: Option<&[u8]>, - sig: &[u8], - ) -> Result<(), SignatureError> { - let mut v = Self::do_verify_init(pk, ctx)?; - v.do_verify_update(msg); - v.do_verify_final(sig) + fn alg_name(&self) -> &'static str { + as Algorithm>::ALG_NAME } - fn do_verify_init(pk: &RsaPublicKey, _ctx: Option<&[u8]>) -> Result { - Ok(Self { hash: X::default(), sk: None, pk: Some(pk.clone()), salt: None }) + fn max_security_strength(&self) -> SecurityStrength { + as Algorithm>::MAX_SECURITY_STRENGTH } +} - fn do_verify_update(&mut self, msg_chunk: &[u8]) { +impl< + X: XOF + HashOneShot, + const H_LEN: usize, + const S_LEN: usize, + const M_PRIME_LEN: usize, + const DB_LEN: usize, + const L: usize, + const L2: usize, + const L21: usize, + const HALF: usize, + const HALF2: usize, + const HALF21: usize, + const K_LEN: usize, + const SK_LEN: usize, + const PK_LEN: usize, +> SignatureVerifier + for RsaPssShakeVerifier< + '_, + X, + H_LEN, + S_LEN, + M_PRIME_LEN, + DB_LEN, + L, + L2, + L21, + HALF, + HALF2, + HALF21, + K_LEN, + SK_LEN, + PK_LEN, + > +{ + fn do_update(&mut self, msg_chunk: &[u8]) { self.hash.do_update(msg_chunk); } fn do_verify_final(self, sig: &[u8]) -> Result<(), SignatureError> { - let pk = self.pk.ok_or(SignatureError::GenericError( - "do_verify_final called on a sign-initialized RSASSA_PSS_SHAKE; call do_sign_final instead", - ))?; - // RFC 8017 §8.1.2 step 1: "Length checking: If the length of the signature S is not k - // octets, output "invalid signature" and stop." (See `RSASSA_PKCS1_v1_5::do_verify_final`.) - let sig: &[u8; K_LEN] = - sig.try_into().map_err(|_| SignatureError::SignatureVerificationFailed)?; + // RFC 8017 §8.1.2 / §8.2.2 step 1, "Length checking: If the length of the signature S is + // not k octets, output "invalid signature" and stop", reported as the length error the + // shared suite expects for a signature of the wrong size. + let sig: &[u8; K_LEN] = sig.try_into().map_err(|_| { + SignatureError::LengthError("RSA signature must be exactly the modulus length") + })?; let mut m_hash = [0u8; H_LEN]; self.hash.do_final_out(&mut m_hash); - // Step 2.b: RSAVP1's "signature representative out of range" is "invalid signature" here - // (see `RSASSA_PKCS1_v1_5::do_verify_final`). + // 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::( - &pk, &m_hash, sig, + self.pk, &m_hash, sig, ) .map_err(|_| SignatureError::SignatureVerificationFailed) } @@ -287,10 +618,10 @@ where /// RSASSA-PSS-SIGN (RFC 8017 §8.1.1) with the salt supplied directly, given the message's hash /// `m_hash` (`X`'s `H_LEN`-byte output over the message) rather than the message -- mirroring -/// [`crate::rsassa_pss::sign_from_hash_with_salt`], and what the [`Signer`] impl's `do_sign_final` +/// [`crate::rsassa_pss::sign_from_hash_with_salt`], and what [`RsaPssShakeSigner`]'s `do_final` /// calls. pub fn sign_from_hash_with_salt< - X: XOF + Default, + X: XOF + HashOneShot, const H_LEN: usize, const S_LEN: usize, const M_PRIME_LEN: usize, @@ -320,7 +651,7 @@ pub fn sign_from_hash_with_salt< /// for `id-RSASSA-PSS-SHAKE128` and 64 for `id-RSASSA-PSS-SHAKE256`) and hands both to /// [`sign_from_hash_with_salt`]. pub fn sign_from_hash< - X: XOF + Default, + X: XOF + HashOneShot, const H_LEN: usize, const S_LEN: usize, const M_PRIME_LEN: usize, @@ -359,7 +690,7 @@ pub fn sign_from_hash< /// [`crate::rsassa_pss::verify_from_hash`] but built on the SHAKE-native EMSA-PSS-VERIFY, which /// recovers the salt from `EM` itself. pub fn verify_from_hash< - X: XOF + Default, + X: XOF + HashOneShot, const H_LEN: usize, const S_LEN: usize, const M_PRIME_LEN: usize, diff --git a/crypto/rsa/src/rsasve.rs b/crypto/rsa/src/rsasve.rs index 46a4d7f1..6aa9d000 100644 --- a/crypto/rsa/src/rsasve.rs +++ b/crypto/rsa/src/rsasve.rs @@ -16,7 +16,7 @@ //! //! The key types here wrap the signature schemes' [`RsaPublicKey`]/[`RsaPrivateKey`] rather than //! reusing them, so the type system keeps key-establishment and signing keys apart. There is no -//! `Signer` impl for an [`RsaKEMPrivateKey`] and no `KEMDecapsulator` impl for an +//! signing-role impl for an [`RsaKEMPrivateKey`] and no `KEMDecapsulator` impl for an //! [`RsaPrivateKey`]. 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 @@ -204,13 +204,13 @@ impl RsaKEMPrivateKey { /// RSASVE (SP 800-56B Rev. 2 §7.2.1) at one modulus size, as a /// [`KEMEncapsulator`]/[`KEMDecapsulator`]. Each size module names its own instantiation (e.g. -/// `crate::rsa_2048::RSASVE`), along with that size's `keygen`/`keygen_from_rng` as inherent -/// associated functions, which is where the KEM traits' docs put key generation. +/// `crate::rsa_2048::RSASVE`), along with that size's `keygen(rng)` as an inherent associated +/// function, which is where the KEM traits' docs put key generation. /// /// `L`/`L2`/`L21`/`HALF`/`HALF2`/`HALF21` are the widths the rest of this crate threads through /// `rsa_core` (see [`crate::modexp`]). `N_BYTES = 8 * L` is `nLen`, which is both the ciphertext /// length and the shared-secret length. `SECURITY_BITS` is the modulus's SP 800-57 Part 1 -/// security strength, the same value that size's `keygen_from_rng` demands of its RNG. `encaps_rng` +/// security strength, the same value that size's `keygen` demands of its RNG. `encaps_rng` /// demands it too, and the shared secret is labelled with it. /// /// Uninhabited: every operation is an associated function, as with the other KEMs in this @@ -380,7 +380,7 @@ where } } -/// Wraps a size module's signature-typed `keygen_from_rng` result as a KEM key pair, applying +/// Wraps a size module's signature-typed `keygen` result as a KEM key pair, applying /// the KEM key types' checks. These always pass for this crate's own keys, which have `e = 65537` /// and an `n` of exactly `nlen` bits by construction (see [`crate::keygen`]). pub(crate) fn keygen_from( diff --git a/crypto/rsa/tests/keygen_tests.rs b/crypto/rsa/tests/keygen_tests.rs index ad4c1efe..779c5d78 100644 --- a/crypto/rsa/tests/keygen_tests.rs +++ b/crypto/rsa/tests/keygen_tests.rs @@ -1,4 +1,4 @@ -//! Tests for [`bouncycastle_rsa::keygen`] and the per-size `keygen`/`keygen_from_rng` functions: +//! 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. @@ -21,14 +21,15 @@ use bouncycastle_core::errors::{RNGError, SignatureError}; use bouncycastle_core::security_strength::SecurityStrength; -use bouncycastle_core::traits::{RNG, SignaturePrivateKey, SignatureVerifier, Signer}; +use bouncycastle_core::signature_key::{DeterministicSigningKey, SigningKey, VerifyingKey}; +use bouncycastle_core::traits::RNG; +use bouncycastle_core::traits::SignaturePrivateKey; use bouncycastle_core_test_framework::signature::TestFrameworkSignature; use bouncycastle_ec::montgomery::widening_mul; use bouncycastle_rng::DefaultRNG; use bouncycastle_rsa::keygen::{PUBLIC_EXPONENT, is_probable_prime}; use bouncycastle_rsa::rsa_2048::{ - self, PK_LEN, RSA2048PrivateKey, RSA2048PublicKey, RSASSA_PKCS1_v1_5_SHA256, RSASSA_PSS_SHA256, - SIG_LEN, SK_LEN, + self, RSA2048PrivateKey, RSA2048PublicKey, RSASSA_PKCS1_v1_5_SHA256, RSASSA_PSS_SHA256, SIG_LEN, }; use bouncycastle_rsa::{rsa_3072, rsa_4096, rsa_8192}; use core::num::NonZeroUsize; @@ -186,7 +187,7 @@ fn assert_fips_186_5_criteria(&sk.encode(), pk.n(), 5); @@ -194,14 +195,21 @@ fn keygen_2048_meets_fips_186_5_criteria_and_signs() { // 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 = RSASSA_PKCS1_v1_5_SHA256::sign(&sk, msg, None).unwrap(); - RSASSA_PKCS1_v1_5_SHA256::verify(&pk, msg, None, &sig).unwrap(); - assert!(RSASSA_PKCS1_v1_5_SHA256::verify(&pk, b"other", None, &sig).is_err()); - let sig = RSASSA_PSS_SHA256::sign(&sk, msg, None).unwrap(); - RSASSA_PSS_SHA256::verify(&pk, msg, None, &sig).unwrap(); + let sig = DeterministicSigningKey::::sign_deterministic( + &sk, msg, None, + ) + .unwrap(); + VerifyingKey::::verify(&pk, msg, None, &sig).unwrap(); + assert!( + VerifyingKey::::verify(&pk, b"other", None, &sig).is_err() + ); + let sig = + SigningKey::::sign(&sk, &mut DefaultRNG::default(), msg, None) + .unwrap(); + VerifyingKey::::verify(&pk, msg, None, &sig).unwrap(); // Two generations give two keys. - let (pk2, _) = rsa_2048::keygen().unwrap(); + let (pk2, _) = rsa_2048::keygen(&mut DefaultRNG::default()).unwrap(); assert_ne!(pk2.n(), pk.n()); } @@ -209,44 +217,50 @@ fn keygen_2048_meets_fips_186_5_criteria_and_signs() { /// 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(true, false).test_signature::< - RSA2048PublicKey, - RSA2048PrivateKey, - RSASSA_PKCS1_v1_5_SHA256, - RSASSA_PKCS1_v1_5_SHA256, - PK_LEN, - SK_LEN, - SIG_LEN, - >(rsa_2048::keygen, false); + TestFrameworkSignature::new(false).test_deterministic_signature::(|| rsa_2048::keygen(&mut DefaultRNG::default()), false); } #[test] fn keygen_3072_meets_fips_186_5_criteria_and_signs() { - let (pk, sk) = rsa_3072::keygen().unwrap(); + let (pk, sk) = rsa_3072::keygen(&mut DefaultRNG::default()).unwrap(); assert_fips_186_5_criteria::<24, 48, 49>(&sk.encode(), pk.n(), 4); let msg = b"signed with a freshly generated RSA-3072 key"; - let sig = rsa_3072::RSASSA_PKCS1_v1_5_SHA384::sign(&sk, msg, None).unwrap(); - rsa_3072::RSASSA_PKCS1_v1_5_SHA384::verify(&pk, msg, None, &sig).unwrap(); + let sig = + DeterministicSigningKey::::sign_deterministic( + &sk, msg, None, + ) + .unwrap(); + VerifyingKey::::verify(&pk, 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) = rsa_4096::keygen().unwrap(); + let (pk, sk) = rsa_4096::keygen(&mut DefaultRNG::default()).unwrap(); assert_fips_186_5_criteria::<32, 64, 65>(&sk.encode(), pk.n(), 4); let msg = b"signed with a freshly generated RSA-4096 key"; - let sig = rsa_4096::RSASSA_PSS_SHA512::sign(&sk, msg, None).unwrap(); - rsa_4096::RSASSA_PSS_SHA512::verify(&pk, msg, None, &sig).unwrap(); + let sig = SigningKey::::sign( + &sk, + &mut DefaultRNG::default(), + msg, + None, + ) + .unwrap(); + VerifyingKey::::verify(&pk, 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) = rsa_8192::keygen().unwrap(); + let (pk, sk) = rsa_8192::keygen(&mut DefaultRNG::default()).unwrap(); assert_fips_186_5_criteria::<64, 128, 129>(&sk.encode(), pk.n(), 4); let msg = b"signed with a freshly generated RSA-8192 key"; - let sig = rsa_8192::RSASSA_PKCS1_v1_5_SHA256::sign(&sk, msg, None).unwrap(); - rsa_8192::RSASSA_PKCS1_v1_5_SHA256::verify(&pk, msg, None, &sig).unwrap(); + let sig = + DeterministicSigningKey::::sign_deterministic( + &sk, msg, None, + ) + .unwrap(); + VerifyingKey::::verify(&pk, msg, None, &sig).unwrap(); } /// An RNG whose every output is the byte `fill`, reporting `strength`. @@ -285,10 +299,10 @@ impl RNG for ConstantRng { /// 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_from_rng_rejects_an_rng_below_the_required_strength() { +fn keygen_rejects_an_rng_below_the_required_strength() { let mut weak = ConstantRng { fill: 0x42, strength: SecurityStrength::None }; assert!(matches!( - rsa_2048::keygen_from_rng(&mut weak), + rsa_2048::keygen(&mut weak), Err(SignatureError::RNGError(RNGError::SecurityStrengthInsufficientForAlgorithm)) )); } @@ -297,7 +311,7 @@ fn keygen_from_rng_rejects_an_rng_below_the_required_strength() { /// 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_from_rng_gives_up_on_a_stuck_rng() { +fn keygen_gives_up_on_a_stuck_rng() { let mut stuck = ConstantRng { fill: 0x42, strength: SecurityStrength::_256bit }; - assert!(matches!(rsa_2048::keygen_from_rng(&mut stuck), Err(SignatureError::GenericError(_)))); + assert!(matches!(rsa_2048::keygen(&mut stuck), Err(SignatureError::GenericError(_)))); } diff --git a/crypto/rsa/tests/rsa_1024_tests.rs b/crypto/rsa/tests/rsa_1024_tests.rs index e9e5d946..e6737d2e 100644 --- a/crypto/rsa/tests/rsa_1024_tests.rs +++ b/crypto/rsa/tests/rsa_1024_tests.rs @@ -7,7 +7,8 @@ //! differently-shaped file because Wycheproof has no dedicated `rsa_signature_1024_*.json`. use bouncycastle_core::errors::SignatureError; -use bouncycastle_core::traits::{SignaturePublicKey, SignatureVerifier}; +use bouncycastle_core::signature_key::VerifyingKey; +use bouncycastle_core::traits::SignaturePublicKey; use bouncycastle_hex::decode as hex_decode; use bouncycastle_rsa::rsa_1024::{ PK_LEN, RSA1024PublicKey, RSASSA_PKCS1_v1_5_SHA256, RSASSA_PKCS1_v1_5_SHA384, @@ -80,14 +81,14 @@ fn run_sig_gen_group_as_verify_vectors( #[test] fn pkcs1_v1_5_sha256_accepts_genuine_sig_gen_signatures() { run_sig_gen_group_as_verify_vectors("SHA-256", |pk, msg, sig| { - RSASSA_PKCS1_v1_5_SHA256::verify(pk, msg, None, sig).is_ok() + VerifyingKey::::verify(pk, 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| { - RSASSA_PKCS1_v1_5_SHA384::verify(pk, msg, None, sig).is_ok() + VerifyingKey::::verify(pk, msg, None, sig).is_ok() }); } @@ -116,7 +117,7 @@ fn run_sig_gen_group_rejects_wrong_message( #[test] fn pkcs1_v1_5_sha256_rejects_wrong_message() { run_sig_gen_group_rejects_wrong_message("SHA-256", |pk, msg, sig| { - RSASSA_PKCS1_v1_5_SHA256::verify(pk, msg, None, sig).is_ok() + VerifyingKey::::verify(pk, msg, None, sig).is_ok() }); } @@ -126,25 +127,25 @@ fn pkcs1_v1_5_sha256_rejects_wrong_message() { #[test] fn pkcs1_v1_5_sha384_rejects_wrong_message() { run_sig_gen_group_rejects_wrong_message("SHA-384", |pk, msg, sig| { - RSASSA_PKCS1_v1_5_SHA384::verify(pk, msg, None, sig).is_ok() + VerifyingKey::::verify(pk, msg, None, sig).is_ok() }); } // ---- bouncycastle_core trait conformance ------------------------------------------------------ // -// No `Signer` exists at this size (see `rsa_1024.rs`'s docs and its `compile_fail` doctest), so +// 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 -// `SignatureVerifier` and `SignaturePublicKey` impls are checked directly against the same +// `VerifyingKey` and `SignaturePublicKey` 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 "invalid signature", never accepted. +/// 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!( - RSASSA_PKCS1_v1_5_SHA256::verify(pk, msg, None, &sig[..127]), - Err(SignatureError::SignatureVerificationFailed) + VerifyingKey::::verify(pk, msg, None, &sig[..127]), + Err(SignatureError::LengthError(_)) ) }); } diff --git a/crypto/rsa/tests/rsa_1536_tests.rs b/crypto/rsa/tests/rsa_1536_tests.rs index 57eb4f0b..d17c08a3 100644 --- a/crypto/rsa/tests/rsa_1536_tests.rs +++ b/crypto/rsa/tests/rsa_1536_tests.rs @@ -5,7 +5,8 @@ //! material and this crate never constructs an RSA-1536 private key at all. use bouncycastle_core::errors::SignatureError; -use bouncycastle_core::traits::{SignaturePublicKey, SignatureVerifier}; +use bouncycastle_core::signature_key::VerifyingKey; +use bouncycastle_core::traits::SignaturePublicKey; use bouncycastle_hex::decode as hex_decode; use bouncycastle_rsa::rsa_1536::{ PK_LEN, RSA1536PublicKey, RSASSA_PKCS1_v1_5_SHA256, RSASSA_PKCS1_v1_5_SHA384, @@ -79,21 +80,21 @@ fn run_sig_gen_group_as_verify_vectors( #[test] fn pkcs1_v1_5_sha256_accepts_genuine_sig_gen_signatures() { run_sig_gen_group_as_verify_vectors("SHA-256", |pk, msg, sig| { - RSASSA_PKCS1_v1_5_SHA256::verify(pk, msg, None, sig).is_ok() + VerifyingKey::::verify(pk, 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| { - RSASSA_PKCS1_v1_5_SHA384::verify(pk, msg, None, sig).is_ok() + VerifyingKey::::verify(pk, 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| { - RSASSA_PKCS1_v1_5_SHA512::verify(pk, msg, None, sig).is_ok() + VerifyingKey::::verify(pk, msg, None, sig).is_ok() }); } @@ -117,7 +118,7 @@ fn run_sig_gen_group_rejects_wrong_message( #[test] fn pkcs1_v1_5_sha256_rejects_wrong_message() { run_sig_gen_group_rejects_wrong_message("SHA-256", |pk, msg, sig| { - RSASSA_PKCS1_v1_5_SHA256::verify(pk, msg, None, sig).is_ok() + VerifyingKey::::verify(pk, msg, None, sig).is_ok() }); } @@ -127,14 +128,14 @@ fn pkcs1_v1_5_sha256_rejects_wrong_message() { #[test] fn pkcs1_v1_5_sha384_rejects_wrong_message() { run_sig_gen_group_rejects_wrong_message("SHA-384", |pk, msg, sig| { - RSASSA_PKCS1_v1_5_SHA384::verify(pk, msg, None, sig).is_ok() + VerifyingKey::::verify(pk, 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| { - RSASSA_PKCS1_v1_5_SHA512::verify(pk, msg, None, sig).is_ok() + VerifyingKey::::verify(pk, msg, None, sig).is_ok() }); } @@ -147,8 +148,8 @@ fn pkcs1_v1_5_sha512_rejects_wrong_message() { fn trait_verify_rejects_truncated_signature() { run_sig_gen_group_as_verify_vectors("SHA-256", |pk, msg, sig| { matches!( - RSASSA_PKCS1_v1_5_SHA256::verify(pk, msg, None, &sig[..191]), - Err(SignatureError::SignatureVerificationFailed) + VerifyingKey::::verify(pk, msg, None, &sig[..191]), + Err(SignatureError::LengthError(_)) ) }); } 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 index 70fea371..879e0f4c 100644 --- 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 @@ -14,12 +14,12 @@ //! the hash in question -- is checked against all of Wycheproof's real vectors for both hashes. use bouncycastle_core::errors::SignatureError; -use bouncycastle_core::traits::{SignatureVerifier, Signer}; +use bouncycastle_core::signature_key::{DeterministicSigningKey, VerifyingKey}; use bouncycastle_core_test_framework::signature::TestFrameworkSignature; use bouncycastle_hex::decode as hex_decode; use bouncycastle_rsa::rsa_2048::{ - PK_LEN, RSA2048PrivateKey, RSA2048PublicKey, RSASSA_PKCS1_v1_5_SHA384, - RSASSA_PKCS1_v1_5_SHA512, SIG_LEN, SK_LEN, + RSA2048PrivateKey, RSA2048PublicKey, RSASSA_PKCS1_v1_5_SHA384, RSASSA_PKCS1_v1_5_SHA512, + SIG_LEN, }; use serde_json::Value; use std::fs; @@ -98,18 +98,30 @@ fn genuine_key() -> RSA2048PrivateKey { fn pkcs1_v1_5_sha384_round_trips() { let sk = genuine_key(); let pk = RSA2048PublicKey::new(sk.n(), 0x10001).unwrap(); - let sig = RSASSA_PKCS1_v1_5_SHA384::sign(&sk, b"hello", None).expect("signing must succeed"); - RSASSA_PKCS1_v1_5_SHA384::verify(&pk, b"hello", None, &sig).expect("must verify"); - assert!(RSASSA_PKCS1_v1_5_SHA384::verify(&pk, b"goodbye", None, &sig).is_err()); + let sig = DeterministicSigningKey::::sign_deterministic( + &sk, b"hello", None, + ) + .expect("signing must succeed"); + VerifyingKey::::verify(&pk, b"hello", None, &sig) + .expect("must verify"); + assert!( + VerifyingKey::::verify(&pk, b"goodbye", None, &sig).is_err() + ); } #[test] fn pkcs1_v1_5_sha512_round_trips() { let sk = genuine_key(); let pk = RSA2048PublicKey::new(sk.n(), 0x10001).unwrap(); - let sig = RSASSA_PKCS1_v1_5_SHA512::sign(&sk, b"hello", None).expect("signing must succeed"); - RSASSA_PKCS1_v1_5_SHA512::verify(&pk, b"hello", None, &sig).expect("must verify"); - assert!(RSASSA_PKCS1_v1_5_SHA512::verify(&pk, b"goodbye", None, &sig).is_err()); + let sig = DeterministicSigningKey::::sign_deterministic( + &sk, b"hello", None, + ) + .expect("signing must succeed"); + VerifyingKey::::verify(&pk, b"hello", None, &sig) + .expect("must verify"); + assert!( + VerifyingKey::::verify(&pk, b"goodbye", None, &sig).is_err() + ); } fn run_verify_vectors( @@ -182,7 +194,9 @@ fn run_verify_vectors( fn rsa_signature_sha384_wycheproof_vectors() { run_verify_vectors( "rsa_signature_2048_sha384_test.json", - |pk, msg, sig| RSASSA_PKCS1_v1_5_SHA384::verify(pk, msg, None, sig).is_ok(), + |pk, msg, sig| { + VerifyingKey::::verify(pk, msg, None, sig).is_ok() + }, "SHA-384", 258, 7, @@ -194,7 +208,9 @@ fn rsa_signature_sha384_wycheproof_vectors() { fn rsa_signature_sha512_wycheproof_vectors() { run_verify_vectors( "rsa_signature_2048_sha512_test.json", - |pk, msg, sig| RSASSA_PKCS1_v1_5_SHA512::verify(pk, msg, None, sig).is_ok(), + |pk, msg, sig| { + VerifyingKey::::verify(pk, msg, None, sig).is_ok() + }, "SHA-512", 259, 8, @@ -215,23 +231,7 @@ fn fixed_keypair() -> Result<(RSA2048PublicKey, RSA2048PrivateKey), SignatureErr /// suite, over the same generic code. #[test] fn pkcs1_v1_5_sha384_sha512_trait_conformance_suite() { - let framework = TestFrameworkSignature::new(true, false); - framework.test_signature::< - RSA2048PublicKey, - RSA2048PrivateKey, - RSASSA_PKCS1_v1_5_SHA384, - RSASSA_PKCS1_v1_5_SHA384, - PK_LEN, - SK_LEN, - SIG_LEN, - >(fixed_keypair, false); - framework.test_signature::< - RSA2048PublicKey, - RSA2048PrivateKey, - RSASSA_PKCS1_v1_5_SHA512, - RSASSA_PKCS1_v1_5_SHA512, - PK_LEN, - SK_LEN, - SIG_LEN, - >(fixed_keypair, false); + let framework = TestFrameworkSignature::new(false); + framework.test_deterministic_signature::(fixed_keypair, false); + framework.test_deterministic_signature::(fixed_keypair, 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 index afc8a3b5..2f53e653 100644 --- a/crypto/rsa/tests/rsa_2048_pkcs1_v1_5_tests.rs +++ b/crypto/rsa/tests/rsa_2048_pkcs1_v1_5_tests.rs @@ -32,7 +32,8 @@ //! constructed edge case. use bouncycastle_core::errors::SignatureError; -use bouncycastle_core::traits::{Hash, SignatureVerifier, Signer}; +use bouncycastle_core::signature_key::{DeterministicSigningKey, VerifyingKey}; +use bouncycastle_core::traits::{HashOneShot, SignatureSigner}; use bouncycastle_core_test_framework::signature::{ TestFrameworkSignature, TestFrameworkSignatureKeys, }; @@ -146,7 +147,10 @@ fn pkcs1_v1_5_sig_gen_2048_sha256() { 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 = RSASSA_PKCS1_v1_5_SHA256::sign(&sk, &msg, None).unwrap_or_else(|e| { + let sig = DeterministicSigningKey::::sign_deterministic( + &sk, &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"); @@ -164,22 +168,14 @@ fn fixed_keypair() -> Result<(RSA2048PublicKey, RSA2048PrivateKey), SignatureErr Ok((pk, sk)) } -/// The shared `Signer`/`SignatureVerifier` conformance suite (per QUALITY_AND_STYLE's rule that +/// 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(true, false).test_signature::< - RSA2048PublicKey, - RSA2048PrivateKey, - RSASSA_PKCS1_v1_5_SHA256, - RSASSA_PKCS1_v1_5_SHA256, - PK_LEN, - SK_LEN, - SIG_LEN, - >(fixed_keypair, true); + TestFrameworkSignature::new(false).test_deterministic_signature::(fixed_keypair, true); } #[test] @@ -189,61 +185,56 @@ fn key_trait_boundary_conditions() { } /// Streamed and one-shot signing are one computation: PKCS#1 v1.5 is deterministic, so the -/// chunked `do_sign_init`/`do_sign_update`/`do_sign_final` path reproduces `Signer::sign` byte for byte. +/// 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 = RSASSA_PKCS1_v1_5_SHA256::sign(&sk, msg, None).unwrap(); - let mut signer = RSASSA_PKCS1_v1_5_SHA256::do_sign_init(&sk, None).unwrap(); - signer.do_sign_update(&msg[..10]); - signer.do_sign_update(&msg[10..]); - let streamed = signer.do_sign_final().unwrap(); + let one_shot = DeterministicSigningKey::::sign_deterministic( + &sk, msg, None, + ) + .unwrap(); + let mut signer = + DeterministicSigningKey::::create_signer_deterministic( + &sk, None, + ) + .unwrap(); + signer.do_update(&msg[..10]); + signer.do_update(&msg[10..]); + let streamed = signer.do_final().unwrap(); assert_eq!(streamed, one_shot); - RSASSA_PKCS1_v1_5_SHA256::verify(&pk, msg, None, &streamed).unwrap(); + VerifyingKey::::verify(&pk, 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. `core-test-framework` -/// covers the too-long case; this is the too-short one. +/// 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 = RSASSA_PKCS1_v1_5_SHA256::sign(&sk, b"msg", None).unwrap(); + let sig = DeterministicSigningKey::::sign_deterministic( + &sk, b"msg", None, + ) + .unwrap(); assert!(matches!( - RSASSA_PKCS1_v1_5_SHA256::verify(&pk, b"msg", None, &sig[..SIG_LEN - 1]), - Err(SignatureError::SignatureVerificationFailed) + VerifyingKey::::verify( + &pk, + b"msg", + None, + &sig[..SIG_LEN - 1] + ), + Err(SignatureError::LengthError(_)) )); assert!(matches!( - RSASSA_PKCS1_v1_5_SHA256::verify(&pk, b"msg", None, &[]), - Err(SignatureError::SignatureVerificationFailed) + VerifyingKey::::verify(&pk, 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 trait_final_in_the_wrong_role_is_an_error() { - let (pk, sk) = fixed_keypair().unwrap(); - let mut out = [0u8; SIG_LEN]; - - let verifier = RSASSA_PKCS1_v1_5_SHA256::do_verify_init(&pk, None).unwrap(); - assert!(matches!(verifier.do_sign_final(), Err(SignatureError::GenericError(_)))); - let verifier = RSASSA_PKCS1_v1_5_SHA256::do_verify_init(&pk, None).unwrap(); - assert!(matches!(verifier.do_sign_final_out(&mut out), Err(SignatureError::GenericError(_)))); - - let signer = RSASSA_PKCS1_v1_5_SHA256::do_sign_init(&sk, None).unwrap(); - assert!(matches!(signer.do_verify_final(&out), Err(SignatureError::GenericError(_)))); -} - -/// All three groups of `rsa_signature_2048_sha256_test.json` (259 vectors; the first group's key -/// is [`wycheproof_key`]'s, the other two are unrelated keys parsed from the JSON) through -/// `SignatureVerifier::verify`'s `&[u8]` signature, so the wrong-length vectors reach the -/// verifier and must come back as `SignatureVerificationFailed` (RFC 8017 §8.2.2 step 1). The one -/// "acceptable" vector is `MissingNull` (a `DigestInfo` whose `AlgorithmIdentifier` omits the -/// `NULL` parameters), accepted by this crate's explicit policy -- see -/// `emsa_pkcs1_v1_5::emsa_pkcs1_v1_5_verify_from_hash`'s docs. -#[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"); @@ -264,7 +255,8 @@ fn rsa_signature_sha256_all_groups() { 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 = RSASSA_PKCS1_v1_5_SHA256::verify(&pk, &msg, None, &sig); + let result = + VerifyingKey::::verify(&pk, &msg, None, &sig); match test["result"].as_str().unwrap() { // "acceptable" is only ever MissingNull in this file, accepted by policy (see above). "valid" | "acceptable" => { @@ -275,9 +267,9 @@ fn rsa_signature_sha256_all_groups() { assert!(result.is_err(), "tcId {tc_id}: expected invalid, got valid"); if sig.len() != SIG_LEN { assert!( - matches!(result, Err(SignatureError::SignatureVerificationFailed)), + matches!(result, Err(SignatureError::LengthError(_))), "tcId {tc_id}: a {}-byte signature must fail step 1's length check \ - as 'invalid signature', got {result:?}", + as a LengthError, got {result:?}", sig.len() ); num_wrong_length += 1; @@ -305,7 +297,7 @@ 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::default().hash_out(b"msg", &mut digest); + SHA256::hash_out(b"msg", &mut digest); assert!(matches!( rsassa_pkcs1_v1_5::verify_from_hash::( &pk, &digest, &too_big @@ -313,7 +305,7 @@ fn trait_verify_reports_out_of_range_representative_as_invalid_signature() { Err(SignatureError::DecodingError(_)) )); assert!(matches!( - RSASSA_PKCS1_v1_5_SHA256::verify(&pk, b"msg", None, &too_big), + VerifyingKey::::verify(&pk, b"msg", None, &too_big), Err(SignatureError::SignatureVerificationFailed) )); } diff --git a/crypto/rsa/tests/rsa_2048_pss_sha384_sha512_tests.rs b/crypto/rsa/tests/rsa_2048_pss_sha384_sha512_tests.rs index 3d0bb5f1..efdfe683 100644 --- a/crypto/rsa/tests/rsa_2048_pss_sha384_sha512_tests.rs +++ b/crypto/rsa/tests/rsa_2048_pss_sha384_sha512_tests.rs @@ -7,26 +7,27 @@ //! sig-gen key here (rather than factoring a fresh one) is the right tradeoff. use bouncycastle_core::errors::SignatureError; -use bouncycastle_core::traits::{SignatureVerifier, Signer}; +use bouncycastle_core::signature_key::{SigningKey, VerifyingKey}; +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::rsa_2048::{ - PK_LEN, RSA2048PrivateKey, RSA2048PublicKey, RSASSA_PSS_SHA384, RSASSA_PSS_SHA512, SIG_LEN, - SK_LEN, + RSA2048PrivateKey, RSA2048PublicKey, 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_signer_salt`) -- the +/// 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 mut signer = <$ty>::do_sign_init($sk, None).unwrap(); - signer.set_signer_salt($salt); - signer.do_sign_update($msg); - signer.do_sign_final() + let mut signer = + SigningKey::<$ty, 256>::create_signer($sk, &mut DefaultRNG::default(), None).unwrap(); + signer.set_salt($salt); + signer.do_update($msg); + signer.do_final() }}; } @@ -105,8 +106,8 @@ fn pss_sha384_fixed_salt_round_trips() { let salt = [0x42u8; 48]; let sig = sign_with_salt!(RSASSA_PSS_SHA384, &sk, b"hello", salt).expect("signing must succeed"); - RSASSA_PSS_SHA384::verify(&pk, b"hello", None, &sig).expect("must verify"); - assert!(RSASSA_PSS_SHA384::verify(&pk, b"goodbye", None, &sig).is_err()); + VerifyingKey::::verify(&pk, b"hello", None, &sig).expect("must verify"); + assert!(VerifyingKey::::verify(&pk, b"goodbye", None, &sig).is_err()); } #[test] @@ -114,13 +115,15 @@ fn pss_sha384_rng_produces_fresh_salts_that_both_verify() { let sk = genuine_key(); let pk = RSA2048PublicKey::new(sk.n(), 0x10001).unwrap(); let mut rng = DefaultRNG::default(); - let sig_a = - RSASSA_PSS_SHA384::sign_randomized(&sk, b"hello", &mut rng).expect("signing must succeed"); - let sig_b = - RSASSA_PSS_SHA384::sign_randomized(&sk, b"hello", &mut rng).expect("signing must succeed"); + let sig_a = SigningKey::::sign(&sk, &mut rng, b"hello", None) + .expect("signing must succeed"); + let sig_b = SigningKey::::sign(&sk, &mut rng, b"hello", None) + .expect("signing must succeed"); assert_ne!(sig_a, sig_b); - RSASSA_PSS_SHA384::verify(&pk, b"hello", None, &sig_a).expect("sig_a must verify"); - RSASSA_PSS_SHA384::verify(&pk, b"hello", None, &sig_b).expect("sig_b must verify"); + VerifyingKey::::verify(&pk, b"hello", None, &sig_a) + .expect("sig_a must verify"); + VerifyingKey::::verify(&pk, b"hello", None, &sig_b) + .expect("sig_b must verify"); } #[test] @@ -130,8 +133,8 @@ fn pss_sha512_fixed_salt_round_trips() { let salt = [0x42u8; 64]; let sig = sign_with_salt!(RSASSA_PSS_SHA512, &sk, b"hello", salt).expect("signing must succeed"); - RSASSA_PSS_SHA512::verify(&pk, b"hello", None, &sig).expect("must verify"); - assert!(RSASSA_PSS_SHA512::verify(&pk, b"goodbye", None, &sig).is_err()); + VerifyingKey::::verify(&pk, b"hello", None, &sig).expect("must verify"); + assert!(VerifyingKey::::verify(&pk, b"goodbye", None, &sig).is_err()); } #[test] @@ -139,13 +142,15 @@ fn pss_sha512_rng_produces_fresh_salts_that_both_verify() { let sk = genuine_key(); let pk = RSA2048PublicKey::new(sk.n(), 0x10001).unwrap(); let mut rng = DefaultRNG::default(); - let sig_a = - RSASSA_PSS_SHA512::sign_randomized(&sk, b"hello", &mut rng).expect("signing must succeed"); - let sig_b = - RSASSA_PSS_SHA512::sign_randomized(&sk, b"hello", &mut rng).expect("signing must succeed"); + let sig_a = SigningKey::::sign(&sk, &mut rng, b"hello", None) + .expect("signing must succeed"); + let sig_b = SigningKey::::sign(&sk, &mut rng, b"hello", None) + .expect("signing must succeed"); assert_ne!(sig_a, sig_b); - RSASSA_PSS_SHA512::verify(&pk, b"hello", None, &sig_a).expect("sig_a must verify"); - RSASSA_PSS_SHA512::verify(&pk, b"hello", None, &sig_b).expect("sig_b must verify"); + VerifyingKey::::verify(&pk, b"hello", None, &sig_a) + .expect("sig_a must verify"); + VerifyingKey::::verify(&pk, b"hello", None, &sig_b) + .expect("sig_b must verify"); } #[test] @@ -178,7 +183,8 @@ fn rsa_pss_sha384_mgf1_48_wycheproof_vectors() { continue; }; - let verified = RSASSA_PSS_SHA384::verify(&pk, &msg, None, &sig).is_ok(); + let verified = + VerifyingKey::::verify(&pk, &msg, None, &sig).is_ok(); match test["result"].as_str().unwrap() { "valid" => { assert!(verified, "tcId {tc_id}: expected valid, got invalid"); @@ -210,41 +216,41 @@ fn fixed_keypair() -> Result<(RSA2048PublicKey, RSA2048PrivateKey), SignatureErr /// `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, false); - framework.test_signature::< - RSA2048PublicKey, - RSA2048PrivateKey, - RSASSA_PSS_SHA384, - RSASSA_PSS_SHA384, - PK_LEN, - SK_LEN, - SIG_LEN, - >(fixed_keypair, false); - framework.test_signature::< - RSA2048PublicKey, - RSA2048PrivateKey, - RSASSA_PSS_SHA512, - RSASSA_PSS_SHA512, - PK_LEN, - SK_LEN, - SIG_LEN, - >(fixed_keypair, false); + let framework = TestFrameworkSignature::new(false); + framework.test_signature::( + fixed_keypair, false, + ); + framework.test_signature::( + fixed_keypair, false, + ); } #[test] fn pss_sha384_and_sha512_reject_each_others_signatures() { let (pk, sk) = fixed_keypair().unwrap(); let msg = b"PSS across both APIs"; - RSASSA_PSS_SHA384::verify(&pk, msg, None, &RSASSA_PSS_SHA384::sign(&sk, msg, None).unwrap()) - .unwrap(); - RSASSA_PSS_SHA512::verify(&pk, msg, None, &RSASSA_PSS_SHA512::sign(&sk, msg, None).unwrap()) - .unwrap(); + VerifyingKey::::verify( + &pk, + msg, + None, + &SigningKey::::sign(&sk, &mut DefaultRNG::default(), msg, None) + .unwrap(), + ) + .unwrap(); + VerifyingKey::::verify( + &pk, + msg, + None, + &SigningKey::::sign(&sk, &mut DefaultRNG::default(), msg, None) + .unwrap(), + ) + .unwrap(); let mut rng = DefaultRNG::default(); - let free_384 = RSASSA_PSS_SHA384::sign_randomized(&sk, msg, &mut rng).unwrap(); - let free_512 = RSASSA_PSS_SHA512::sign_randomized(&sk, msg, &mut rng).unwrap(); - RSASSA_PSS_SHA384::verify(&pk, msg, None, &free_384).unwrap(); - RSASSA_PSS_SHA512::verify(&pk, msg, None, &free_512).unwrap(); + let free_384 = SigningKey::::sign(&sk, &mut rng, msg, None).unwrap(); + let free_512 = SigningKey::::sign(&sk, &mut rng, msg, None).unwrap(); + VerifyingKey::::verify(&pk, msg, None, &free_384).unwrap(); + VerifyingKey::::verify(&pk, msg, None, &free_512).unwrap(); // The two hash pairings are distinct encodings: neither accepts the other's signature. - assert!(RSASSA_PSS_SHA384::verify(&pk, msg, None, &free_512).is_err()); - assert!(RSASSA_PSS_SHA512::verify(&pk, msg, None, &free_384).is_err()); + assert!(VerifyingKey::::verify(&pk, msg, None, &free_512).is_err()); + assert!(VerifyingKey::::verify(&pk, 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 index 2b969698..4fd50320 100644 --- a/crypto/rsa/tests/rsa_2048_pss_shake128_tests.rs +++ b/crypto/rsa/tests/rsa_2048_pss_shake128_tests.rs @@ -6,12 +6,14 @@ //! checked against all of Wycheproof's real vectors. use bouncycastle_core::errors::SignatureError; -use bouncycastle_core::traits::{Hash, RNG, SignatureVerifier, Signer}; +use bouncycastle_core::signature_key::{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::rsa_2048::{ - PK_LEN, RSA2048PrivateKey, RSA2048PublicKey, RSASSA_PSS_SHAKE128, SIG_LEN, SK_LEN, + RSA2048PrivateKey, RSA2048PublicKey, RSASSA_PSS_SHAKE128, SIG_LEN, }; use bouncycastle_rsa::rsassa_pss_shake; use bouncycastle_sha3::SHAKE128; @@ -19,14 +21,15 @@ use serde_json::Value; use std::fs; use std::path::Path; -/// Signs through the streaming trait path with a fixed salt (`set_signer_salt`) -- the +/// 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 mut signer = <$ty>::do_sign_init($sk, None).unwrap(); - signer.set_signer_salt($salt); - signer.do_sign_update($msg); - signer.do_sign_final() + let mut signer = + SigningKey::<$ty, 256>::create_signer($sk, &mut DefaultRNG::default(), None).unwrap(); + signer.set_salt($salt); + signer.do_update($msg); + signer.do_final() }}; } @@ -107,13 +110,17 @@ fn pss_shake128_sign_with_fixed_salt_round_trips() { let salt = [0x42u8; 32]; let sig = sign_with_salt!(RSASSA_PSS_SHAKE128, &sk, b"the message to sign", salt) .expect("signing must succeed"); - RSASSA_PSS_SHAKE128::verify(&pk, b"the message to sign", None, &sig).expect("must verify"); + VerifyingKey::::verify(&pk, 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!(RSASSA_PSS_SHAKE128::verify(&pk, b"a different message", None, &sig).is_err()); + assert!( + VerifyingKey::::verify(&pk, b"a different message", None, &sig) + .is_err() + ); } #[test] @@ -122,13 +129,15 @@ fn pss_shake128_sign_with_rng_produces_fresh_salts_that_both_verify() { let pk = RSA2048PublicKey::new(sk.n(), 0x10001).unwrap(); let mut rng = DefaultRNG::default(); - let sig_a = RSASSA_PSS_SHAKE128::sign_randomized(&sk, b"hello", &mut rng) + let sig_a = SigningKey::::sign(&sk, &mut rng, b"hello", None) .expect("signing must succeed"); - let sig_b = RSASSA_PSS_SHAKE128::sign_randomized(&sk, b"hello", &mut rng) + let sig_b = SigningKey::::sign(&sk, &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"); - RSASSA_PSS_SHAKE128::verify(&pk, b"hello", None, &sig_a).expect("sig_a must verify"); - RSASSA_PSS_SHAKE128::verify(&pk, b"hello", None, &sig_b).expect("sig_b must verify"); + VerifyingKey::::verify(&pk, b"hello", None, &sig_a) + .expect("sig_a must verify"); + VerifyingKey::::verify(&pk, b"hello", None, &sig_b) + .expect("sig_b must verify"); } #[test] @@ -161,7 +170,8 @@ fn rsa_pss_2048_shake128_wycheproof_vectors() { continue; }; - let verified = RSASSA_PSS_SHAKE128::verify(&pk, &msg, None, &sig).is_ok(); + let verified = + VerifyingKey::::verify(&pk, &msg, None, &sig).is_ok(); match test["result"].as_str().unwrap() { "valid" => { assert!(verified, "tcId {tc_id}: expected valid, got invalid"); @@ -194,19 +204,14 @@ fn fixed_keypair() -> Result<(RSA2048PublicKey, RSA2048PrivateKey), SignatureErr /// gets the exhaustive pass once, here. #[test] fn pss_shake128_trait_conformance_suite() { - TestFrameworkSignature::new(false, false).test_signature::< - RSA2048PublicKey, - RSA2048PrivateKey, - RSASSA_PSS_SHAKE128, - RSASSA_PSS_SHAKE128, - PK_LEN, - SK_LEN, - SIG_LEN, - >(fixed_keypair, true); + TestFrameworkSignature::new(false) + .test_signature::( + fixed_keypair, true, + ); } /// A fixed-output RNG (all-`0x42` bytes), as `bouncycastle-ecdsa`'s tests use: pins that -/// `sign_randomized` takes its salt from the caller's RNG and nowhere else. +/// `SigningKey::sign` takes its salt from the caller's RNG and nowhere else. struct FixedRng; impl RNG for FixedRng { fn add_seed_keymaterial( @@ -239,23 +244,28 @@ impl RNG for FixedRng { } } -/// `set_signer_salt` fixes the salt on the streaming path (the counterpart of ML-DSA's +/// `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_shake::sign_from_hash_with_salt` over the same digest and salt, while an unfixed /// streamed signature is fresh. #[test] -fn set_signer_salt_fixes_the_salt_on_the_streaming_path() { +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 mut signer = RSASSA_PSS_SHAKE128::do_sign_init(&sk, None).unwrap(); - signer.set_signer_salt(salt); - signer.do_sign_update(&msg[..11]); - signer.do_sign_update(&msg[11..]); - let sig = signer.do_sign_final().unwrap(); + let mut signer = SigningKey::::create_signer( + &sk, + &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::default().hash_out(msg, &mut digest); + SHAKE128::hash_out(msg, &mut digest); let expected = rsassa_pss_shake::sign_from_hash_with_salt::< SHAKE128, 32, @@ -272,37 +282,43 @@ fn set_signer_salt_fixes_the_salt_on_the_streaming_path() { >(&sk, &digest, &salt) .unwrap(); assert_eq!(sig, expected); - RSASSA_PSS_SHAKE128::verify(&pk, msg, None, &sig).unwrap(); + VerifyingKey::::verify(&pk, msg, None, &sig).unwrap(); - let mut fresh = RSASSA_PSS_SHAKE128::do_sign_init(&sk, None).unwrap(); - fresh.do_sign_update(msg); - assert_ne!(fresh.do_sign_final().unwrap(), sig, "without set_signer_salt the salt is fresh"); + let mut fresh = SigningKey::::create_signer( + &sk, + &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 mut verifier = RSASSA_PSS_SHAKE128::do_verify_init(&pk, None).unwrap(); - verifier.set_signer_salt([0xffu8; 32]); - verifier.do_verify_update(msg); + let mut verifier = + VerifyingKey::::create_verifier(&pk, None).unwrap(); + verifier.do_update(msg); verifier.do_verify_final(&sig).unwrap(); } -/// `sign_randomized` draws the salt from the caller's RNG (the ECDSA/SM2 shape): with a +/// `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_randomized_takes_the_salt_from_the_callers_rng() { +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 = RSASSA_PSS_SHAKE128::sign_randomized(&sk, msg, &mut FixedRng).unwrap(); + let from_fixed_rng = + SigningKey::::sign(&sk, &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 = RSASSA_PSS_SHAKE128::sign_randomized(&sk, msg, &mut rng).unwrap(); - let b = RSASSA_PSS_SHAKE128::sign_randomized(&sk, msg, &mut rng).unwrap(); + let a = SigningKey::::sign(&sk, &mut rng, msg, None).unwrap(); + let b = SigningKey::::sign(&sk, &mut rng, msg, None).unwrap(); assert_ne!(a, b); - RSASSA_PSS_SHAKE128::verify(&pk, msg, None, &a).unwrap(); - RSASSA_PSS_SHAKE128::verify(&pk, msg, None, &b).unwrap(); - assert!(RSASSA_PSS_SHAKE128::verify(&pk, b"other", None, &a).is_err()); + VerifyingKey::::verify(&pk, msg, None, &a).unwrap(); + VerifyingKey::::verify(&pk, msg, None, &b).unwrap(); + assert!(VerifyingKey::::verify(&pk, 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 index d0a5a932..fc314fef 100644 --- a/crypto/rsa/tests/rsa_2048_pss_tests.rs +++ b/crypto/rsa/tests/rsa_2048_pss_tests.rs @@ -11,27 +11,28 @@ //! by comparing moduli in Python before writing this file). use bouncycastle_core::errors::SignatureError; -use bouncycastle_core::traits::{Hash, RNG, SignatureVerifier, Signer}; +use bouncycastle_core::signature_key::{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::rsa_2048::{ - PK_LEN, RSA2048PrivateKey, RSA2048PublicKey, RSASSA_PSS_SHA256, SIG_LEN, SK_LEN, -}; +use bouncycastle_rsa::rsa_2048::{RSA2048PrivateKey, RSA2048PublicKey, RSASSA_PSS_SHA256, SIG_LEN}; use bouncycastle_rsa::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_signer_salt`) -- the +/// 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 mut signer = <$ty>::do_sign_init($sk, None).unwrap(); - signer.set_signer_salt($salt); - signer.do_sign_update($msg); - signer.do_sign_final() + let mut signer = + SigningKey::<$ty, 256>::create_signer($sk, &mut DefaultRNG::default(), None).unwrap(); + signer.set_salt($salt); + signer.do_update($msg); + signer.do_final() }}; } @@ -112,13 +113,17 @@ fn pss_sign_with_fixed_salt_round_trips() { let salt = [0x42u8; 32]; let sig = sign_with_salt!(RSASSA_PSS_SHA256, &sk, b"the message to sign", salt) .expect("signing must succeed"); - RSASSA_PSS_SHA256::verify(&pk, b"the message to sign", None, &sig).expect("must verify"); + VerifyingKey::::verify(&pk, 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!(RSASSA_PSS_SHA256::verify(&pk, b"a different message", None, &sig).is_err()); + assert!( + VerifyingKey::::verify(&pk, b"a different message", None, &sig) + .is_err() + ); } #[test] @@ -127,13 +132,15 @@ fn pss_sign_with_rng_produces_fresh_salts_that_both_verify() { let pk = RSA2048PublicKey::new(sk.n(), 0x10001).unwrap(); let mut rng = DefaultRNG::default(); - let sig_a = - RSASSA_PSS_SHA256::sign_randomized(&sk, b"hello", &mut rng).expect("signing must succeed"); - let sig_b = - RSASSA_PSS_SHA256::sign_randomized(&sk, b"hello", &mut rng).expect("signing must succeed"); + let sig_a = SigningKey::::sign(&sk, &mut rng, b"hello", None) + .expect("signing must succeed"); + let sig_b = SigningKey::::sign(&sk, &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"); - RSASSA_PSS_SHA256::verify(&pk, b"hello", None, &sig_a).expect("sig_a must verify"); - RSASSA_PSS_SHA256::verify(&pk, b"hello", None, &sig_b).expect("sig_b must verify"); + VerifyingKey::::verify(&pk, b"hello", None, &sig_a) + .expect("sig_a must verify"); + VerifyingKey::::verify(&pk, b"hello", None, &sig_b) + .expect("sig_b must verify"); } #[test] @@ -166,7 +173,8 @@ fn rsa_pss_sha256_mgf1_32_wycheproof_vectors() { continue; }; - let verified = RSASSA_PSS_SHA256::verify(&pk, &msg, None, &sig).is_ok(); + let verified = + VerifyingKey::::verify(&pk, &msg, None, &sig).is_ok(); match test["result"].as_str().unwrap() { "valid" => { assert!(verified, "tcId {tc_id}: expected valid, got invalid"); @@ -194,24 +202,19 @@ fn fixed_keypair() -> Result<(RSA2048PublicKey, RSA2048PrivateKey), SignatureErr Ok((pk, sk)) } -/// `core-test-framework`'s conformance suite: randomized (`Signer::sign` draws a fresh salt from +/// `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, false).test_signature::< - RSA2048PublicKey, - RSA2048PrivateKey, - RSASSA_PSS_SHA256, - RSASSA_PSS_SHA256, - PK_LEN, - SK_LEN, - SIG_LEN, - >(fixed_keypair, true); + TestFrameworkSignature::new(false) + .test_signature::( + fixed_keypair, true, + ); } /// A fixed-output RNG (all-`0x42` bytes), as `bouncycastle-ecdsa`'s tests use: pins that -/// `sign_randomized` takes its salt from the caller's RNG and nowhere else. +/// `SigningKey::sign` takes its salt from the caller's RNG and nowhere else. struct FixedRng; impl RNG for FixedRng { fn add_seed_keymaterial( @@ -244,23 +247,25 @@ impl RNG for FixedRng { } } -/// `set_signer_salt` fixes the salt on the streaming path (the counterpart of ML-DSA's +/// `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_signer_salt_fixes_the_salt_on_the_streaming_path() { +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 mut signer = RSASSA_PSS_SHA256::do_sign_init(&sk, None).unwrap(); - signer.set_signer_salt(salt); - signer.do_sign_update(&msg[..11]); - signer.do_sign_update(&msg[11..]); - let sig = signer.do_sign_final().unwrap(); + let mut signer = + SigningKey::::create_signer(&sk, &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::default().hash_out(msg, &mut digest); + SHA256::hash_out(msg, &mut digest); let expected = rsassa_pss::sign_from_hash_with_salt::< SHA256, 32, @@ -278,34 +283,36 @@ fn set_signer_salt_fixes_the_salt_on_the_streaming_path() { >(&sk, &digest, &salt) .unwrap(); assert_eq!(sig, expected); - RSASSA_PSS_SHA256::verify(&pk, msg, None, &sig).unwrap(); + VerifyingKey::::verify(&pk, msg, None, &sig).unwrap(); - let mut fresh = RSASSA_PSS_SHA256::do_sign_init(&sk, None).unwrap(); - fresh.do_sign_update(msg); - assert_ne!(fresh.do_sign_final().unwrap(), sig, "without set_signer_salt the salt is fresh"); + let mut fresh = + SigningKey::::create_signer(&sk, &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 mut verifier = RSASSA_PSS_SHA256::do_verify_init(&pk, None).unwrap(); - verifier.set_signer_salt([0xffu8; 32]); - verifier.do_verify_update(msg); + let mut verifier = VerifyingKey::::create_verifier(&pk, None).unwrap(); + verifier.do_update(msg); verifier.do_verify_final(&sig).unwrap(); } -/// `sign_randomized` draws the salt from the caller's RNG (the ECDSA/SM2 shape): with a +/// `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_randomized_takes_the_salt_from_the_callers_rng() { +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 = RSASSA_PSS_SHA256::sign_randomized(&sk, msg, &mut FixedRng).unwrap(); + let from_fixed_rng = + SigningKey::::sign(&sk, &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 = RSASSA_PSS_SHA256::sign_randomized(&sk, msg, &mut rng).unwrap(); - let b = RSASSA_PSS_SHA256::sign_randomized(&sk, msg, &mut rng).unwrap(); + let a = SigningKey::::sign(&sk, &mut rng, msg, None).unwrap(); + let b = SigningKey::::sign(&sk, &mut rng, msg, None).unwrap(); assert_ne!(a, b); - RSASSA_PSS_SHA256::verify(&pk, msg, None, &a).unwrap(); - RSASSA_PSS_SHA256::verify(&pk, msg, None, &b).unwrap(); - assert!(RSASSA_PSS_SHA256::verify(&pk, b"other", None, &a).is_err()); + VerifyingKey::::verify(&pk, msg, None, &a).unwrap(); + VerifyingKey::::verify(&pk, msg, None, &b).unwrap(); + assert!(VerifyingKey::::verify(&pk, 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 index 4364e591..7c063796 100644 --- a/crypto/rsa/tests/rsa_3072_pss_shake128_tests.rs +++ b/crypto/rsa/tests/rsa_3072_pss_shake128_tests.rs @@ -4,25 +4,27 @@ //! `rsa_3072_tests.rs` recovered), and all of Wycheproof's real vectors for verification. use bouncycastle_core::errors::SignatureError; -use bouncycastle_core::traits::{SignatureVerifier, Signer}; +use bouncycastle_core::signature_key::{SigningKey, VerifyingKey}; +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::rsa_3072::{ - PK_LEN, RSA3072PrivateKey, RSA3072PublicKey, RSASSA_PSS_SHAKE128, SIG_LEN, SK_LEN, + RSA3072PrivateKey, RSA3072PublicKey, 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_signer_salt`) -- the +/// 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 mut signer = <$ty>::do_sign_init($sk, None).unwrap(); - signer.set_signer_salt($salt); - signer.do_sign_update($msg); - signer.do_sign_final() + let mut signer = + SigningKey::<$ty, 384>::create_signer($sk, &mut DefaultRNG::default(), None).unwrap(); + signer.set_salt($salt); + signer.do_update($msg); + signer.do_final() }}; } @@ -113,12 +115,16 @@ fn pss_shake128_sign_with_fixed_salt_round_trips() { let salt = [0x42u8; 32]; let sig = sign_with_salt!(RSASSA_PSS_SHAKE128, &sk, b"the message to sign", salt) .expect("signing must succeed"); - RSASSA_PSS_SHAKE128::verify(&pk, b"the message to sign", None, &sig).expect("must verify"); + VerifyingKey::::verify(&pk, 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!(RSASSA_PSS_SHAKE128::verify(&pk, b"a different message", None, &sig).is_err()); + assert!( + VerifyingKey::::verify(&pk, b"a different message", None, &sig) + .is_err() + ); } #[test] @@ -127,13 +133,15 @@ fn pss_shake128_sign_with_rng_produces_fresh_salts_that_both_verify() { let pk = RSA3072PublicKey::new(sk.n(), 0x10001).unwrap(); let mut rng = DefaultRNG::default(); - let sig_a = RSASSA_PSS_SHAKE128::sign_randomized(&sk, b"hello", &mut rng) + let sig_a = SigningKey::::sign(&sk, &mut rng, b"hello", None) .expect("signing must succeed"); - let sig_b = RSASSA_PSS_SHAKE128::sign_randomized(&sk, b"hello", &mut rng) + let sig_b = SigningKey::::sign(&sk, &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"); - RSASSA_PSS_SHAKE128::verify(&pk, b"hello", None, &sig_a).expect("sig_a must verify"); - RSASSA_PSS_SHAKE128::verify(&pk, b"hello", None, &sig_b).expect("sig_b must verify"); + VerifyingKey::::verify(&pk, b"hello", None, &sig_a) + .expect("sig_a must verify"); + VerifyingKey::::verify(&pk, b"hello", None, &sig_b) + .expect("sig_b must verify"); } #[test] @@ -166,7 +174,8 @@ fn rsa_pss_3072_shake128_wycheproof_vectors() { continue; }; - let verified = RSASSA_PSS_SHAKE128::verify(&pk, &msg, None, &sig).is_ok(); + let verified = + VerifyingKey::::verify(&pk, &msg, None, &sig).is_ok(); match test["result"].as_str().unwrap() { "valid" => { assert!(verified, "tcId {tc_id}: expected valid, got invalid"); @@ -196,13 +205,8 @@ fn fixed_keypair() -> Result<(RSA3072PublicKey, RSA3072PrivateKey), SignatureErr #[test] fn pss_shake128_trait_conformance_suite() { - TestFrameworkSignature::new(false, false).test_signature::< - RSA3072PublicKey, - RSA3072PrivateKey, - RSASSA_PSS_SHAKE128, - RSASSA_PSS_SHAKE128, - PK_LEN, - SK_LEN, - SIG_LEN, - >(fixed_keypair, false); + TestFrameworkSignature::new(false) + .test_signature::( + fixed_keypair, false, + ); } diff --git a/crypto/rsa/tests/rsa_3072_tests.rs b/crypto/rsa/tests/rsa_3072_tests.rs index 3d5a4ecf..8afc2828 100644 --- a/crypto/rsa/tests/rsa_3072_tests.rs +++ b/crypto/rsa/tests/rsa_3072_tests.rs @@ -11,7 +11,8 @@ //! before being pasted here. use bouncycastle_core::errors::SignatureError; -use bouncycastle_core::traits::{SignatureVerifier, Signer}; +use bouncycastle_core::signature_key::{DeterministicSigningKey, SigningKey, VerifyingKey}; +use bouncycastle_core::traits::SignatureSigner; use bouncycastle_core_test_framework::signature::{ TestFrameworkSignature, TestFrameworkSignatureKeys, }; @@ -26,14 +27,15 @@ use serde_json::Value; use std::fs; use std::path::Path; -/// Signs through the streaming trait path with a fixed salt (`set_signer_salt`) -- the +/// 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 mut signer = <$ty>::do_sign_init($sk, None).unwrap(); - signer.set_signer_salt($salt); - signer.do_sign_update($msg); - signer.do_sign_final() + let mut signer = + SigningKey::<$ty, 384>::create_signer($sk, &mut DefaultRNG::default(), None).unwrap(); + signer.set_salt($salt); + signer.do_update($msg); + signer.do_final() }}; } @@ -131,7 +133,10 @@ fn pkcs1_v1_5_sig_gen_3072_sha256() { 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 = RSASSA_PKCS1_v1_5_SHA256::sign(&sk, &msg, None).unwrap_or_else(|e| { + let sig = DeterministicSigningKey::::sign_deterministic( + &sk, &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"); @@ -143,10 +148,16 @@ fn pkcs1_v1_5_sig_gen_3072_sha256() { fn pkcs1_v1_5_sha384_and_sha512_round_trip() { let sk = genuine_key(); let pk = RSA3072PublicKey::new(sk.n(), 0x10001).unwrap(); - let sig384 = RSASSA_PKCS1_v1_5_SHA384::sign(&sk, b"hello", None).unwrap(); - RSASSA_PKCS1_v1_5_SHA384::verify(&pk, b"hello", None, &sig384).unwrap(); - let sig512 = RSASSA_PKCS1_v1_5_SHA512::sign(&sk, b"hello", None).unwrap(); - RSASSA_PKCS1_v1_5_SHA512::verify(&pk, b"hello", None, &sig512).unwrap(); + let sig384 = DeterministicSigningKey::::sign_deterministic( + &sk, b"hello", None, + ) + .unwrap(); + VerifyingKey::::verify(&pk, b"hello", None, &sig384).unwrap(); + let sig512 = DeterministicSigningKey::::sign_deterministic( + &sk, b"hello", None, + ) + .unwrap(); + VerifyingKey::::verify(&pk, b"hello", None, &sig512).unwrap(); } /// Mutation testing found that fixed-salt PSS/SHA-256 signing, RNG-salted PSS/SHA-384 signing, @@ -164,8 +175,8 @@ fn pss_sha256_fixed_salt_round_trips() { let salt = [0x22u8; 32]; let sig = sign_with_salt!(RSASSA_PSS_SHA256, &sk, b"hello", salt).expect("signing must succeed"); - RSASSA_PSS_SHA256::verify(&pk, b"hello", None, &sig).expect("must verify"); - assert!(RSASSA_PSS_SHA256::verify(&pk, b"goodbye", None, &sig).is_err()); + VerifyingKey::::verify(&pk, b"hello", None, &sig).expect("must verify"); + assert!(VerifyingKey::::verify(&pk, b"goodbye", None, &sig).is_err()); } #[test] @@ -173,13 +184,15 @@ fn pss_sha256_rng_produces_fresh_salts_that_both_verify() { let sk = genuine_key(); let pk = RSA3072PublicKey::new(sk.n(), 0x10001).unwrap(); let mut rng = DefaultRNG::default(); - let sig_a = - RSASSA_PSS_SHA256::sign_randomized(&sk, b"hello", &mut rng).expect("signing must succeed"); - let sig_b = - RSASSA_PSS_SHA256::sign_randomized(&sk, b"hello", &mut rng).expect("signing must succeed"); + let sig_a = SigningKey::::sign(&sk, &mut rng, b"hello", None) + .expect("signing must succeed"); + let sig_b = SigningKey::::sign(&sk, &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"); - RSASSA_PSS_SHA256::verify(&pk, b"hello", None, &sig_a).expect("sig_a must verify"); - RSASSA_PSS_SHA256::verify(&pk, b"hello", None, &sig_b).expect("sig_b must verify"); + VerifyingKey::::verify(&pk, b"hello", None, &sig_a) + .expect("sig_a must verify"); + VerifyingKey::::verify(&pk, b"hello", None, &sig_b) + .expect("sig_b must verify"); } #[test] @@ -189,8 +202,8 @@ fn pss_sha384_fixed_salt_round_trips() { let salt = [0x11u8; 48]; let sig = sign_with_salt!(RSASSA_PSS_SHA384, &sk, b"hello", salt).expect("signing must succeed"); - RSASSA_PSS_SHA384::verify(&pk, b"hello", None, &sig).expect("must verify"); - assert!(RSASSA_PSS_SHA384::verify(&pk, b"goodbye", None, &sig).is_err()); + VerifyingKey::::verify(&pk, b"hello", None, &sig).expect("must verify"); + assert!(VerifyingKey::::verify(&pk, b"goodbye", None, &sig).is_err()); } #[test] @@ -198,13 +211,15 @@ fn pss_sha384_rng_produces_fresh_salts_that_both_verify() { let sk = genuine_key(); let pk = RSA3072PublicKey::new(sk.n(), 0x10001).unwrap(); let mut rng = DefaultRNG::default(); - let sig_a = - RSASSA_PSS_SHA384::sign_randomized(&sk, b"hello", &mut rng).expect("signing must succeed"); - let sig_b = - RSASSA_PSS_SHA384::sign_randomized(&sk, b"hello", &mut rng).expect("signing must succeed"); + let sig_a = SigningKey::::sign(&sk, &mut rng, b"hello", None) + .expect("signing must succeed"); + let sig_b = SigningKey::::sign(&sk, &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"); - RSASSA_PSS_SHA384::verify(&pk, b"hello", None, &sig_a).expect("sig_a must verify"); - RSASSA_PSS_SHA384::verify(&pk, b"hello", None, &sig_b).expect("sig_b must verify"); + VerifyingKey::::verify(&pk, b"hello", None, &sig_a) + .expect("sig_a must verify"); + VerifyingKey::::verify(&pk, b"hello", None, &sig_b) + .expect("sig_b must verify"); } #[test] @@ -214,8 +229,8 @@ fn pss_sha512_fixed_salt_round_trips() { let salt = [0x33u8; 64]; let sig = sign_with_salt!(RSASSA_PSS_SHA512, &sk, b"hello", salt).expect("signing must succeed"); - RSASSA_PSS_SHA512::verify(&pk, b"hello", None, &sig).expect("must verify"); - assert!(RSASSA_PSS_SHA512::verify(&pk, b"goodbye", None, &sig).is_err()); + VerifyingKey::::verify(&pk, b"hello", None, &sig).expect("must verify"); + assert!(VerifyingKey::::verify(&pk, b"goodbye", None, &sig).is_err()); } #[test] @@ -223,13 +238,15 @@ fn pss_sha512_rng_produces_fresh_salts_that_both_verify() { let sk = genuine_key(); let pk = RSA3072PublicKey::new(sk.n(), 0x10001).unwrap(); let mut rng = DefaultRNG::default(); - let sig_a = - RSASSA_PSS_SHA512::sign_randomized(&sk, b"hello", &mut rng).expect("signing must succeed"); - let sig_b = - RSASSA_PSS_SHA512::sign_randomized(&sk, b"hello", &mut rng).expect("signing must succeed"); + let sig_a = SigningKey::::sign(&sk, &mut rng, b"hello", None) + .expect("signing must succeed"); + let sig_b = SigningKey::::sign(&sk, &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"); - RSASSA_PSS_SHA512::verify(&pk, b"hello", None, &sig_a).expect("sig_a must verify"); - RSASSA_PSS_SHA512::verify(&pk, b"hello", None, &sig_b).expect("sig_b must verify"); + VerifyingKey::::verify(&pk, b"hello", None, &sig_a) + .expect("sig_a must verify"); + VerifyingKey::::verify(&pk, b"hello", None, &sig_b) + .expect("sig_b must verify"); } fn run_pkcs1_v1_5_verify_vectors( @@ -291,7 +308,9 @@ fn run_pkcs1_v1_5_verify_vectors( fn rsa_signature_3072_sha256_wycheproof_vectors() { run_pkcs1_v1_5_verify_vectors( "rsa_signature_3072_sha256_test.json", - |pk, msg, sig| RSASSA_PKCS1_v1_5_SHA256::verify(pk, msg, None, sig).is_ok(), + |pk, msg, sig| { + VerifyingKey::::verify(pk, msg, None, sig).is_ok() + }, "SHA-256", 8, 250, @@ -306,7 +325,9 @@ fn rsa_signature_3072_sha256_wycheproof_vectors() { fn rsa_signature_3072_sha384_wycheproof_vectors() { run_pkcs1_v1_5_verify_vectors( "rsa_signature_3072_sha384_test.json", - |pk, msg, sig| RSASSA_PKCS1_v1_5_SHA384::verify(pk, msg, None, sig).is_ok(), + |pk, msg, sig| { + VerifyingKey::::verify(pk, msg, None, sig).is_ok() + }, "SHA-384", 7, 251, @@ -321,7 +342,9 @@ fn rsa_signature_3072_sha384_wycheproof_vectors() { fn rsa_signature_3072_sha512_wycheproof_vectors() { run_pkcs1_v1_5_verify_vectors( "rsa_signature_3072_sha512_test.json", - |pk, msg, sig| RSASSA_PKCS1_v1_5_SHA512::verify(pk, msg, None, sig).is_ok(), + |pk, msg, sig| { + VerifyingKey::::verify(pk, msg, None, sig).is_ok() + }, "SHA-512", 8, 251, @@ -352,7 +375,8 @@ fn rsa_pss_3072_sha256_mgf1_32_wycheproof_vectors() { num_invalid += 1; continue; }; - let verified = RSASSA_PSS_SHA256::verify(&pk, &msg, None, &sig).is_ok(); + let verified = + VerifyingKey::::verify(&pk, &msg, None, &sig).is_ok(); match test["result"].as_str().unwrap() { "valid" => { assert!(verified, "tcId {tc_id}: expected valid"); @@ -382,66 +406,24 @@ fn fixed_keypair() -> Result<(RSA3072PublicKey, RSA3072PrivateKey), SignatureErr /// pass over the shared generic code runs at RSA-2048). #[test] fn pkcs1_v1_5_trait_conformance_suites() { - let framework = TestFrameworkSignature::new(true, false); - framework.test_signature::< - RSA3072PublicKey, - RSA3072PrivateKey, - RSASSA_PKCS1_v1_5_SHA256, - RSASSA_PKCS1_v1_5_SHA256, - PK_LEN, - SK_LEN, - SIG_LEN, - >(fixed_keypair, false); - framework.test_signature::< - RSA3072PublicKey, - RSA3072PrivateKey, - RSASSA_PKCS1_v1_5_SHA384, - RSASSA_PKCS1_v1_5_SHA384, - PK_LEN, - SK_LEN, - SIG_LEN, - >(fixed_keypair, false); - framework.test_signature::< - RSA3072PublicKey, - RSA3072PrivateKey, - RSASSA_PKCS1_v1_5_SHA512, - RSASSA_PKCS1_v1_5_SHA512, - PK_LEN, - SK_LEN, - SIG_LEN, - >(fixed_keypair, false); + let framework = TestFrameworkSignature::new(false); + framework.test_deterministic_signature::(fixed_keypair, false); + framework.test_deterministic_signature::(fixed_keypair, false); + framework.test_deterministic_signature::(fixed_keypair, false); } #[test] fn pss_trait_conformance_suites() { - let framework = TestFrameworkSignature::new(false, false); - framework.test_signature::< - RSA3072PublicKey, - RSA3072PrivateKey, - RSASSA_PSS_SHA256, - RSASSA_PSS_SHA256, - PK_LEN, - SK_LEN, - SIG_LEN, - >(fixed_keypair, false); - framework.test_signature::< - RSA3072PublicKey, - RSA3072PrivateKey, - RSASSA_PSS_SHA384, - RSASSA_PSS_SHA384, - PK_LEN, - SK_LEN, - SIG_LEN, - >(fixed_keypair, false); - framework.test_signature::< - RSA3072PublicKey, - RSA3072PrivateKey, - RSASSA_PSS_SHA512, - RSASSA_PSS_SHA512, - PK_LEN, - SK_LEN, - SIG_LEN, - >(fixed_keypair, false); + let framework = TestFrameworkSignature::new(false); + framework.test_signature::( + fixed_keypair, false, + ); + framework.test_signature::( + fixed_keypair, false, + ); + framework.test_signature::( + fixed_keypair, false, + ); } #[test] diff --git a/crypto/rsa/tests/rsa_4096_pss_shake256_tests.rs b/crypto/rsa/tests/rsa_4096_pss_shake256_tests.rs index b47f913e..e31c0bc9 100644 --- a/crypto/rsa/tests/rsa_4096_pss_shake256_tests.rs +++ b/crypto/rsa/tests/rsa_4096_pss_shake256_tests.rs @@ -3,7 +3,8 @@ //! 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::traits::{SignatureVerifier, Signer}; +use bouncycastle_core::signature_key::{SigningKey, VerifyingKey}; +use bouncycastle_core::traits::SignatureSigner; use bouncycastle_hex::decode as hex_decode; use bouncycastle_rng::DefaultRNG; use bouncycastle_rsa::rsa_4096::{RSA4096PrivateKey, RSA4096PublicKey, RSASSA_PSS_SHAKE256}; @@ -11,14 +12,15 @@ use serde_json::Value; use std::fs; use std::path::Path; -/// Signs through the streaming trait path with a fixed salt (`set_signer_salt`) -- the +/// 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 mut signer = <$ty>::do_sign_init($sk, None).unwrap(); - signer.set_signer_salt($salt); - signer.do_sign_update($msg); - signer.do_sign_final() + let mut signer = + SigningKey::<$ty, 512>::create_signer($sk, &mut DefaultRNG::default(), None).unwrap(); + signer.set_salt($salt); + signer.do_update($msg); + signer.do_final() }}; } @@ -119,12 +121,16 @@ fn pss_shake256_sign_with_fixed_salt_round_trips() { let salt = [0x42u8; 64]; let sig = sign_with_salt!(RSASSA_PSS_SHAKE256, &sk, b"the message to sign", salt) .expect("signing must succeed"); - RSASSA_PSS_SHAKE256::verify(&pk, b"the message to sign", None, &sig).expect("must verify"); + VerifyingKey::::verify(&pk, 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!(RSASSA_PSS_SHAKE256::verify(&pk, b"a different message", None, &sig).is_err()); + assert!( + VerifyingKey::::verify(&pk, b"a different message", None, &sig) + .is_err() + ); } #[test] @@ -133,13 +139,15 @@ fn pss_shake256_sign_with_rng_produces_fresh_salts_that_both_verify() { let pk = RSA4096PublicKey::new(sk.n(), 0x10001).unwrap(); let mut rng = DefaultRNG::default(); - let sig_a = RSASSA_PSS_SHAKE256::sign_randomized(&sk, b"hello", &mut rng) + let sig_a = SigningKey::::sign(&sk, &mut rng, b"hello", None) .expect("signing must succeed"); - let sig_b = RSASSA_PSS_SHAKE256::sign_randomized(&sk, b"hello", &mut rng) + let sig_b = SigningKey::::sign(&sk, &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"); - RSASSA_PSS_SHAKE256::verify(&pk, b"hello", None, &sig_a).expect("sig_a must verify"); - RSASSA_PSS_SHAKE256::verify(&pk, b"hello", None, &sig_b).expect("sig_b must verify"); + VerifyingKey::::verify(&pk, b"hello", None, &sig_a) + .expect("sig_a must verify"); + VerifyingKey::::verify(&pk, b"hello", None, &sig_b) + .expect("sig_b must verify"); } #[test] @@ -172,7 +180,8 @@ fn rsa_pss_4096_shake256_wycheproof_vectors() { continue; }; - let verified = RSASSA_PSS_SHAKE256::verify(&pk, &msg, None, &sig).is_ok(); + let verified = + VerifyingKey::::verify(&pk, &msg, None, &sig).is_ok(); match test["result"].as_str().unwrap() { "valid" => { assert!(verified, "tcId {tc_id}: expected valid, got invalid"); @@ -196,17 +205,22 @@ fn rsa_pss_4096_shake256_wycheproof_vectors() { /// 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 `Signer::sign` and `sign_randomized`. +/// trips through `SigningKey::sign`. #[test] fn pss_shake256_trait_round_trips() { let sk = genuine_key(); let pk = RSA4096PublicKey::new(sk.n(), 0x10001).unwrap(); let msg = b"PSS-SHAKE256 at RSA-4096, both APIs"; - let from_trait = RSASSA_PSS_SHAKE256::sign(&sk, msg, None).unwrap(); - RSASSA_PSS_SHAKE256::verify(&pk, msg, None, &from_trait).unwrap(); - RSASSA_PSS_SHAKE256::verify(&pk, msg, None, &from_trait).unwrap(); + let from_trait = + SigningKey::::sign(&sk, &mut DefaultRNG::default(), msg, None) + .unwrap(); + VerifyingKey::::verify(&pk, msg, None, &from_trait).unwrap(); + VerifyingKey::::verify(&pk, msg, None, &from_trait).unwrap(); let from_free = - RSASSA_PSS_SHAKE256::sign_randomized(&sk, msg, &mut DefaultRNG::default()).unwrap(); - RSASSA_PSS_SHAKE256::verify(&pk, msg, None, &from_free).unwrap(); - assert!(RSASSA_PSS_SHAKE256::verify(&pk, b"other", None, &from_free).is_err()); + SigningKey::::sign(&sk, &mut DefaultRNG::default(), msg, None) + .unwrap(); + VerifyingKey::::verify(&pk, msg, None, &from_free).unwrap(); + assert!( + VerifyingKey::::verify(&pk, 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 index 617d01f1..b3e0eea9 100644 --- a/crypto/rsa/tests/rsa_4096_tests.rs +++ b/crypto/rsa/tests/rsa_4096_tests.rs @@ -12,7 +12,10 @@ //! against all 8 of that group's real signatures before being pasted here. use bouncycastle_core::errors::SignatureError; -use bouncycastle_core::traits::{SignatureVerifier, Signer}; +use bouncycastle_core::signature_key::{ + DeterministicSigningKey, SignatureAlgorithm, SigningKey, VerifyingKey, +}; +use bouncycastle_core::traits::SignatureSigner; use bouncycastle_core_test_framework::signature::{ TestFrameworkSignature, TestFrameworkSignatureKeys, }; @@ -27,14 +30,15 @@ use serde_json::Value; use std::fs; use std::path::Path; -/// Signs through the streaming trait path with a fixed salt (`set_signer_salt`) -- the +/// 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 mut signer = <$ty>::do_sign_init($sk, None).unwrap(); - signer.set_signer_salt($salt); - signer.do_sign_update($msg); - signer.do_sign_final() + let mut signer = + SigningKey::<$ty, 512>::create_signer($sk, &mut DefaultRNG::default(), None).unwrap(); + signer.set_salt($salt); + signer.do_update($msg); + signer.do_final() }}; } @@ -142,7 +146,10 @@ fn pkcs1_v1_5_sig_gen_4096_sha256() { 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 = RSASSA_PKCS1_v1_5_SHA256::sign(&sk, &msg, None).unwrap_or_else(|e| { + let sig = DeterministicSigningKey::::sign_deterministic( + &sk, &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"); @@ -158,10 +165,16 @@ fn pkcs1_v1_5_sig_gen_4096_sha256() { fn pkcs1_v1_5_sha384_and_sha512_round_trip() { let sk = genuine_key(); let pk = RSA4096PublicKey::new(sk.n(), 0x10001).unwrap(); - let sig384 = RSASSA_PKCS1_v1_5_SHA384::sign(&sk, b"hello", None).unwrap(); - RSASSA_PKCS1_v1_5_SHA384::verify(&pk, b"hello", None, &sig384).unwrap(); - let sig512 = RSASSA_PKCS1_v1_5_SHA512::sign(&sk, b"hello", None).unwrap(); - RSASSA_PKCS1_v1_5_SHA512::verify(&pk, b"hello", None, &sig512).unwrap(); + let sig384 = DeterministicSigningKey::::sign_deterministic( + &sk, b"hello", None, + ) + .unwrap(); + VerifyingKey::::verify(&pk, b"hello", None, &sig384).unwrap(); + let sig512 = DeterministicSigningKey::::sign_deterministic( + &sk, b"hello", None, + ) + .unwrap(); + VerifyingKey::::verify(&pk, b"hello", None, &sig512).unwrap(); } fn run_pkcs1_v1_5_verify_vectors( @@ -223,7 +236,9 @@ fn run_pkcs1_v1_5_verify_vectors( fn rsa_signature_4096_sha256_wycheproof_vectors() { run_pkcs1_v1_5_verify_vectors( "rsa_signature_4096_sha256_test.json", - |pk, msg, sig| RSASSA_PKCS1_v1_5_SHA256::verify(pk, msg, None, sig).is_ok(), + |pk, msg, sig| { + VerifyingKey::::verify(pk, msg, None, sig).is_ok() + }, "SHA-256", 7, 250, @@ -234,7 +249,9 @@ fn rsa_signature_4096_sha256_wycheproof_vectors() { fn rsa_signature_4096_sha384_wycheproof_vectors() { run_pkcs1_v1_5_verify_vectors( "rsa_signature_4096_sha384_test.json", - |pk, msg, sig| RSASSA_PKCS1_v1_5_SHA384::verify(pk, msg, None, sig).is_ok(), + |pk, msg, sig| { + VerifyingKey::::verify(pk, msg, None, sig).is_ok() + }, "SHA-384", 7, 251, @@ -245,7 +262,9 @@ fn rsa_signature_4096_sha384_wycheproof_vectors() { fn rsa_signature_4096_sha512_wycheproof_vectors() { run_pkcs1_v1_5_verify_vectors( "rsa_signature_4096_sha512_test.json", - |pk, msg, sig| RSASSA_PKCS1_v1_5_SHA512::verify(pk, msg, None, sig).is_ok(), + |pk, msg, sig| { + VerifyingKey::::verify(pk, msg, None, sig).is_ok() + }, "SHA-512", 7, 251, @@ -304,7 +323,7 @@ fn run_pss_verify_vectors( fn rsa_pss_4096_sha256_mgf1_32_wycheproof_vectors() { run_pss_verify_vectors( "rsa_pss_4096_sha256_mgf1_32_test.json", - |pk, msg, sig| RSASSA_PSS_SHA256::verify(pk, msg, None, sig).is_ok(), + |pk, msg, sig| VerifyingKey::::verify(pk, msg, None, sig).is_ok(), "SHA-256", 32, 63, @@ -316,7 +335,7 @@ fn rsa_pss_4096_sha256_mgf1_32_wycheproof_vectors() { fn rsa_pss_4096_sha384_mgf1_48_wycheproof_vectors() { run_pss_verify_vectors( "rsa_pss_4096_sha384_mgf1_48_test.json", - |pk, msg, sig| RSASSA_PSS_SHA384::verify(pk, msg, None, sig).is_ok(), + |pk, msg, sig| VerifyingKey::::verify(pk, msg, None, sig).is_ok(), "SHA-384", 48, 95, @@ -328,7 +347,7 @@ fn rsa_pss_4096_sha384_mgf1_48_wycheproof_vectors() { fn rsa_pss_4096_sha512_mgf1_64_wycheproof_vectors() { run_pss_verify_vectors( "rsa_pss_4096_sha512_mgf1_64_test.json", - |pk, msg, sig| RSASSA_PSS_SHA512::verify(pk, msg, None, sig).is_ok(), + |pk, msg, sig| VerifyingKey::::verify(pk, msg, None, sig).is_ok(), "SHA-512", 64, 132, @@ -349,8 +368,8 @@ fn pss_sha256_fixed_salt_round_trips() { let salt = [0x22u8; 32]; let sig = sign_with_salt!(RSASSA_PSS_SHA256, &sk, b"hello", salt).expect("signing must succeed"); - RSASSA_PSS_SHA256::verify(&pk, b"hello", None, &sig).expect("must verify"); - assert!(RSASSA_PSS_SHA256::verify(&pk, b"goodbye", None, &sig).is_err()); + VerifyingKey::::verify(&pk, b"hello", None, &sig).expect("must verify"); + assert!(VerifyingKey::::verify(&pk, b"goodbye", None, &sig).is_err()); } #[test] @@ -358,13 +377,15 @@ fn pss_sha256_rng_produces_fresh_salts_that_both_verify() { let sk = genuine_key(); let pk = RSA4096PublicKey::new(sk.n(), 0x10001).unwrap(); let mut rng = DefaultRNG::default(); - let sig_a = - RSASSA_PSS_SHA256::sign_randomized(&sk, b"hello", &mut rng).expect("signing must succeed"); - let sig_b = - RSASSA_PSS_SHA256::sign_randomized(&sk, b"hello", &mut rng).expect("signing must succeed"); + let sig_a = SigningKey::::sign(&sk, &mut rng, b"hello", None) + .expect("signing must succeed"); + let sig_b = SigningKey::::sign(&sk, &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"); - RSASSA_PSS_SHA256::verify(&pk, b"hello", None, &sig_a).expect("sig_a must verify"); - RSASSA_PSS_SHA256::verify(&pk, b"hello", None, &sig_b).expect("sig_b must verify"); + VerifyingKey::::verify(&pk, b"hello", None, &sig_a) + .expect("sig_a must verify"); + VerifyingKey::::verify(&pk, b"hello", None, &sig_b) + .expect("sig_b must verify"); } #[test] @@ -374,8 +395,8 @@ fn pss_sha384_fixed_salt_round_trips() { let salt = [0x11u8; 48]; let sig = sign_with_salt!(RSASSA_PSS_SHA384, &sk, b"hello", salt).expect("signing must succeed"); - RSASSA_PSS_SHA384::verify(&pk, b"hello", None, &sig).expect("must verify"); - assert!(RSASSA_PSS_SHA384::verify(&pk, b"goodbye", None, &sig).is_err()); + VerifyingKey::::verify(&pk, b"hello", None, &sig).expect("must verify"); + assert!(VerifyingKey::::verify(&pk, b"goodbye", None, &sig).is_err()); } #[test] @@ -383,13 +404,15 @@ fn pss_sha384_rng_produces_fresh_salts_that_both_verify() { let sk = genuine_key(); let pk = RSA4096PublicKey::new(sk.n(), 0x10001).unwrap(); let mut rng = DefaultRNG::default(); - let sig_a = - RSASSA_PSS_SHA384::sign_randomized(&sk, b"hello", &mut rng).expect("signing must succeed"); - let sig_b = - RSASSA_PSS_SHA384::sign_randomized(&sk, b"hello", &mut rng).expect("signing must succeed"); + let sig_a = SigningKey::::sign(&sk, &mut rng, b"hello", None) + .expect("signing must succeed"); + let sig_b = SigningKey::::sign(&sk, &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"); - RSASSA_PSS_SHA384::verify(&pk, b"hello", None, &sig_a).expect("sig_a must verify"); - RSASSA_PSS_SHA384::verify(&pk, b"hello", None, &sig_b).expect("sig_b must verify"); + VerifyingKey::::verify(&pk, b"hello", None, &sig_a) + .expect("sig_a must verify"); + VerifyingKey::::verify(&pk, b"hello", None, &sig_b) + .expect("sig_b must verify"); } #[test] @@ -399,8 +422,8 @@ fn pss_sha512_fixed_salt_round_trips() { let salt = [0x33u8; 64]; let sig = sign_with_salt!(RSASSA_PSS_SHA512, &sk, b"hello", salt).expect("signing must succeed"); - RSASSA_PSS_SHA512::verify(&pk, b"hello", None, &sig).expect("must verify"); - assert!(RSASSA_PSS_SHA512::verify(&pk, b"goodbye", None, &sig).is_err()); + VerifyingKey::::verify(&pk, b"hello", None, &sig).expect("must verify"); + assert!(VerifyingKey::::verify(&pk, b"goodbye", None, &sig).is_err()); } #[test] @@ -408,13 +431,15 @@ fn pss_sha512_rng_produces_fresh_salts_that_both_verify() { let sk = genuine_key(); let pk = RSA4096PublicKey::new(sk.n(), 0x10001).unwrap(); let mut rng = DefaultRNG::default(); - let sig_a = - RSASSA_PSS_SHA512::sign_randomized(&sk, b"hello", &mut rng).expect("signing must succeed"); - let sig_b = - RSASSA_PSS_SHA512::sign_randomized(&sk, b"hello", &mut rng).expect("signing must succeed"); + let sig_a = SigningKey::::sign(&sk, &mut rng, b"hello", None) + .expect("signing must succeed"); + let sig_b = SigningKey::::sign(&sk, &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"); - RSASSA_PSS_SHA512::verify(&pk, b"hello", None, &sig_a).expect("sig_a must verify"); - RSASSA_PSS_SHA512::verify(&pk, b"hello", None, &sig_b).expect("sig_b must verify"); + VerifyingKey::::verify(&pk, b"hello", None, &sig_a) + .expect("sig_a must verify"); + VerifyingKey::::verify(&pk, b"hello", None, &sig_b) + .expect("sig_b must verify"); } // ---- bouncycastle_core trait conformance ------------------------------------------------------ @@ -432,24 +457,11 @@ fn fixed_keypair() -> Result<(RSA4096PublicKey, RSA4096PrivateKey), SignatureErr /// RSA-2048 and RSA-3072, and only this size's width constants are new. #[test] fn sha256_trait_conformance_suites() { - TestFrameworkSignature::new(true, false).test_signature::< - RSA4096PublicKey, - RSA4096PrivateKey, - RSASSA_PKCS1_v1_5_SHA256, - RSASSA_PKCS1_v1_5_SHA256, - PK_LEN, - SK_LEN, - SIG_LEN, - >(fixed_keypair, false); - TestFrameworkSignature::new(false, false).test_signature::< - RSA4096PublicKey, - RSA4096PrivateKey, - RSASSA_PSS_SHA256, - RSASSA_PSS_SHA256, - PK_LEN, - SK_LEN, - SIG_LEN, - >(fixed_keypair, false); + TestFrameworkSignature::new(false).test_deterministic_signature::(fixed_keypair, false); + TestFrameworkSignature::new(false) + .test_signature::( + fixed_keypair, false, + ); } #[test] @@ -459,27 +471,45 @@ fn key_trait_boundary_conditions() { } /// Sign one-shot and streamed, verify both, and reject a different message -- what a wrong width -/// constant in this size's aliases would break. -fn trait_round_trip(pk: &RSA4096PublicKey, sk: &RSA4096PrivateKey) +/// constant in this size's aliases would break. PSS, through `SigningKey`. +fn pss_round_trip(pk: &RSA4096PublicKey, sk: &RSA4096PrivateKey) +where + RSA4096PrivateKey: SigningKey, + RSA4096PublicKey: VerifyingKey, +{ + let msg = b"RSA-4096 trait round trip"; + let mut rng = DefaultRNG::default(); + let sig = SigningKey::::sign(sk, &mut rng, msg, None).unwrap(); + VerifyingKey::::verify(pk, msg, None, &sig).unwrap(); + let mut signer = SigningKey::::create_signer(sk, &mut rng, None).unwrap(); + signer.do_update(&msg[..8]); + signer.do_update(&msg[8..]); + VerifyingKey::::verify(pk, msg, None, &signer.do_final().unwrap()).unwrap(); + assert!(VerifyingKey::::verify(pk, b"a different message", None, &sig).is_err()); +} + +/// As [`pss_round_trip`], for PKCS#1 v1.5 through `DeterministicSigningKey`. +fn pkcs1_round_trip(pk: &RSA4096PublicKey, sk: &RSA4096PrivateKey) where - S: Signer - + SignatureVerifier, + RSA4096PrivateKey: DeterministicSigningKey, + RSA4096PublicKey: VerifyingKey, { let msg = b"RSA-4096 trait round trip"; - let sig = S::sign(sk, msg, None).unwrap(); - S::verify(pk, msg, None, &sig).unwrap(); - let mut signer = S::do_sign_init(sk, None).unwrap(); - signer.do_sign_update(&msg[..8]); - signer.do_sign_update(&msg[8..]); - S::verify(pk, msg, None, &signer.do_sign_final().unwrap()).unwrap(); - assert!(S::verify(pk, b"a different message", None, &sig).is_err()); + let sig = DeterministicSigningKey::::sign_deterministic(sk, msg, None).unwrap(); + VerifyingKey::::verify(pk, msg, None, &sig).unwrap(); + let mut signer = + DeterministicSigningKey::::create_signer_deterministic(sk, None).unwrap(); + signer.do_update(&msg[..8]); + signer.do_update(&msg[8..]); + assert_eq!(signer.do_final().unwrap(), sig); + assert!(VerifyingKey::::verify(pk, b"a different message", None, &sig).is_err()); } #[test] fn remaining_pairings_trait_round_trips() { let (pk, sk) = fixed_keypair().unwrap(); - trait_round_trip::(&pk, &sk); - trait_round_trip::(&pk, &sk); - trait_round_trip::(&pk, &sk); - trait_round_trip::(&pk, &sk); + 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 index 2a9ad83f..4445cb5e 100644 --- a/crypto/rsa/tests/rsa_8192_tests.rs +++ b/crypto/rsa/tests/rsa_8192_tests.rs @@ -21,7 +21,10 @@ //! Wycheproof encodes for this hash is checked -- just not every repetition of it. use bouncycastle_core::errors::SignatureError; -use bouncycastle_core::traits::{SignatureVerifier, Signer}; +use bouncycastle_core::signature_key::{ + DeterministicSigningKey, SignatureAlgorithm, SigningKey, VerifyingKey, +}; +use bouncycastle_core::traits::SignatureSigner; use bouncycastle_core_test_framework::signature::{ TestFrameworkSignature, TestFrameworkSignatureKeys, }; @@ -37,14 +40,15 @@ use std::collections::HashSet; use std::fs; use std::path::Path; -/// Signs through the streaming trait path with a fixed salt (`set_signer_salt`) -- the +/// 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 mut signer = <$ty>::do_sign_init($sk, None).unwrap(); - signer.set_signer_salt($salt); - signer.do_sign_update($msg); - signer.do_sign_final() + let mut signer = + SigningKey::<$ty, 1024>::create_signer($sk, &mut DefaultRNG::default(), None).unwrap(); + signer.set_salt($salt); + signer.do_update($msg); + signer.do_final() }}; } @@ -183,13 +187,22 @@ const BC_JAVA_PSS_SHA256_SIG: &str = "71c1b3dd982fd6e1e8be1e20c8a4d42fbe6a8b204a #[test] fn pkcs1_v1_5_matches_bc_java_byte_for_byte() { let sk = genuine_key(); - let sig256 = RSASSA_PKCS1_v1_5_SHA256::sign(&sk, b"hello", None).unwrap(); + let sig256 = DeterministicSigningKey::::sign_deterministic( + &sk, b"hello", None, + ) + .unwrap(); assert_eq!(sig256.to_vec(), hex_decode(BC_JAVA_SHA256_SIG).unwrap()); - let sig384 = RSASSA_PKCS1_v1_5_SHA384::sign(&sk, b"hello", None).unwrap(); + let sig384 = DeterministicSigningKey::::sign_deterministic( + &sk, b"hello", None, + ) + .unwrap(); assert_eq!(sig384.to_vec(), hex_decode(BC_JAVA_SHA384_SIG).unwrap()); - let sig512 = RSASSA_PKCS1_v1_5_SHA512::sign(&sk, b"hello", None).unwrap(); + let sig512 = DeterministicSigningKey::::sign_deterministic( + &sk, b"hello", None, + ) + .unwrap(); assert_eq!(sig512.to_vec(), hex_decode(BC_JAVA_SHA512_SIG).unwrap()); } @@ -200,11 +213,11 @@ fn pkcs1_v1_5_verifies_bc_java_signatures() { 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(); - RSASSA_PKCS1_v1_5_SHA256::verify(&pk, b"hello", None, &sig256) + VerifyingKey::::verify(&pk, b"hello", None, &sig256) .expect("BC Java's SHA-256 sig must verify"); - RSASSA_PKCS1_v1_5_SHA384::verify(&pk, b"hello", None, &sig384) + VerifyingKey::::verify(&pk, b"hello", None, &sig384) .expect("BC Java's SHA-384 sig must verify"); - RSASSA_PKCS1_v1_5_SHA512::verify(&pk, b"hello", None, &sig512) + VerifyingKey::::verify(&pk, b"hello", None, &sig512) .expect("BC Java's SHA-512 sig must verify"); } @@ -213,7 +226,7 @@ fn pss_verifies_bc_java_sha256_signature() { let sk = genuine_key(); let pk = RSA8192PublicKey::new(sk.n(), 0x10001).unwrap(); let sig: [u8; 1024] = hex_decode(BC_JAVA_PSS_SHA256_SIG).unwrap().try_into().unwrap(); - RSASSA_PSS_SHA256::verify(&pk, b"hello", None, &sig) + VerifyingKey::::verify(&pk, b"hello", None, &sig) .expect("BC Java's PSS/SHA-256 signature (default salt length = hLen) must verify"); } @@ -230,8 +243,9 @@ fn pss_sha256_fixed_salt_round_trips() { let salt = [0x33u8; 32]; let sig = sign_with_salt!(RSASSA_PSS_SHA256, &sk, b"hello", salt).expect("signing must succeed"); - RSASSA_PSS_SHA256::verify(&pk, b"hello", None, &sig).expect("must verify"); - assert!(RSASSA_PSS_SHA256::verify(&pk, b"goodbye", None, &sig).is_err()); + VerifyingKey::::verify(&pk, b"hello", None, &sig) + .expect("must verify"); + assert!(VerifyingKey::::verify(&pk, b"goodbye", None, &sig).is_err()); } #[test] @@ -239,13 +253,15 @@ fn pss_sha256_rng_produces_fresh_salts_that_both_verify() { let sk = genuine_key(); let pk = RSA8192PublicKey::new(sk.n(), 0x10001).unwrap(); let mut rng = DefaultRNG::default(); - let sig_a = - RSASSA_PSS_SHA256::sign_randomized(&sk, b"hello", &mut rng).expect("signing must succeed"); - let sig_b = - RSASSA_PSS_SHA256::sign_randomized(&sk, b"hello", &mut rng).expect("signing must succeed"); + let sig_a = SigningKey::::sign(&sk, &mut rng, b"hello", None) + .expect("signing must succeed"); + let sig_b = SigningKey::::sign(&sk, &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"); - RSASSA_PSS_SHA256::verify(&pk, b"hello", None, &sig_a).expect("sig_a must verify"); - RSASSA_PSS_SHA256::verify(&pk, b"hello", None, &sig_b).expect("sig_b must verify"); + VerifyingKey::::verify(&pk, b"hello", None, &sig_a) + .expect("sig_a must verify"); + VerifyingKey::::verify(&pk, b"hello", None, &sig_b) + .expect("sig_b must verify"); } #[test] @@ -255,8 +271,9 @@ fn pss_sha384_fixed_salt_round_trips() { let salt = [0x11u8; 48]; let sig = sign_with_salt!(RSASSA_PSS_SHA384, &sk, b"hello", salt).expect("signing must succeed"); - RSASSA_PSS_SHA384::verify(&pk, b"hello", None, &sig).expect("must verify"); - assert!(RSASSA_PSS_SHA384::verify(&pk, b"goodbye", None, &sig).is_err()); + VerifyingKey::::verify(&pk, b"hello", None, &sig) + .expect("must verify"); + assert!(VerifyingKey::::verify(&pk, b"goodbye", None, &sig).is_err()); } #[test] @@ -264,13 +281,15 @@ fn pss_sha384_rng_produces_fresh_salts_that_both_verify() { let sk = genuine_key(); let pk = RSA8192PublicKey::new(sk.n(), 0x10001).unwrap(); let mut rng = DefaultRNG::default(); - let sig_a = - RSASSA_PSS_SHA384::sign_randomized(&sk, b"hello", &mut rng).expect("signing must succeed"); - let sig_b = - RSASSA_PSS_SHA384::sign_randomized(&sk, b"hello", &mut rng).expect("signing must succeed"); + let sig_a = SigningKey::::sign(&sk, &mut rng, b"hello", None) + .expect("signing must succeed"); + let sig_b = SigningKey::::sign(&sk, &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"); - RSASSA_PSS_SHA384::verify(&pk, b"hello", None, &sig_a).expect("sig_a must verify"); - RSASSA_PSS_SHA384::verify(&pk, b"hello", None, &sig_b).expect("sig_b must verify"); + VerifyingKey::::verify(&pk, b"hello", None, &sig_a) + .expect("sig_a must verify"); + VerifyingKey::::verify(&pk, b"hello", None, &sig_b) + .expect("sig_b must verify"); } #[test] @@ -280,8 +299,9 @@ fn pss_sha512_fixed_salt_round_trips() { let salt = [0x22u8; 64]; let sig = sign_with_salt!(RSASSA_PSS_SHA512, &sk, b"hello", salt).expect("signing must succeed"); - RSASSA_PSS_SHA512::verify(&pk, b"hello", None, &sig).expect("must verify"); - assert!(RSASSA_PSS_SHA512::verify(&pk, b"goodbye", None, &sig).is_err()); + VerifyingKey::::verify(&pk, b"hello", None, &sig) + .expect("must verify"); + assert!(VerifyingKey::::verify(&pk, b"goodbye", None, &sig).is_err()); } #[test] @@ -289,13 +309,15 @@ fn pss_sha512_rng_produces_fresh_salts_that_both_verify() { let sk = genuine_key(); let pk = RSA8192PublicKey::new(sk.n(), 0x10001).unwrap(); let mut rng = DefaultRNG::default(); - let sig_a = - RSASSA_PSS_SHA512::sign_randomized(&sk, b"hello", &mut rng).expect("signing must succeed"); - let sig_b = - RSASSA_PSS_SHA512::sign_randomized(&sk, b"hello", &mut rng).expect("signing must succeed"); + let sig_a = SigningKey::::sign(&sk, &mut rng, b"hello", None) + .expect("signing must succeed"); + let sig_b = SigningKey::::sign(&sk, &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"); - RSASSA_PSS_SHA512::verify(&pk, b"hello", None, &sig_a).expect("sig_a must verify"); - RSASSA_PSS_SHA512::verify(&pk, b"hello", None, &sig_b).expect("sig_b must verify"); + VerifyingKey::::verify(&pk, b"hello", None, &sig_a) + .expect("sig_a must verify"); + VerifyingKey::::verify(&pk, b"hello", None, &sig_b) + .expect("sig_b must verify"); } /// Every distinct `(result, flags)` combination in `filename`'s (single) test group, in file @@ -361,7 +383,9 @@ fn run_sampled_pkcs1_v1_5_verify_vectors( fn rsa_signature_8192_sha256_wycheproof_vectors_sampled() { run_sampled_pkcs1_v1_5_verify_vectors( "rsa_signature_8192_sha256_test.json", - |pk, msg, sig| RSASSA_PKCS1_v1_5_SHA256::verify(pk, msg, None, sig).is_ok(), + |pk, msg, sig| { + VerifyingKey::::verify(pk, msg, None, sig).is_ok() + }, "SHA-256", ); } @@ -370,7 +394,9 @@ fn rsa_signature_8192_sha256_wycheproof_vectors_sampled() { fn rsa_signature_8192_sha384_wycheproof_vectors_sampled() { run_sampled_pkcs1_v1_5_verify_vectors( "rsa_signature_8192_sha384_test.json", - |pk, msg, sig| RSASSA_PKCS1_v1_5_SHA384::verify(pk, msg, None, sig).is_ok(), + |pk, msg, sig| { + VerifyingKey::::verify(pk, msg, None, sig).is_ok() + }, "SHA-384", ); } @@ -379,7 +405,9 @@ fn rsa_signature_8192_sha384_wycheproof_vectors_sampled() { fn rsa_signature_8192_sha512_wycheproof_vectors_sampled() { run_sampled_pkcs1_v1_5_verify_vectors( "rsa_signature_8192_sha512_test.json", - |pk, msg, sig| RSASSA_PKCS1_v1_5_SHA512::verify(pk, msg, None, sig).is_ok(), + |pk, msg, sig| { + VerifyingKey::::verify(pk, msg, None, sig).is_ok() + }, "SHA-512", ); } @@ -397,15 +425,7 @@ fn fixed_keypair() -> Result<(RSA8192PublicKey, RSA8192PrivateKey), SignatureErr /// slower still in a debug build). #[test] fn pkcs1_v1_5_sha256_trait_conformance_suite() { - TestFrameworkSignature::new(true, false).test_signature::< - RSA8192PublicKey, - RSA8192PrivateKey, - RSASSA_PKCS1_v1_5_SHA256, - RSASSA_PKCS1_v1_5_SHA256, - PK_LEN, - SK_LEN, - SIG_LEN, - >(fixed_keypair, false); + TestFrameworkSignature::new(false).test_deterministic_signature::(fixed_keypair, false); } #[test] @@ -414,39 +434,62 @@ fn key_trait_boundary_conditions() { .test_keys::(fixed_keypair); } -fn trait_round_trip(pk: &RSA8192PublicKey, sk: &RSA8192PrivateKey) +/// 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: &RSA8192PublicKey, sk: &RSA8192PrivateKey) +where + RSA8192PrivateKey: SigningKey, + RSA8192PublicKey: VerifyingKey, +{ + let msg = b"RSA-8192 trait round trip"; + let mut rng = DefaultRNG::default(); + let sig = SigningKey::::sign(sk, &mut rng, msg, None).unwrap(); + VerifyingKey::::verify(pk, msg, None, &sig).unwrap(); + let mut signer = SigningKey::::create_signer(sk, &mut rng, None).unwrap(); + signer.do_update(&msg[..8]); + signer.do_update(&msg[8..]); + VerifyingKey::::verify(pk, msg, None, &signer.do_final().unwrap()).unwrap(); + assert!(VerifyingKey::::verify(pk, b"a different message", None, &sig).is_err()); +} + +/// As [`pss_round_trip`], for PKCS#1 v1.5 through `DeterministicSigningKey`. +fn pkcs1_round_trip(pk: &RSA8192PublicKey, sk: &RSA8192PrivateKey) where - S: Signer - + SignatureVerifier, + RSA8192PrivateKey: DeterministicSigningKey, + RSA8192PublicKey: VerifyingKey, { let msg = b"RSA-8192 trait round trip"; - let sig = S::sign(sk, msg, None).unwrap(); - S::verify(pk, msg, None, &sig).unwrap(); - let mut signer = S::do_sign_init(sk, None).unwrap(); - signer.do_sign_update(&msg[..8]); - signer.do_sign_update(&msg[8..]); - S::verify(pk, msg, None, &signer.do_sign_final().unwrap()).unwrap(); - assert!(S::verify(pk, b"a different message", None, &sig).is_err()); + let sig = DeterministicSigningKey::::sign_deterministic(sk, msg, None).unwrap(); + VerifyingKey::::verify(pk, msg, None, &sig).unwrap(); + let mut signer = + DeterministicSigningKey::::create_signer_deterministic(sk, None).unwrap(); + signer.do_update(&msg[..8]); + signer.do_update(&msg[8..]); + assert_eq!(signer.do_final().unwrap(), sig); + assert!(VerifyingKey::::verify(pk, b"a different message", None, &sig).is_err()); } #[test] fn remaining_pairings_trait_round_trips() { let (pk, sk) = fixed_keypair().unwrap(); - trait_round_trip::(&pk, &sk); - trait_round_trip::(&pk, &sk); - trait_round_trip::(&pk, &sk); - trait_round_trip::(&pk, &sk); - trait_round_trip::(&pk, &sk); + 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 `Signer`/`SignatureVerifier`. +/// tests above, through the key role traits. #[test] fn trait_matches_bc_java() { let (pk, sk) = fixed_keypair().unwrap(); - let sig = RSASSA_PKCS1_v1_5_SHA256::sign(&sk, b"hello", None).unwrap(); + let sig = DeterministicSigningKey::::sign_deterministic( + &sk, 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(); - RSASSA_PSS_SHA256::verify(&pk, b"hello", None, &pss).unwrap(); + VerifyingKey::::verify(&pk, b"hello", None, &pss).unwrap(); } diff --git a/crypto/rsa/tests/rsasve_tests.rs b/crypto/rsa/tests/rsasve_tests.rs index 3dd5461b..c2cc0f3b 100644 --- a/crypto/rsa/tests/rsasve_tests.rs +++ b/crypto/rsa/tests/rsasve_tests.rs @@ -25,9 +25,10 @@ use bouncycastle_core::errors::{KEMError, RNGError}; use bouncycastle_core::key_material::{KeyMaterialTrait, KeyType}; use bouncycastle_core::security_strength::SecurityStrength; use bouncycastle_core::traits::{KEMDecapsulator, KEMEncapsulator, KEMPrivateKey, KEMPublicKey}; -use bouncycastle_core_test_framework::FixedSeedRNG; 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; @@ -75,7 +76,10 @@ fn limbs(hex: &str) -> [u64; L] { } /// An `RNG` whose stream is `bytes` repeated, reporting `strength`. -fn rng_emitting(bytes: [u8; N], strength: SecurityStrength) -> FixedSeedRNG { +fn rng_emitting( + bytes: [u8; N], + strength: SecurityStrength, +) -> FixedSeedRNG<[u8; N]> { let mut rng = FixedSeedRNG::new(bytes); rng.set_security_strength(strength); rng @@ -257,8 +261,8 @@ macro_rules! rsasve_suite { 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 mut rng = - FixedSeedRNG::<{ ATTEMPTS * CT_LEN }>::new(stream.try_into().unwrap()); + let seed: [u8; ATTEMPTS * CT_LEN] = stream.try_into().unwrap(); + let mut rng = FixedSeedRNG::new(seed); let (ss, _) = RSASVE::encaps_rng(&pk, &mut rng).unwrap(); assert_eq!(ss.ref_to_bytes(), &[0x5Au8; CT_LEN][..]); } @@ -562,21 +566,21 @@ acvp_rsadp!(acvp_rsadp_crt_3072, rsa_3072, 3072, 48, 24); acvp_rsadp!(acvp_rsadp_crt_4096, rsa_4096, 4096, 64, 32); /// `RSASVE::keygen`'s pairs are usable KEM keys (a genuine generation, at the smallest size -/// only: key generation is the slow part), and `keygen_from_rng` enforces the RNG strength. +/// 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().unwrap(); + let (pk, sk) = RSASVE::keygen(&mut DefaultRNG::default()).unwrap(); assert_eq!(pk.e(), 65537); assert_eq!(pk.n(), sk.n()); let (ss, ct) = RSASVE::encaps(&pk).unwrap(); assert_eq!(RSASVE::decaps(&sk, &ct).unwrap(), ss); // A stuck RNG exhausts FIPS 186-5 A.1.3's candidate limit (see `keygen_tests.rs`'s - // `keygen_from_rng_gives_up_on_a_stuck_rng`), and the KEM keygen passes that error through + // `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_from_rng(&mut stuck) { + match RSASVE::keygen(&mut stuck) { Err(KEMError::GenericError(msg)) => assert!(msg.contains("candidate limit"), "{msg}"), other => panic!("expected GenericError, got {other:?}"), } @@ -584,7 +588,7 @@ fn keygen_produces_working_kem_keys() { let mut weak = FixedSeedRNG::new([0x5Au8; 64]); weak.set_security_strength(SecurityStrength::None); assert!(matches!( - RSASVE::keygen_from_rng(&mut weak), + RSASVE::keygen(&mut weak), Err(KEMError::RNGError(RNGError::SecurityStrengthInsufficientForAlgorithm)) )); } @@ -597,7 +601,7 @@ macro_rules! kem_keygen_round_trip { $(#[$ignore])? fn $name() { use bouncycastle_rsa::$size::RSASVE; - let (pk, sk) = RSASVE::keygen().unwrap(); + let (pk, sk) = RSASVE::keygen(&mut DefaultRNG::default()).unwrap(); assert_eq!(pk.e(), 65537); assert_eq!(pk.n(), sk.n()); let (ss, ct) = RSASVE::encaps(&pk).unwrap(); 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/mem_usage_benches/src/bench_rsa_mem_usage.rs b/mem_usage_benches/src/bench_rsa_mem_usage.rs index 17c1d11c..33dc730b 100644 --- a/mem_usage_benches/src/bench_rsa_mem_usage.rs +++ b/mem_usage_benches/src/bench_rsa_mem_usage.rs @@ -31,10 +31,12 @@ #![allow(unused_imports)] use bouncycastle::core::key_material::KeyMaterialTrait; +use bouncycastle::core::signature_key::{DeterministicSigningKey, SigningKey, VerifyingKey}; use bouncycastle::core::traits::{ KEMDecapsulator, KEMEncapsulator, KEMPrivateKey, KEMPublicKey, SignaturePrivateKey, - SignaturePublicKey, SignatureVerifier, Signer, + SignaturePublicKey, }; +use bouncycastle::rng::DefaultRNG; use bouncycastle::rsa::{rsa_1024, rsa_1536, rsa_2048, rsa_3072, rsa_4096, rsa_8192}; const MSG: &[u8] = b"peak stack usage of RSA sign/verify, held constant across every modulus size"; @@ -150,7 +152,9 @@ fn bench_1024_verify() { ); let msg = bouncycastle::hex::decode("0000000000000000000000000000000000000000").unwrap(); - if rsa_1024::RSASSA_PKCS1_v1_5_SHA256::verify(&pk, &msg, None, &sig).is_ok() { + if VerifyingKey::::verify(&pk, &msg, None, &sig) + .is_ok() + { eprintln!("Verification succeeded!"); } else { panic!("Verification failed! -- figure that out"); @@ -196,7 +200,7 @@ fn genuine_2048_key() -> rsa_2048::RSA2048PrivateKey { /// the modulus width. fn bench_2048_keygen() { eprintln!("RSA-2048/Keygen"); - let (pk, sk) = rsa_2048::keygen().unwrap(); + let (pk, sk) = rsa_2048::keygen(&mut DefaultRNG::default()).unwrap(); println!("{:x?}", pk.encode()); println!("{}", sk.encode().len()); } @@ -204,7 +208,11 @@ fn bench_2048_keygen() { fn bench_2048_sign() { eprintln!("RSA-2048/Sign"); let sk = genuine_2048_key(); - let sig = rsa_2048::RSASSA_PKCS1_v1_5_SHA256::sign(&sk, MSG, None).unwrap(); + let sig = + DeterministicSigningKey::::sign_deterministic( + &sk, MSG, None, + ) + .unwrap(); println!("{:x?}", sig); } @@ -212,9 +220,14 @@ fn bench_2048_verify() { eprintln!("RSA-2048/Verify"); let sk = genuine_2048_key(); let pk = rsa_2048::RSA2048PublicKey::new(sk.n(), 0x10001).unwrap(); - let sig = rsa_2048::RSASSA_PKCS1_v1_5_SHA256::sign(&sk, MSG, None).unwrap(); + let sig = + DeterministicSigningKey::::sign_deterministic( + &sk, MSG, None, + ) + .unwrap(); - if rsa_2048::RSASSA_PKCS1_v1_5_SHA256::verify(&pk, MSG, None, &sig).is_ok() { + if VerifyingKey::::verify(&pk, MSG, None, &sig).is_ok() + { eprintln!("Verification succeeded!"); } else { panic!("Verification failed! -- figure that out"); @@ -318,7 +331,11 @@ fn genuine_8192_key() -> rsa_8192::RSA8192PrivateKey { fn bench_8192_sign() { eprintln!("RSA-8192/Sign"); let sk = genuine_8192_key(); - let sig = rsa_8192::RSASSA_PKCS1_v1_5_SHA256::sign(&sk, MSG, None).unwrap(); + let sig = + DeterministicSigningKey::::sign_deterministic( + &sk, MSG, None, + ) + .unwrap(); println!("{:x?}", sig); } @@ -326,9 +343,15 @@ fn bench_8192_verify() { eprintln!("RSA-8192/Verify"); let sk = genuine_8192_key(); let pk = rsa_8192::RSA8192PublicKey::new(sk.n(), 0x10001).unwrap(); - let sig = rsa_8192::RSASSA_PKCS1_v1_5_SHA256::sign(&sk, MSG, None).unwrap(); + let sig = + DeterministicSigningKey::::sign_deterministic( + &sk, MSG, None, + ) + .unwrap(); - if rsa_8192::RSASSA_PKCS1_v1_5_SHA256::verify(&pk, MSG, None, &sig).is_ok() { + if VerifyingKey::::verify(&pk, MSG, None, &sig) + .is_ok() + { eprintln!("Verification succeeded!"); } else { panic!("Verification failed! -- figure that out"); From 4ea06c82f42915a57574f6420a2c3981390c6ccd Mon Sep 17 00:00:00 2001 From: David Hook Date: Tue, 3 Nov 2026 13:35:49 +1100 Subject: [PATCH 25/55] rsa-sig: the merge-time adaptations to feature/key-rework-memory, carried over the rebase onto its release-based history This branch took feature/key-rework-memory by merge, and the merge commits carried the adaptations to what arrived. The rebase onto the branch's new history (key-rework-memory rebased onto release/0.1.3alpha, which carries feature/key-rework as one squash commit) dropped those merges; this commit restores the affected files to the branch's pre-rebase tip, so the tree is identical to it. Assisted-by: Claude:claude-mythos-5-1 --- cli/src/main.rs | 108 ------------------------------------------------ 1 file changed, 108 deletions(-) diff --git a/cli/src/main.rs b/cli/src/main.rs index 85b9bdcd..f33dc22b 100644 --- a/cli/src/main.rs +++ b/cli/src/main.rs @@ -2944,102 +2944,6 @@ 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, - }, - /// 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 { @@ -3887,18 +3791,6 @@ fn run() { Some(Subcommands::RSASVE_8192 { action, skfile, pkfile, ctfile, x }) => { rsasve_cmd::rsasve_8192_cmd(action, skfile, pkfile, ctfile, *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_1024 { scheme, hash, pkfile, sigfile }) => { rsa_cmd::rsa_1024_cmd(scheme, hash, pkfile, sigfile); } From aa8ad7f1f462c73458a08adf05d2d64cc9de2cdd Mon Sep 17 00:00:00 2001 From: David Hook Date: Thu, 5 Nov 2026 08:37:14 +1100 Subject: [PATCH 26/55] rsa-sig: the merge-time adaptations to release/0.1.3alpha, carried over the rebase onto feature/ecdsa's release/0.1.4alpha history This branch took feature/ecdsa (which carried release/0.1.3alpha 029a17b0, the squash merge of PR #190) by merge, and that merge commit carried the adaptations to what arrived. The rebase onto feature/ecdsa as replayed onto release/0.1.4alpha dropped the merge; this commit restores the affected files to the branch's pre-rebase tip, so the tree is identical to it apart from the 0.1.4 line's own version bump and notes file. Assisted-by: Claude:claude-fable-5-1 --- cli/src/rsa_cmd.rs | 43 +++++++++++++++++++++----------------- cli/src/rsasve_cmd.rs | 16 +++++++------- cli/tests/rsa_cli_tests.rs | 22 ++++++++++--------- 3 files changed, 45 insertions(+), 36 deletions(-) diff --git a/cli/src/rsa_cmd.rs b/cli/src/rsa_cmd.rs index ba39e1ef..f4dfb981 100644 --- a/cli/src/rsa_cmd.rs +++ b/cli/src/rsa_cmd.rs @@ -32,8 +32,12 @@ //! through [`do_verify`], which needs only a `VerifyingKey` -- exactly the trait those sizes' //! types implement. -use crate::helpers::{read_from_file, write_bytes_or_hex, write_bytes_or_hex_to_file}; +use crate::helpers::{ + println_stdout, read_input_file, read_secret_file, stream_stdin, write_bytes_or_hex, + write_bytes_or_hex_to_file, +}; use bouncycastle::core::errors::SignatureError; +use bouncycastle::core::key_material::KeyMaterialTrait; use bouncycastle::core::signature_key::{ DeterministicSigningKey, SignatureAlgorithm, SigningKey, VerifyingKey, }; @@ -43,8 +47,6 @@ use bouncycastle::core::traits::{ use bouncycastle::rng::HashDRBG_SHA512; use bouncycastle::rsa::{rsa_1024, rsa_1536, rsa_2048, rsa_3072, rsa_4096, rsa_8192}; use clap::ValueEnum; -use std::io; -use std::io::Read; use std::process::exit; #[derive(ValueEnum, Clone, Debug, PartialEq, Eq)] @@ -80,9 +82,11 @@ pub(crate) enum RSAHash { 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_from_file(f), + Some(f) => read_input_file(f), None => { eprintln!("Error: no {flag_name} provided."); exit(-1); @@ -90,15 +94,14 @@ fn require_file(file: &Option, flag_name: &str) -> Vec { } } -/// The message is read raw, never hex-decoded: unlike a key or signature file, arbitrary message -/// bytes that happen to look like hex must still be signed/verified byte-for-byte. Streams stdin -/// through `update` in ~1 KB chunks (the same loop as `ecdsa_cmd.rs`). -fn stream_stdin_into(mut update: impl FnMut(&[u8])) { - let mut buf = [0u8; 1024]; - let mut bytes_read = io::stdin().read(&mut buf).expect("Failed to read from stdin"); - while bytes_read > 0 { - update(&buf[..bytes_read]); - bytes_read = io::stdin().read(&mut buf).expect("Failed to read from stdin"); +/// `--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); + } } } @@ -163,10 +166,10 @@ fn do_verify< // `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_into(|chunk| verifier.do_update(chunk)); + stream_stdin(|chunk| verifier.do_update(chunk)); if verifier.do_verify_final(&sig).is_ok() { - println!("Signature is valid."); + println_stdout("Signature is valid."); } else { eprintln!("Signature is invalid."); exit(-1); @@ -226,14 +229,15 @@ fn rsa_pss_cmd< rsa_keygen_cmd::(keygen, pkfile, output_hex, alg_name) } RSAAction::Sign => { - let sk = parse_sk::(&require_file(skfile, "skfile"), alg_name); + let sk = + parse_sk::(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_into(|chunk| signer.do_update(chunk)); + stream_stdin(|chunk| signer.do_update(chunk)); let sig = signer.do_final().unwrap_or_else(|_| { eprintln!("Error: signing failed."); exit(-1); @@ -268,11 +272,12 @@ fn rsa_pkcs1_cmd< rsa_keygen_cmd::(keygen, pkfile, output_hex, alg_name) } RSAAction::Sign => { - let sk = parse_sk::(&require_file(skfile, "skfile"), alg_name); + let sk = + parse_sk::(require_secret(skfile, "skfile").ref_to_bytes(), alg_name); let mut signer = DeterministicSigningKey::::create_signer_deterministic(&sk, None) .unwrap(); - stream_stdin_into(|chunk| signer.do_update(chunk)); + stream_stdin(|chunk| signer.do_update(chunk)); let sig = signer.do_final().unwrap_or_else(|_| { eprintln!("Error: signing failed."); exit(-1); diff --git a/cli/src/rsasve_cmd.rs b/cli/src/rsasve_cmd.rs index a9421dfc..51743d9c 100644 --- a/cli/src/rsasve_cmd.rs +++ b/cli/src/rsasve_cmd.rs @@ -19,7 +19,8 @@ //! a KDF (e.g. `hkdf`) before it can be used as a key. use crate::helpers::{ - read_from_file, read_from_file_or_stdin, write_bytes_or_hex, write_bytes_or_hex_to_file, + println_stdout, read_input_file_or_stdin, read_secret_file, write_bytes_or_hex, + write_bytes_or_hex_to_file, }; use bouncycastle::core::errors::KEMError; use bouncycastle::core::key_material::KeyMaterialTrait; @@ -45,9 +46,10 @@ pub(crate) enum RSASVEAction { Decaps, } -fn require_file(file: &Option, flag_name: &str) -> Vec { +/// `--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_from_file(f), + Some(f) => read_secret_file(f), None => { eprintln!("Error: no {flag_name} provided."); exit(-1); @@ -90,7 +92,7 @@ fn rsasve_cmd< write_bytes_or_hex(&sk.encode(), output_hex); } RSASVEAction::Encaps => { - let pk = PK::from_bytes(&read_from_file_or_stdin(pkfile)).unwrap_or_else(|e| { + 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:?}" @@ -108,13 +110,13 @@ fn rsasve_cmd< } None => { write_bytes_or_hex(&ct, true); - println!(); + println_stdout(""); write_bytes_or_hex(ss.ref_to_bytes(), true); } } } RSASVEAction::Decaps => { - let sk = SK::from_bytes(&require_file(skfile, "skfile")).unwrap_or_else(|e| { + 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:?}" @@ -122,7 +124,7 @@ fn rsasve_cmd< exit(-1); }); // `decaps` reports a wrong-length ciphertext itself (as `LengthError`). - let ss = K::decaps(&sk, &read_from_file_or_stdin(ctfile)).unwrap_or_else(|e| { + let ss = K::decaps(&sk, &read_input_file_or_stdin(ctfile)).unwrap_or_else(|e| { eprintln!("Error: {alg_name} decapsulation failed: {e:?}"); exit(-1); }); diff --git a/cli/tests/rsa_cli_tests.rs b/cli/tests/rsa_cli_tests.rs index 115728b8..1e0bd8cf 100644 --- a/cli/tests/rsa_cli_tests.rs +++ b/cli/tests/rsa_cli_tests.rs @@ -167,14 +167,14 @@ fn pk_2048() -> RSA2048PublicKey { RSA2048PublicKey::from_bytes(&unhex(PK_2048_HEX)).expect("the documented key decodes") } -/// The CLI accepts key and signature files as hex (as written here) or binary. +/// 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", SK_2048_HEX.as_bytes()); + 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", PK_2048_HEX.as_bytes()); + let pkfile = temp_file("pk", &unhex(PK_2048_HEX)); let sigfile = temp_file("sig", sig); run( &[ @@ -189,8 +189,8 @@ fn rsa_2048_verify(scheme: &str, hash: &str, msg: &[u8], sig: &[u8]) -> Output { /// 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", PK_1024_HEX.as_bytes()); - let sigfile = temp_file("sig1024", SIG_1024_HEX.as_bytes()); + 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, @@ -222,7 +222,7 @@ fn rsa_2048_pkcs1v15_signature_matches_the_library_and_verifies() { assert!(String::from_utf8_lossy(&out.stdout).contains("Signature is valid.")); // `-x` writes the same signature as hex. - let skfile = temp_file("sk", SK_2048_HEX.as_bytes()); + let skfile = temp_file("sk", &unhex(SK_2048_HEX)); let hex = run_ok( &[ "rsa-2048", "sign", "--scheme", "pkcs1v15", "--hash", "sha256", "--skfile", &skfile, @@ -300,8 +300,8 @@ fn rsa_2048_rejects_a_wrong_length_key_file() { /// 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", PK_1024_HEX.as_bytes()); - let sigfile = temp_file("sig1024", SIG_1024_HEX.as_bytes()); + 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", @@ -311,7 +311,7 @@ fn unsupported_pairings_are_refused() { ); assert!(err.contains("not supported"), "stderr: {err}"); - let skfile = temp_file("sk", SK_2048_HEX.as_bytes()); + let skfile = temp_file("sk", &unhex(SK_2048_HEX)); let err = run_err( &["rsa-2048", "sign", "--scheme", "pss", "--hash", "shake256", "--skfile", &skfile], b"msg", @@ -339,7 +339,9 @@ fn rsa_2048_keygen_then_sign_and_verify() { let pk = RSA2048PublicKey::from_bytes(&unhex(pk_hex.trim())).unwrap(); assert_eq!(pk.e(), 65537); - let skfile = temp_file("gensk", sk_hex.trim().as_bytes()); + // 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], From 57c5c093020c53ae08a26011664c742805648442 Mon Sep 17 00:00:00 2001 From: David Hook Date: Fri, 6 Nov 2026 13:41:56 +1100 Subject: [PATCH 27/55] rsa: the private-key paths scrub what they derive from the primes An audit against QUALITY_AND_STYLE's rule on secret-holding locals. The key material itself was already in `Secret` (the CRT quintuple in the key, `p`, `q`, `d` and the quintuple in key generation, `Z` and `z` in RSASVE); what the rule found was the plain locals around it. `crt_exp` left every intermediate of the CRT on the stack: the two half-signatures (either one factors `n`, through `gcd(s - s1, n)`), `m mod p`, `m mod q`, `h` and the recombination temporaries, plus two `MontgomeryContext`s each holding a prime. The nine are zeroized before `s` is returned, and the contexts are built inside `Secret`: `MontgomeryContext` gains `Copy` and a `ZeroizablePrimitive` impl for that. `mod_pow` left its second ladder register and the per-bit products; both are now declared before the ladder and zeroized with `r0` after it, and `from_montgomery` and `mul_mod` zeroize their own temporaries. The products inside `mont_mul` and `mont_square` are the callee intermediates the rule does not reach, and are left. `RsaPrivateKey::from_bytes_raw` decoded through five byte-array copies and five limb arrays; the byte arrays are now borrowed from the caller's buffer and the limb arrays zeroized once the key holds them. In key generation, `is_probable_prime` holds `w - 1`, `m`, the context over `w` and the Miller-Rabin `z` in `Secret` (the function has several exits), `primes_too_close` zeroizes the differences it takes, and `keygen_from_rng`'s two blocks zeroize `g`, `(q-1)/g`, `q mod p` and `p - 2` and hold the context over `p` in `Secret`. `primes_too_close` gains the unit test its reject path and boundary need, which no key generation reaches (two random primes land within `2^(nlen/2 - 100)` with probability about `2^-100`): the private known-answer exception, with the cases either side of `2^28` at `N = 2` and in both argument orders. No behavioural change. cargo test -p bouncycastle-rsa 245 passed, 4 ignored; clippy locations identical. Mutants (apollo, `--in-diff`): 47 tested, 36 caught, 11 unviable, 0 missed. Caught: keygen 18 (the `primes_too_close` restructure and its new tests among them), keys 10, modexp 6, rsa_core 2; the unviable ones are whole-function replacements of types without `Default`. A removed `zeroize` call is not a mutant cargo mutants generates. Assisted-by: Claude:claude-mythos-5-1 --- crypto/rsa/src/keygen.rs | 96 ++++++++++++++++++++++++++++---------- crypto/rsa/src/keys.rs | 33 ++++++++----- crypto/rsa/src/modexp.rs | 40 +++++++++++++--- crypto/rsa/src/rsa_core.rs | 36 ++++++++++---- 4 files changed, 152 insertions(+), 53 deletions(-) diff --git a/crypto/rsa/src/keygen.rs b/crypto/rsa/src/keygen.rs index 20cd5aa1..7e6c4057 100644 --- a/crypto/rsa/src/keygen.rs +++ b/crypto/rsa/src/keygen.rs @@ -31,7 +31,7 @@ use bouncycastle_core::security_strength::SecurityStrength; use bouncycastle_core::traits::RNG; use bouncycastle_ec::montgomery; use bouncycastle_ec::nat; -use bouncycastle_utils::secret::Secret; +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`. @@ -361,13 +361,17 @@ pub fn is_probable_prime( return Ok(false); } - // Steps 1-2: w - 1 = 2^a * m with m odd. - let w_minus_1 = sub_u64(w, 1); + // 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 m = shr(&w_minus_1, a); + 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 ctx = MontgomeryContext::new(w).expect("w is odd and nonzero"); + 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 @@ -393,20 +397,21 @@ pub fn is_probable_prime( )); } // Step 4.3. - let mut z = mod_pow::(&b, &m, &ctx); + let mut z = Secret::<[u64; N]>::new(); + *z = mod_pow::(&b, &m, &ctx); // Step 4.4. - if z == one || z == w_minus_1 { + 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 { + *z = mul_mod::(&z, &z, &ctx); + if *z == *w_minus_1 { witness = false; break; } - if z == one { + if *z == one { break; } } @@ -472,18 +477,22 @@ fn random_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 (d1, borrow) = nat::sub(q, p); - let (d2, _) = nat::sub(p, q); - let diff = if borrow == 1 { d2 } else { d1 }; + 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 high = shr(&diff, threshold_bit); - if is_zero(&high) { - return true; // |p - q| < 2^(nlen/2 - 100) - } + let mut high = shr(&diff, threshold_bit); let mut one = [0u64; N]; one[0] = 1; - // Exactly 2^(nlen/2 - 100) is also "<=": the high part is 1 and nothing is set below it. - high == one && diff == shl(&one, threshold_bit) + // `|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 * @@ -537,9 +546,11 @@ pub fn keygen_from_rng::new(); { - let g = gcd(&p_minus_1, &q_minus_1); - let q_minus_1_over_g = div(&q_minus_1, &g); + 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); @@ -564,11 +575,14 @@ pub fn keygen_from_rng::new(); { - let q_mod_p = reduce_wide::(&q, &p); - let p_minus_2 = sub_u64(&p, 2); + 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 ctx_p = MontgomeryContext::new(&p).expect("p is odd"); + 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 = RsaPrivateKey::::from_crt_components(&p, &q, &d_p, &d_q, &q_inv)?; @@ -576,3 +590,37 @@ pub fn keygen_from_rng 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 index 63a79359..f541bc49 100644 --- a/crypto/rsa/src/keys.rs +++ b/crypto/rsa/src/keys.rs @@ -21,7 +21,7 @@ use bouncycastle_core::errors::SignatureError; use bouncycastle_core::security_strength::SecurityStrength; use bouncycastle_ec::montgomery; use bouncycastle_ec::nat; -use bouncycastle_utils::secret::Secret; +use bouncycastle_utils::secret::{Secret, zeroize_in_place}; use core::fmt; use core::fmt::{Display, Formatter}; @@ -282,22 +282,31 @@ impl RsaPrivateKey { 5 * HALF_BYTES, "RsaPrivateKey::from_bytes_raw needs SK_LEN == 5 * HALF_BYTES" ); - let p_bytes: [u8; HALF_BYTES] = bytes[..HALF_BYTES].try_into().expect("HALF_BYTES bytes"); - let q_bytes: [u8; HALF_BYTES] = + // Borrowed, not copied: the caller's buffer is the one copy of the encoding. + let p_bytes: &[u8; HALF_BYTES] = bytes[..HALF_BYTES].try_into().expect("HALF_BYTES bytes"); + let q_bytes: &[u8; HALF_BYTES] = bytes[HALF_BYTES..2 * HALF_BYTES].try_into().expect("HALF_BYTES bytes"); - let d_p_bytes: [u8; HALF_BYTES] = + let d_p_bytes: &[u8; HALF_BYTES] = bytes[2 * HALF_BYTES..3 * HALF_BYTES].try_into().expect("HALF_BYTES bytes"); - let d_q_bytes: [u8; HALF_BYTES] = + let d_q_bytes: &[u8; HALF_BYTES] = bytes[3 * HALF_BYTES..4 * HALF_BYTES].try_into().expect("HALF_BYTES bytes"); - let q_inv_bytes: [u8; HALF_BYTES] = + let q_inv_bytes: &[u8; HALF_BYTES] = bytes[4 * HALF_BYTES..].try_into().expect("HALF_BYTES bytes"); - let p = limbs_from_be_bytes::(&p_bytes); - let q = limbs_from_be_bytes::(&q_bytes); - let d_p = limbs_from_be_bytes::(&d_p_bytes); - let d_q = limbs_from_be_bytes::(&d_q_bytes); - let q_inv = limbs_from_be_bytes::(&q_inv_bytes); - Self::from_crt_components(&p, &q, &d_p, &d_q, &q_inv) + let mut p = limbs_from_be_bytes::(p_bytes); + let mut q = limbs_from_be_bytes::(q_bytes); + let mut d_p = limbs_from_be_bytes::(d_p_bytes); + let mut d_q = limbs_from_be_bytes::(d_q_bytes); + let mut q_inv = limbs_from_be_bytes::(q_inv_bytes); + let key = Self::from_crt_components(&p, &q, &d_p, &d_q, &q_inv); + // The five decoded components now live in the key's `Secret` fields (or the decoding was + // rejected); either way these copies are scrubbed before returning. + zeroize_in_place(&mut p); + zeroize_in_place(&mut q); + zeroize_in_place(&mut d_p); + zeroize_in_place(&mut d_q); + zeroize_in_place(&mut q_inv); + key } } diff --git a/crypto/rsa/src/modexp.rs b/crypto/rsa/src/modexp.rs index 3a73531c..6507a019 100644 --- a/crypto/rsa/src/modexp.rs +++ b/crypto/rsa/src/modexp.rs @@ -34,6 +34,7 @@ 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 @@ -143,7 +144,9 @@ fn from_montgomery( ) -> [u64; L] { let mut padded = [0u64; L2]; padded[..L].copy_from_slice(a_bar); - redc_normalize::(&padded, &ctx.modulus, ctx.n_prime) + 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 @@ -156,9 +159,12 @@ pub fn mul_mod( b: &[u64; L], ctx: &MontgomeryContext, ) -> [u64; L] { - let b_bar = to_montgomery::(b, ctx); - let t = montgomery::widening_mul::(a, &b_bar); - redc_normalize::(&t, &ctx.modulus, ctx.n_prime) + 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 @@ -226,6 +232,7 @@ pub fn reduce_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, @@ -235,6 +242,14 @@ pub struct MontgomeryContext { 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 @@ -265,18 +280,29 @@ pub fn mod_pow( 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); - let new_r1 = mont_mul::(&r0, &r1, &ctx.modulus, ctx.n_prime); - let new_r0 = mont_square::(&r0, &ctx.modulus, ctx.n_prime); + 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); } } - from_montgomery::(&r0, ctx) + 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_core.rs b/crypto/rsa/src/rsa_core.rs index 6d7f75c8..13139c55 100644 --- a/crypto/rsa/src/rsa_core.rs +++ b/crypto/rsa/src/rsa_core.rs @@ -15,6 +15,7 @@ use crate::modexp::{MontgomeryContext, mod_pow, mul_mod, reduce_wide, sub_mod}; 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. @@ -87,9 +88,12 @@ pub(crate) fn crt_exp< sk: &RsaPrivateKey, m: &[u64; L], ) -> [u64; L] { - let ctx_p = MontgomeryContext::::new(sk.p()) + // The two contexts hold `p` and `q`; `Secret` scrubs them on return. + let mut ctx_p = Secret::>::new(); + *ctx_p = MontgomeryContext::::new(sk.p()) .expect("RsaPrivateKey::from_crt_components already validated p is odd and nonzero"); - let ctx_q = MontgomeryContext::::new(sk.q()) + let mut ctx_q = Secret::>::new(); + *ctx_q = MontgomeryContext::::new(sk.q()) .expect("RsaPrivateKey::from_crt_components already validated q is odd and nonzero"); // RFC 8017 §5.2.1 step 2.b.1: reducing `m` (n-width) down to each prime's width is not itself @@ -97,11 +101,11 @@ pub(crate) fn crt_exp< // is as wide as `n = p * q`, so a real implementation must reduce it first. `p`/`q` are // private key material, so this uses the constant-time (in the modulus) `reduce_wide`, not // `bouncycastle_ec`-style variable-time reduction (which is only safe for RSA's *public* `n`). - let m_mod_p = reduce_wide::(m, sk.p()); - let m_mod_q = reduce_wide::(m, sk.q()); + let mut m_mod_p = reduce_wide::(m, sk.p()); + let mut m_mod_q = reduce_wide::(m, sk.q()); - let s1 = mod_pow::(&m_mod_p, sk.d_p(), &ctx_p); - let s2 = mod_pow::(&m_mod_q, sk.d_q(), &ctx_q); + let mut s1 = mod_pow::(&m_mod_p, sk.d_p(), &ctx_p); + let mut s2 = mod_pow::(&m_mod_q, sk.d_q(), &ctx_q); // Step 2.b.3: `h = (s1 - s2) * qInv mod p`, which needs `s2` reduced mod `p` first. RFC 8017 // does not require `p` and `q` to be close in magnitude (only that both are the modulus's two @@ -109,19 +113,31 @@ pub(crate) fn crt_exp< // `RsaPrivateKey`'s docs. `reduce_wide` (built for exactly this: reducing a value wider than // its target modulus, constant-time in that modulus) handles the general case; it does not // require its first width to exceed its second. - let s2_mod_p = reduce_wide::(&s2, sk.p()); - let diff = sub_mod::(&s1, &s2_mod_p, sk.p()); - let h = mul_mod::(&diff, sk.q_inv(), &ctx_p); + let mut s2_mod_p = reduce_wide::(&s2, sk.p()); + let mut diff = sub_mod::(&s1, &s2_mod_p, sk.p()); + let mut h = mul_mod::(&diff, sk.q_inv(), &ctx_p); // Step 2.b.4: `s = s2 + q * h`. `h < p` and `q * h < q * p = n`, and CRT recombination // guarantees `s2 + q*h < n` (Garner's algorithm's own correctness property), so this widening // multiply-then-add cannot overflow `L` limbs. - let q_h = montgomery::widening_mul::(sk.q(), &h); + let mut q_h = montgomery::widening_mul::(sk.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"); + // Everything above but `s` is a function of the private primes -- a half-signature alone + // factors `n`, through `gcd(s - s1, n)` -- so it is scrubbed before returning, as + // QUALITY_AND_STYLE.md asks of a secret-holding local. `s` is the caller's. + 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 } From dce549018282b26df90f01283d70550637cbf60f Mon Sep 17 00:00:00 2001 From: David Hook Date: Sun, 8 Nov 2026 16:05:31 +1100 Subject: [PATCH 28/55] core-test-framework: the KEM suite's fixed seed outlasts two draws of the largest KEM and does not repeat The seed was a 256-byte counting pattern, so two consecutive draws of 256, 512 or 1024 bytes, RSASVE's secret at 2048, 4096 and 8192 bits, were identical and the "two encapsulations differ" check failed for every size but 3072; a 4096-byte hashed pattern now. Assisted-by: Claude:claude-mythos-5-1 --- crypto/core-test-framework/src/kem.rs | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/crypto/core-test-framework/src/kem.rs b/crypto/core-test-framework/src/kem.rs index 01c0bea7..945d3274 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 From c3129a31f1ceedb3e90fc64291e312f5ad2c1dc5 Mon Sep 17 00:00:00 2001 From: David Hook Date: Sun, 8 Nov 2026 16:05:31 +1100 Subject: [PATCH 29/55] rsa: RSASVE moves onto the KEM key roles The squash of PR #192 (f3fdb8bf) replaced the static KEM traits: the KEM-only key types implement `EncapsulatingKey<()>` / `DecapsulatingKey<()>` in each size module, naming `RSASVE` as the `KEMAlgorithm`, and hand out `RsasveEncapsulator` / `RsasveDecapsulator` workers whose `encaps_out` is RSASVE.GENERATE and `decaps_out` RSASVE.RECOVER, writing into the caller's buffers and leaving them zeroized on error; `encaps`, `encaps_rng` and `decaps` go, and a wrong-length ciphertext is a type error, so its test and `KEMError::LengthError` go with them. The tests, benches and crate docs call the roles. Assisted-by: Claude:claude-mythos-5-1 --- crypto/rsa/benches/rsa_2048_benches.rs | 12 +- crypto/rsa/benches/rsa_3072_benches.rs | 12 +- crypto/rsa/benches/rsa_4096_benches.rs | 12 +- crypto/rsa/benches/rsa_8192_benches.rs | 12 +- crypto/rsa/src/lib.rs | 21 +- crypto/rsa/src/rsa_2048.rs | 26 ++- crypto/rsa/src/rsa_3072.rs | 26 ++- crypto/rsa/src/rsa_4096.rs | 26 ++- crypto/rsa/src/rsa_8192.rs | 26 ++- crypto/rsa/src/rsasve.rs | 271 ++++++++++++++++++------- crypto/rsa/tests/rsasve_tests.rs | 100 ++++----- 11 files changed, 371 insertions(+), 173 deletions(-) diff --git a/crypto/rsa/benches/rsa_2048_benches.rs b/crypto/rsa/benches/rsa_2048_benches.rs index 65878ae5..78d90df0 100644 --- a/crypto/rsa/benches/rsa_2048_benches.rs +++ b/crypto/rsa/benches/rsa_2048_benches.rs @@ -4,12 +4,12 @@ //! 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::{DeterministicSigningKey, SigningKey, VerifyingKey}; use bouncycastle_core::traits::{ - KEMDecapsulator, KEMEncapsulator, KEMPrivateKey, KEMPublicKey, SignaturePrivateKey, - SignaturePublicKey, + KEMPrivateKey, KEMPublicKey, SignaturePrivateKey, SignaturePublicKey, }; -use bouncycastle_rsa::rsa_2048::{RSA2048KEMPrivateKey, RSA2048KEMPublicKey, RSASVE}; +use bouncycastle_rsa::rsa_2048::{RSA2048KEMPrivateKey, RSA2048KEMPublicKey}; use criterion::{Criterion, criterion_group, criterion_main}; use std::hint::black_box; @@ -257,12 +257,12 @@ fn bench_rsa_2048(c: &mut Criterion) { // draw; decapsulation is the same CRT exponentiation signing does. let kem_sk = RSA2048KEMPrivateKey::from_bytes(&sk.encode()).unwrap(); let kem_pk = RSA2048KEMPublicKey::from_bytes(&pk.encode()).unwrap(); - let (_, kem_ct) = RSASVE::encaps(&kem_pk).unwrap(); + let (_, kem_ct) = kem_pk.encaps(&mut rng, ()).unwrap(); group.bench_function("rsasve_encaps", |b| { - b.iter(|| black_box(RSASVE::encaps_rng(black_box(&kem_pk), &mut rng).unwrap())) + b.iter(|| black_box(black_box(&kem_pk).encaps(&mut rng, ()).unwrap())) }); group.bench_function("rsasve_decaps", |b| { - b.iter(|| black_box(RSASVE::decaps(black_box(&kem_sk), black_box(&kem_ct)).unwrap())) + b.iter(|| black_box(black_box(&kem_sk).decaps(black_box(&kem_ct), ()).unwrap())) }); group.finish(); diff --git a/crypto/rsa/benches/rsa_3072_benches.rs b/crypto/rsa/benches/rsa_3072_benches.rs index c88256df..3ea62f7f 100644 --- a/crypto/rsa/benches/rsa_3072_benches.rs +++ b/crypto/rsa/benches/rsa_3072_benches.rs @@ -2,12 +2,12 @@ //! 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::{DeterministicSigningKey, SigningKey, VerifyingKey}; use bouncycastle_core::traits::{ - KEMDecapsulator, KEMEncapsulator, KEMPrivateKey, KEMPublicKey, SignaturePrivateKey, - SignaturePublicKey, + KEMPrivateKey, KEMPublicKey, SignaturePrivateKey, SignaturePublicKey, }; -use bouncycastle_rsa::rsa_3072::{RSA3072KEMPrivateKey, RSA3072KEMPublicKey, RSASVE}; +use bouncycastle_rsa::rsa_3072::{RSA3072KEMPrivateKey, RSA3072KEMPublicKey}; use criterion::{Criterion, criterion_group, criterion_main}; use std::hint::black_box; @@ -265,12 +265,12 @@ fn bench_rsa_3072(c: &mut Criterion) { // draw; decapsulation is the same CRT exponentiation signing does. let kem_sk = RSA3072KEMPrivateKey::from_bytes(&sk.encode()).unwrap(); let kem_pk = RSA3072KEMPublicKey::from_bytes(&pk.encode()).unwrap(); - let (_, kem_ct) = RSASVE::encaps(&kem_pk).unwrap(); + let (_, kem_ct) = kem_pk.encaps(&mut rng, ()).unwrap(); group.bench_function("rsasve_encaps", |b| { - b.iter(|| black_box(RSASVE::encaps_rng(black_box(&kem_pk), &mut rng).unwrap())) + b.iter(|| black_box(black_box(&kem_pk).encaps(&mut rng, ()).unwrap())) }); group.bench_function("rsasve_decaps", |b| { - b.iter(|| black_box(RSASVE::decaps(black_box(&kem_sk), black_box(&kem_ct)).unwrap())) + b.iter(|| black_box(black_box(&kem_sk).decaps(black_box(&kem_ct), ()).unwrap())) }); group.finish(); diff --git a/crypto/rsa/benches/rsa_4096_benches.rs b/crypto/rsa/benches/rsa_4096_benches.rs index bedbe96c..a2345451 100644 --- a/crypto/rsa/benches/rsa_4096_benches.rs +++ b/crypto/rsa/benches/rsa_4096_benches.rs @@ -3,12 +3,12 @@ //! `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::{DeterministicSigningKey, SigningKey, VerifyingKey}; use bouncycastle_core::traits::{ - KEMDecapsulator, KEMEncapsulator, KEMPrivateKey, KEMPublicKey, SignaturePrivateKey, - SignaturePublicKey, + KEMPrivateKey, KEMPublicKey, SignaturePrivateKey, SignaturePublicKey, }; -use bouncycastle_rsa::rsa_4096::{RSA4096KEMPrivateKey, RSA4096KEMPublicKey, RSASVE}; +use bouncycastle_rsa::rsa_4096::{RSA4096KEMPrivateKey, RSA4096KEMPublicKey}; use criterion::{Criterion, criterion_group, criterion_main}; use std::hint::black_box; @@ -275,12 +275,12 @@ fn bench_rsa_4096(c: &mut Criterion) { // draw; decapsulation is the same CRT exponentiation signing does. let kem_sk = RSA4096KEMPrivateKey::from_bytes(&sk.encode()).unwrap(); let kem_pk = RSA4096KEMPublicKey::from_bytes(&pk.encode()).unwrap(); - let (_, kem_ct) = RSASVE::encaps(&kem_pk).unwrap(); + let (_, kem_ct) = kem_pk.encaps(&mut rng, ()).unwrap(); group.bench_function("rsasve_encaps", |b| { - b.iter(|| black_box(RSASVE::encaps_rng(black_box(&kem_pk), &mut rng).unwrap())) + b.iter(|| black_box(black_box(&kem_pk).encaps(&mut rng, ()).unwrap())) }); group.bench_function("rsasve_decaps", |b| { - b.iter(|| black_box(RSASVE::decaps(black_box(&kem_sk), black_box(&kem_ct)).unwrap())) + b.iter(|| black_box(black_box(&kem_sk).decaps(black_box(&kem_ct), ()).unwrap())) }); group.finish(); diff --git a/crypto/rsa/benches/rsa_8192_benches.rs b/crypto/rsa/benches/rsa_8192_benches.rs index cb20348e..e42cf3db 100644 --- a/crypto/rsa/benches/rsa_8192_benches.rs +++ b/crypto/rsa/benches/rsa_8192_benches.rs @@ -3,12 +3,12 @@ //! 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::{DeterministicSigningKey, SigningKey, VerifyingKey}; use bouncycastle_core::traits::{ - KEMDecapsulator, KEMEncapsulator, KEMPrivateKey, KEMPublicKey, SignaturePrivateKey, - SignaturePublicKey, + KEMPrivateKey, KEMPublicKey, SignaturePrivateKey, SignaturePublicKey, }; -use bouncycastle_rsa::rsa_8192::{RSA8192KEMPrivateKey, RSA8192KEMPublicKey, RSASVE}; +use bouncycastle_rsa::rsa_8192::{RSA8192KEMPrivateKey, RSA8192KEMPublicKey}; use criterion::{Criterion, criterion_group, criterion_main}; use std::hint::black_box; @@ -291,12 +291,12 @@ fn bench_rsa_8192(c: &mut Criterion) { // draw; decapsulation is the same CRT exponentiation signing does. let kem_sk = RSA8192KEMPrivateKey::from_bytes(&sk.encode()).unwrap(); let kem_pk = RSA8192KEMPublicKey::from_bytes(&pk.encode()).unwrap(); - let (_, kem_ct) = RSASVE::encaps(&kem_pk).unwrap(); + let (_, kem_ct) = kem_pk.encaps(&mut rng, ()).unwrap(); group.bench_function("rsasve_encaps", |b| { - b.iter(|| black_box(RSASVE::encaps_rng(black_box(&kem_pk), &mut rng).unwrap())) + b.iter(|| black_box(black_box(&kem_pk).encaps(&mut rng, ()).unwrap())) }); group.bench_function("rsasve_decaps", |b| { - b.iter(|| black_box(RSASVE::decaps(black_box(&kem_sk), black_box(&kem_ct)).unwrap())) + b.iter(|| black_box(black_box(&kem_sk).decaps(black_box(&kem_ct), ()).unwrap())) }); group.finish(); diff --git a/crypto/rsa/src/lib.rs b/crypto/rsa/src/lib.rs index f12c5206..e33f23e2 100644 --- a/crypto/rsa/src/lib.rs +++ b/crypto/rsa/src/lib.rs @@ -128,14 +128,17 @@ //! # Ok::<(), bouncycastle_core::errors::SignatureError>(()) //! ``` //! -//! RSASVE through the `bouncycastle_core` KEM traits ([`rsa_2048::RSASVE`]). The shared secret is +//! 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::traits::{KEMDecapsulator, KEMEncapsulator, KEMPrivateKey, KEMPublicKey, KDF}; -//! use bouncycastle_rsa::rsa_2048::{RSASVE, RSA2048KEMPrivateKey, RSA2048KEMPublicKey, CT_LEN}; +//! 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]; @@ -147,23 +150,23 @@ //! 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) = RSASVE::encaps(&pk)?; +//! 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 = RSASVE::decaps(&sk, &ct)?; +//! 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") +//! .derive_key(&z, b"example protocol v1", 32) //! .expect("HKDF accepts any non-empty input key"); //! assert_eq!(key.key_len(), 32); //! -//! // A wrong-length ciphertext is an error. So is one outside (1, n - 1) (SP 800-56B §7.1.2.3). -//! assert!(RSASVE::decaps(&sk, &ct[1..]).is_err()); -//! assert!(RSASVE::decaps(&sk, &[0u8; CT_LEN]).is_err()); +//! // 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()); //! # Ok::<(), bouncycastle_core::errors::KEMError>(()) //! ``` //! diff --git a/crypto/rsa/src/rsa_2048.rs b/crypto/rsa/src/rsa_2048.rs index c2884492..7bdaee52 100644 --- a/crypto/rsa/src/rsa_2048.rs +++ b/crypto/rsa/src/rsa_2048.rs @@ -17,8 +17,9 @@ use crate::keys::{RsaPrivateKey, RsaPublicKey}; use crate::rsassa_pkcs1_v1_5::RSASSA_PKCS1_v1_5; use crate::rsassa_pss::RSASSA_PSS; use crate::rsassa_pss_shake::RSASSA_PSS_SHAKE; -use crate::rsasve::{RsaKEMPrivateKey, RsaKEMPublicKey}; +use crate::rsasve::{RsaKEMPrivateKey, RsaKEMPublicKey, RsasveDecapsulator, RsasveEncapsulator}; use bouncycastle_core::errors::{KEMError, SignatureError}; +use bouncycastle_core::kem_key::{DecapsulatingKey, EncapsulatingKey}; use bouncycastle_core::security_strength::SecurityStrength; use bouncycastle_core::traits::{ KEMPrivateKey, KEMPublicKey, RNG, SignaturePrivateKey, SignaturePublicKey, @@ -138,7 +139,8 @@ pub const CT_LEN: usize = 256; /// value, not a derived key: see [`crate::rsasve`]. pub const SS_LEN: usize = 256; -/// RSASVE (SP 800-56B Rev. 2 §7.2.1) over RSA-2048 as a `KEMEncapsulator`/`KEMDecapsulator`: +/// RSASVE (SP 800-56B Rev. 2 §7.2.1) over RSA-2048, the algorithm the KEM roles of +/// [`RSA2048KEMPublicKey`] and [`RSA2048KEMPrivateKey`] name: /// [`crate::rsasve::RSASVE`] at this size's widths and its 112-bit security strength. pub type RSASVE = crate::rsasve::RSASVE<32, 64, 65, 16, 32, 33, 256, 112>; @@ -152,6 +154,26 @@ impl RSASVE { } } +impl EncapsulatingKey<(), CT_LEN, SS_LEN> for RSA2048KEMPublicKey { + type Algorithm = RSASVE; + type Encapsulator<'k> = RsasveEncapsulator<'k, 32, 64, 65, 256, 112>; + + /// The raw KEM takes nothing beyond the key, so this never fails. + fn create_encapsulator<'k>(&'k self, _params: ()) -> Result, KEMError> { + Ok(RsasveEncapsulator::new(self)) + } +} + +impl DecapsulatingKey<(), CT_LEN, SS_LEN> for RSA2048KEMPrivateKey { + type Algorithm = RSASVE; + type Decapsulator<'k> = RsasveDecapsulator<'k, 32, 64, 65, 16, 32, 33, 256, 112>; + + /// The raw KEM takes nothing beyond the key, so this never fails. + fn create_decapsulator<'k>(&'k self, _params: ()) -> Result, KEMError> { + Ok(RsasveDecapsulator::new(self)) + } +} + impl KEMPrivateKey for RSA2048KEMPrivateKey { fn encode(&self) -> [u8; SK_LEN] { self.0.encode_raw::<128, SK_LEN>() diff --git a/crypto/rsa/src/rsa_3072.rs b/crypto/rsa/src/rsa_3072.rs index bbeed231..4c31346d 100644 --- a/crypto/rsa/src/rsa_3072.rs +++ b/crypto/rsa/src/rsa_3072.rs @@ -5,8 +5,9 @@ use crate::keys::{RsaPrivateKey, RsaPublicKey}; use crate::rsassa_pkcs1_v1_5::RSASSA_PKCS1_v1_5; use crate::rsassa_pss::RSASSA_PSS; use crate::rsassa_pss_shake::RSASSA_PSS_SHAKE; -use crate::rsasve::{RsaKEMPrivateKey, RsaKEMPublicKey}; +use crate::rsasve::{RsaKEMPrivateKey, RsaKEMPublicKey, RsasveDecapsulator, RsasveEncapsulator}; use bouncycastle_core::errors::{KEMError, SignatureError}; +use bouncycastle_core::kem_key::{DecapsulatingKey, EncapsulatingKey}; use bouncycastle_core::security_strength::SecurityStrength; use bouncycastle_core::traits::{ KEMPrivateKey, KEMPublicKey, RNG, SignaturePrivateKey, SignaturePublicKey, @@ -123,7 +124,8 @@ pub const CT_LEN: usize = 384; /// value, not a derived key: see [`crate::rsasve`]. pub const SS_LEN: usize = 384; -/// RSASVE (SP 800-56B Rev. 2 §7.2.1) over RSA-3072 as a `KEMEncapsulator`/`KEMDecapsulator`: +/// RSASVE (SP 800-56B Rev. 2 §7.2.1) over RSA-3072, the algorithm the KEM roles of +/// [`RSA3072KEMPublicKey`] and [`RSA3072KEMPrivateKey`] name: /// [`crate::rsasve::RSASVE`] at this size's widths and its 128-bit security strength. pub type RSASVE = crate::rsasve::RSASVE<48, 96, 97, 24, 48, 49, 384, 128>; @@ -137,6 +139,26 @@ impl RSASVE { } } +impl EncapsulatingKey<(), CT_LEN, SS_LEN> for RSA3072KEMPublicKey { + type Algorithm = RSASVE; + type Encapsulator<'k> = RsasveEncapsulator<'k, 48, 96, 97, 384, 128>; + + /// The raw KEM takes nothing beyond the key, so this never fails. + fn create_encapsulator<'k>(&'k self, _params: ()) -> Result, KEMError> { + Ok(RsasveEncapsulator::new(self)) + } +} + +impl DecapsulatingKey<(), CT_LEN, SS_LEN> for RSA3072KEMPrivateKey { + type Algorithm = RSASVE; + type Decapsulator<'k> = RsasveDecapsulator<'k, 48, 96, 97, 24, 48, 49, 384, 128>; + + /// The raw KEM takes nothing beyond the key, so this never fails. + fn create_decapsulator<'k>(&'k self, _params: ()) -> Result, KEMError> { + Ok(RsasveDecapsulator::new(self)) + } +} + impl KEMPrivateKey for RSA3072KEMPrivateKey { fn encode(&self) -> [u8; SK_LEN] { self.0.encode_raw::<192, SK_LEN>() diff --git a/crypto/rsa/src/rsa_4096.rs b/crypto/rsa/src/rsa_4096.rs index b631e350..966f8a87 100644 --- a/crypto/rsa/src/rsa_4096.rs +++ b/crypto/rsa/src/rsa_4096.rs @@ -5,8 +5,9 @@ use crate::keys::{RsaPrivateKey, RsaPublicKey}; use crate::rsassa_pkcs1_v1_5::RSASSA_PKCS1_v1_5; use crate::rsassa_pss::RSASSA_PSS; use crate::rsassa_pss_shake::RSASSA_PSS_SHAKE; -use crate::rsasve::{RsaKEMPrivateKey, RsaKEMPublicKey}; +use crate::rsasve::{RsaKEMPrivateKey, RsaKEMPublicKey, RsasveDecapsulator, RsasveEncapsulator}; use bouncycastle_core::errors::{KEMError, SignatureError}; +use bouncycastle_core::kem_key::{DecapsulatingKey, EncapsulatingKey}; use bouncycastle_core::security_strength::SecurityStrength; use bouncycastle_core::traits::{ KEMPrivateKey, KEMPublicKey, RNG, SignaturePrivateKey, SignaturePublicKey, @@ -123,7 +124,8 @@ pub const CT_LEN: usize = 512; /// value, not a derived key: see [`crate::rsasve`]. pub const SS_LEN: usize = 512; -/// RSASVE (SP 800-56B Rev. 2 §7.2.1) over RSA-4096 as a `KEMEncapsulator`/`KEMDecapsulator`: +/// RSASVE (SP 800-56B Rev. 2 §7.2.1) over RSA-4096, the algorithm the KEM roles of +/// [`RSA4096KEMPublicKey`] and [`RSA4096KEMPrivateKey`] name: /// [`crate::rsasve::RSASVE`] at this size's widths and its 128-bit security strength. pub type RSASVE = crate::rsasve::RSASVE<64, 128, 129, 32, 64, 65, 512, 128>; @@ -137,6 +139,26 @@ impl RSASVE { } } +impl EncapsulatingKey<(), CT_LEN, SS_LEN> for RSA4096KEMPublicKey { + type Algorithm = RSASVE; + type Encapsulator<'k> = RsasveEncapsulator<'k, 64, 128, 129, 512, 128>; + + /// The raw KEM takes nothing beyond the key, so this never fails. + fn create_encapsulator<'k>(&'k self, _params: ()) -> Result, KEMError> { + Ok(RsasveEncapsulator::new(self)) + } +} + +impl DecapsulatingKey<(), CT_LEN, SS_LEN> for RSA4096KEMPrivateKey { + type Algorithm = RSASVE; + type Decapsulator<'k> = RsasveDecapsulator<'k, 64, 128, 129, 32, 64, 65, 512, 128>; + + /// The raw KEM takes nothing beyond the key, so this never fails. + fn create_decapsulator<'k>(&'k self, _params: ()) -> Result, KEMError> { + Ok(RsasveDecapsulator::new(self)) + } +} + impl KEMPrivateKey for RSA4096KEMPrivateKey { fn encode(&self) -> [u8; SK_LEN] { self.0.encode_raw::<256, SK_LEN>() diff --git a/crypto/rsa/src/rsa_8192.rs b/crypto/rsa/src/rsa_8192.rs index a4b97e18..b547531c 100644 --- a/crypto/rsa/src/rsa_8192.rs +++ b/crypto/rsa/src/rsa_8192.rs @@ -4,8 +4,9 @@ use crate::keys::{RsaPrivateKey, RsaPublicKey}; use crate::rsassa_pkcs1_v1_5::RSASSA_PKCS1_v1_5; use crate::rsassa_pss::RSASSA_PSS; -use crate::rsasve::{RsaKEMPrivateKey, RsaKEMPublicKey}; +use crate::rsasve::{RsaKEMPrivateKey, RsaKEMPublicKey, RsasveDecapsulator, RsasveEncapsulator}; use bouncycastle_core::errors::{KEMError, SignatureError}; +use bouncycastle_core::kem_key::{DecapsulatingKey, EncapsulatingKey}; use bouncycastle_core::security_strength::SecurityStrength; use bouncycastle_core::traits::{ KEMPrivateKey, KEMPublicKey, RNG, SignaturePrivateKey, SignaturePublicKey, @@ -117,7 +118,8 @@ pub const CT_LEN: usize = 1024; /// value, not a derived key: see [`crate::rsasve`]. pub const SS_LEN: usize = 1024; -/// RSASVE (SP 800-56B Rev. 2 §7.2.1) over RSA-8192 as a `KEMEncapsulator`/`KEMDecapsulator`: +/// RSASVE (SP 800-56B Rev. 2 §7.2.1) over RSA-8192, the algorithm the KEM roles of +/// [`RSA8192KEMPublicKey`] and [`RSA8192KEMPrivateKey`] name: /// [`crate::rsasve::RSASVE`] at this size's widths and its 192-bit security strength. pub type RSASVE = crate::rsasve::RSASVE<128, 256, 257, 64, 128, 129, 1024, 192>; @@ -131,6 +133,26 @@ impl RSASVE { } } +impl EncapsulatingKey<(), CT_LEN, SS_LEN> for RSA8192KEMPublicKey { + type Algorithm = RSASVE; + type Encapsulator<'k> = RsasveEncapsulator<'k, 128, 256, 257, 1024, 192>; + + /// The raw KEM takes nothing beyond the key, so this never fails. + fn create_encapsulator<'k>(&'k self, _params: ()) -> Result, KEMError> { + Ok(RsasveEncapsulator::new(self)) + } +} + +impl DecapsulatingKey<(), CT_LEN, SS_LEN> for RSA8192KEMPrivateKey { + type Algorithm = RSASVE; + type Decapsulator<'k> = RsasveDecapsulator<'k, 128, 256, 257, 64, 128, 129, 1024, 192>; + + /// The raw KEM takes nothing beyond the key, so this never fails. + fn create_decapsulator<'k>(&'k self, _params: ()) -> Result, KEMError> { + Ok(RsasveDecapsulator::new(self)) + } +} + impl KEMPrivateKey for RSA8192KEMPrivateKey { fn encode(&self) -> [u8; SK_LEN] { self.0.encode_raw::<512, SK_LEN>() diff --git a/crypto/rsa/src/rsasve.rs b/crypto/rsa/src/rsasve.rs index 6aa9d000..df42ad25 100644 --- a/crypto/rsa/src/rsasve.rs +++ b/crypto/rsa/src/rsasve.rs @@ -1,8 +1,9 @@ //! RSASVE, RSA Secret-Value Encapsulation (NIST SP 800-56B Rev. 2 §7.2.1), as a -//! [`bouncycastle_core`] KEM: [`RSASVE`] implements -//! [`KEMEncapsulator`]/[`KEMDecapsulator`], with RSASVE.GENERATE (§7.2.1.2) as `encaps` and -//! RSASVE.RECOVER (§7.2.1.3) as `decaps`, over the KEM-only key types [`RsaKEMPublicKey`] and -//! [`RsaKEMPrivateKey`]. +//! [`bouncycastle_core`] KEM on the key objects: the KEM-only key types [`RsaKEMPublicKey`] and +//! [`RsaKEMPrivateKey`] implement the `EncapsulatingKey` / `DecapsulatingKey` roles over `()` +//! in each size module, naming [`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 @@ -16,7 +17,7 @@ //! //! The key types here wrap the signature schemes' [`RsaPublicKey`]/[`RsaPrivateKey`] 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 `KEMDecapsulator` impl for an +//! signing-role impl for an [`RsaKEMPrivateKey`] and no decapsulating role for an //! [`RsaPrivateKey`]. 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 @@ -48,13 +49,11 @@ use crate::keys::{RsaPrivateKey, RsaPublicKey}; use crate::rsa_core::{crt_exp, public_exp}; use bouncycastle_core::errors::{KEMError, RNGError, SignatureError}; use bouncycastle_core::hazmat::do_hazardous_operations; +use bouncycastle_core::kem_key::KEMAlgorithm; use bouncycastle_core::key_material::{KeyMaterial, KeyMaterialTrait, KeyType}; use bouncycastle_core::security_strength::SecurityStrength; -use bouncycastle_core::traits::{ - KEMDecapsulator, KEMEncapsulator, KEMPrivateKey, KEMPublicKey, RNG, -}; +use bouncycastle_core::traits::{Algorithm, KEMDecapsulator, KEMEncapsulator, RNG}; use bouncycastle_ec::nat; -use bouncycastle_rng::DefaultRNG; use bouncycastle_utils::secret::Secret; use core::fmt; use core::fmt::{Display, Formatter}; @@ -202,19 +201,16 @@ impl RsaKEMPrivateKey { } } -/// RSASVE (SP 800-56B Rev. 2 §7.2.1) at one modulus size, as a -/// [`KEMEncapsulator`]/[`KEMDecapsulator`]. Each size module names its own instantiation (e.g. -/// `crate::rsa_2048::RSASVE`), along with that size's `keygen(rng)` as an inherent associated -/// function, which is where the KEM traits' docs put key generation. +/// RSASVE (SP 800-56B Rev. 2 §7.2.1) at one modulus size: the [`KEMAlgorithm`] marker the key +/// roles name, carrying the metadata and no state. Each size module names its own instantiation +/// (e.g. `crate::rsa_2048::RSASVE`), along with that size's `keygen(rng)` as an inherent +/// associated function. /// /// `L`/`L2`/`L21`/`HALF`/`HALF2`/`HALF21` are the widths the rest of this crate threads through /// `rsa_core` (see [`crate::modexp`]). `N_BYTES = 8 * L` is `nLen`, which is both the ciphertext /// length and the shared-secret length. `SECURITY_BITS` is the modulus's SP 800-57 Part 1 -/// security strength, the same value that size's `keygen` demands of its RNG. `encaps_rng` +/// security strength, the same value that size's `keygen` demands of its RNG. Encapsulation /// demands it too, and the shared secret is labelled with it. -/// -/// Uninhabited: every operation is an associated function, as with the other KEMs in this -/// workspace. #[allow(non_camel_case_types)] pub struct RSASVE< const L: usize, @@ -229,6 +225,17 @@ pub struct RSASVE< _widths: PhantomData<[u64; L]>, } +/// The algorithm name at one modulus size, from the limb count. +const fn alg_name(l: usize) -> &'static str { + match l { + 32 => "RSASVE-2048", + 48 => "RSASVE-3072", + 64 => "RSASVE-4096", + 128 => "RSASVE-8192", + _ => "RSASVE", + } +} + impl< const L: usize, const L2: usize, @@ -238,35 +245,95 @@ impl< const HALF21: usize, const N_BYTES: usize, const SECURITY_BITS: usize, - const PK_LEN: usize, -> KEMEncapsulator, PK_LEN, N_BYTES, N_BYTES> - for RSASVE -where - RsaKEMPublicKey: KEMPublicKey, +> Algorithm for RSASVE +{ + const ALG_NAME: &'static str = alg_name(L); + const MAX_SECURITY_STRENGTH: SecurityStrength = SecurityStrength::from_bits(SECURITY_BITS); +} + +impl< + const L: usize, + const L2: usize, + const L21: usize, + const HALF: usize, + const HALF2: usize, + const HALF21: usize, + const N_BYTES: usize, + const SECURITY_BITS: usize, +> KEMAlgorithm for RSASVE +{ +} + +/// The encapsulator an [`RsaKEMPublicKey`] hands out through `EncapsulatingKey<()>`: it borrows +/// the key and draws `Z` from the RNG of each call. The widths are the size module's. +pub struct RsasveEncapsulator< + 'k, + const L: usize, + const L2: usize, + const L21: usize, + const N_BYTES: usize, + const SECURITY_BITS: usize, +> { + pk: &'k RsaKEMPublicKey, +} + +impl< + 'k, + const L: usize, + const L2: usize, + const L21: usize, + const N_BYTES: usize, + const SECURITY_BITS: usize, +> RsasveEncapsulator<'k, L, L2, L21, N_BYTES, SECURITY_BITS> { - /// RSASVE.GENERATE, drawing `Z` from the library's default OS-backed RNG. See - /// [`Self::encaps_rng`]. - fn encaps(pk: &RsaKEMPublicKey) -> Result<(KeyMaterial, [u8; N_BYTES]), KEMError> { - Self::encaps_rng(pk, &mut DefaultRNG::default()) + /// Borrows `pk`; the size modules' role impls call this. + pub(crate) fn new(pk: &'k RsaKEMPublicKey) -> Self { + Self { pk } } +} - /// RSASVE.GENERATE((n, e)) (SP 800-56B Rev. 2 §7.2.1.2), drawing `Z` from `rng`. Returns - /// `(Z, C)`: the secret value as a [`KeyMaterial`] of type - /// [`KeyType::CryptographicRandom`] at the modulus's security strength, and the ciphertext. +impl< + const L: usize, + const L2: usize, + const L21: usize, + const N_BYTES: usize, + const SECURITY_BITS: usize, +> Algorithm for RsasveEncapsulator<'_, L, L2, L21, N_BYTES, SECURITY_BITS> +{ + const ALG_NAME: &'static str = alg_name(L); + const MAX_SECURITY_STRENGTH: SecurityStrength = SecurityStrength::from_bits(SECURITY_BITS); +} + +impl< + const L: usize, + const L2: usize, + const L21: usize, + const N_BYTES: usize, + const SECURITY_BITS: usize, +> KEMEncapsulator for RsasveEncapsulator<'_, L, L2, L21, N_BYTES, SECURITY_BITS> +{ + /// RSASVE.GENERATE((n, e)) (SP 800-56B Rev. 2 §7.2.1.2), drawing `Z` from `rng`: the + /// ciphertext `C` into `ct` and the secret value `Z` into `ss`, as a [`KeyMaterial`] of type + /// [`KeyType::CryptographicRandom`] at the modulus's security strength. /// /// Errors: `RNGError(SecurityStrengthInsufficientForAlgorithm)` if `rng` is weaker than the /// modulus (§5.3: an RBG generating `Z` "shall be instantiated to support a security strength /// that is equal to or greater than the security strength associated with the RSA modulus /// length"), /// `RNGError` if `rng` fails, and `GenericError` if [`MAX_GENERATE_ATTEMPTS`] draws all fall - /// outside `(1, n - 1)`, which a working RNG does not do (see that constant). + /// outside `(1, n - 1)`, which a working RNG does not do (see that constant). Both buffers + /// are left zeroized on every error. // `Z`, `C`: SP 800-56B's own names (see QUALITY_AND_STYLE.md's naming exception). #[allow(non_snake_case)] - fn encaps_rng( - pk: &RsaKEMPublicKey, + fn encaps_out( + &self, rng: &mut dyn RNG, - ) -> Result<(KeyMaterial, [u8; N_BYTES]), KEMError> { + ct: &mut [u8; N_BYTES], + ss: &mut KeyMaterial, + ) -> Result { debug_assert_eq!(N_BYTES, 8 * L, "RSASVE needs N_BYTES == 8 * L"); + ct.fill(0); + ss.zeroize(); if rng.security_strength() < SecurityStrength::from_bits(SECURITY_BITS) { return Err(KEMError::RNGError(RNGError::SecurityStrengthInsufficientForAlgorithm)); } @@ -292,7 +359,7 @@ where // Step 2.b: "z = BS2I(Z, nLen)." *z = limbs_from_be_bytes::(&Z); // Step 2.c: "If z does not satisfy 1 < z < (n – 1), then go to step 2a." - if in_open_range(&z, pk.n()) { + if in_open_range(&z, self.pk.n()) { break; } } @@ -300,20 +367,56 @@ where // Step 3.a: "c = RSAEP((n, e), z)". RSAEP's own step 1 range check (§7.1.1, "1 < m < // (n – 1)") is the one step 2.c has just ensured, so it is not repeated: `public_exp` is // RSAEP's step 2, `c = z^e mod n`. - let c = public_exp::(&pk.0, &z); + let c = public_exp::(&self.pk.0, &z); // Step 3.b: "C = I2BS(c, nLen)." - let C = be_bytes_from_limbs::(&c); + *ct = be_bytes_from_limbs::(&c); // Step 4: "Output the string Z as the secret value, and the ciphertext C." - let mut ss = KeyMaterial::::from_bytes_as_type(&*Z, KeyType::CryptographicRandom)?; - do_hazardous_operations(&mut ss, |ss| { - ss.set_security_strength(SecurityStrength::from_bits(SECURITY_BITS)) - })?; - Ok((ss, C)) + if let Err(e) = secret_value_into::(&Z, ss) { + ct.fill(0); + return Err(e); + } + Ok(N_BYTES) + } +} + +/// `Z` into `ss` as [`KeyType::CryptographicRandom`] at the modulus's strength, zeroizing `ss` +/// first and again if the label cannot be set. +#[allow(non_snake_case)] +fn secret_value_into( + Z: &[u8; N_BYTES], + 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(SecurityStrength::from_bits(SECURITY_BITS)) + }); + if let Err(e) = result { + ss.zeroize(); + return Err(e.into()); } + Ok(()) +} + +/// The decapsulator an [`RsaKEMPrivateKey`] hands out through `DecapsulatingKey<()>`: it borrows +/// the key. The widths are the size module's. +pub struct RsasveDecapsulator< + 'k, + const L: usize, + const L2: usize, + const L21: usize, + const HALF: usize, + const HALF2: usize, + const HALF21: usize, + const N_BYTES: usize, + const SECURITY_BITS: usize, +> { + sk: &'k RsaKEMPrivateKey, } impl< + 'k, const L: usize, const L2: usize, const L21: usize, @@ -322,37 +425,66 @@ impl< const HALF21: usize, const N_BYTES: usize, const SECURITY_BITS: usize, - const SK_LEN: usize, -> KEMDecapsulator, SK_LEN, N_BYTES, N_BYTES> - for RSASVE -where - RsaKEMPrivateKey: KEMPrivateKey, +> RsasveDecapsulator<'k, L, L2, L21, HALF, HALF2, HALF21, N_BYTES, SECURITY_BITS> +{ + /// Borrows `sk`; the size modules' role impls call this. + pub(crate) fn new(sk: &'k RsaKEMPrivateKey) -> Self { + Self { sk } + } +} + +impl< + const L: usize, + const L2: usize, + const L21: usize, + const HALF: usize, + const HALF2: usize, + const HALF21: usize, + const N_BYTES: usize, + const SECURITY_BITS: usize, +> Algorithm for RsasveDecapsulator<'_, L, L2, L21, HALF, HALF2, HALF21, N_BYTES, SECURITY_BITS> +{ + const ALG_NAME: &'static str = alg_name(L); + const MAX_SECURITY_STRENGTH: SecurityStrength = SecurityStrength::from_bits(SECURITY_BITS); +} + +impl< + const L: usize, + const L2: usize, + const L21: usize, + const HALF: usize, + const HALF2: usize, + const HALF21: usize, + const N_BYTES: usize, + const SECURITY_BITS: usize, +> KEMDecapsulator + for RsasveDecapsulator<'_, L, L2, L21, HALF, HALF2, HALF21, N_BYTES, SECURITY_BITS> { /// RSASVE.RECOVER((n, d), C) (SP 800-56B Rev. 2 §7.2.1.3), with the private key in CRT form - /// (§7.1.2.3's RSADP). Returns `Z` as a [`KeyMaterial`] of type - /// [`KeyType::CryptographicRandom`] at the modulus's security strength, matching what - /// [`KEMEncapsulator::encaps_rng`] returned to the other party. + /// (§7.1.2.3's RSADP): `Z` into `ss` as a [`KeyMaterial`] of type + /// [`KeyType::CryptographicRandom`] at the modulus's security strength, matching what the + /// encapsulator gave the other party. /// - /// Errors: `LengthError` if `ct` is not `nLen` bytes long (step 2), and `DecapsulationFailed` - /// if RSADP finds the ciphertext out of range (step 3.c). §7.2.1.3 calls both "an indication - /// of a decryption error". They are kept as separate variants because every KEM in this workspace reports a - /// wrong-length ciphertext as `LengthError`, which `bouncycastle_core_test_framework`'s KEM - /// suite checks. A ciphertext that is in range but was never produced by `encaps` is *not* - /// detected. RSASVE has no redundancy to check, so such a ciphertext just recovers a different - /// `Z` (see the crate docs' `# Security Considerations`). + /// Errors: `DecapsulationFailed` if RSADP finds the ciphertext out of range (step 3.c), + /// which §7.2.1.3 calls "an indication of a decryption error"; step 2's length check is the + /// type's. A ciphertext that is in range but was never produced by an encapsulation is *not* + /// detected. RSASVE has no redundancy to check, so such a ciphertext just recovers a + /// different `Z` (see the crate docs' `# Security Considerations`). `ss` is left zeroized + /// on every error. #[allow(non_snake_case)] - fn decaps(sk: &RsaKEMPrivateKey, ct: &[u8]) -> Result, KEMError> { + fn decaps_out( + &self, + ct: &[u8; N_BYTES], + ss: &mut KeyMaterial, + ) -> Result { debug_assert_eq!(N_BYTES, 8 * L, "RSASVE needs N_BYTES == 8 * L"); - // Step 1: "nLen = len(n)/8" -- N_BYTES, as in `encaps_rng`. - + ss.zeroize(); + // Step 1: "nLen = len(n)/8" -- N_BYTES, as in `encaps_out`. // Step 2: "If the length of the ciphertext C is not nLen bytes in length, output an - // indication of a decryption error". - let C: &[u8; N_BYTES] = ct - .try_into() - .map_err(|_| KEMError::LengthError("RSASVE ciphertext must be exactly nLen bytes"))?; + // indication of a decryption error" -- the array type. // Step 3.a: "c = BS2I(C)." - let c = limbs_from_be_bytes::(C); + let c = limbs_from_be_bytes::(ct); // Step 3.b/3.c: "z = RSADP((n, d), c)", and "If RSADP indicates that the ciphertext is // out of range, output an indication of a decryption error". This is RSADP's step 1 @@ -361,22 +493,19 @@ where // c^dP mod p`, `mq = c^dQ mod q`, `h = ((mp − mq) × qInv) mod p`, `m = mq + q × h`). // `c` is the public ciphertext, so the range check need not be constant-time, although // it is. - if !in_open_range(&c, sk.n()) { + if !in_open_range(&c, self.sk.n()) { return Err(KEMError::DecapsulationFailed); } let mut z = Secret::<[u64; L]>::new(); - *z = crt_exp::(&sk.0, &c); + *z = crt_exp::(&self.sk.0, &c); // Step 3.d: "Z = I2BS(z, nLen)." let mut Z = Secret::<[u8; N_BYTES]>::new(); *Z = be_bytes_from_limbs::(&z); // Step 4: "Output the string Z as the secret value (i.e., the shared secret)". - let mut ss = KeyMaterial::::from_bytes_as_type(&*Z, KeyType::CryptographicRandom)?; - do_hazardous_operations(&mut ss, |ss| { - ss.set_security_strength(SecurityStrength::from_bits(SECURITY_BITS)) - })?; - Ok(ss) + secret_value_into::(&Z, ss)?; + Ok(N_BYTES) } } diff --git a/crypto/rsa/tests/rsasve_tests.rs b/crypto/rsa/tests/rsasve_tests.rs index c2cc0f3b..3b3d5332 100644 --- a/crypto/rsa/tests/rsasve_tests.rs +++ b/crypto/rsa/tests/rsasve_tests.rs @@ -6,7 +6,7 @@ //! (`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_rng` through an RNG that emits the +//! 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 @@ -22,9 +22,10 @@ //! suites below use as their fixed keys. use bouncycastle_core::errors::{KEMError, 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::{KEMDecapsulator, KEMEncapsulator, KEMPrivateKey, KEMPublicKey}; +use bouncycastle_core::traits::{KEMPrivateKey, KEMPublicKey}; use bouncycastle_core_test_framework::kem::{TestFrameworkKEM, TestFrameworkKEMKeys}; use bouncycastle_hex::decode as hex_decode; use bouncycastle_rng::DefaultRNG; @@ -89,7 +90,7 @@ macro_rules! rsasve_suite { ($module:ident, $size:ident, $bits:literal, $L:literal, $HALF:literal, $strength:expr, $weaker:expr) => { mod $module { use super::*; - use bouncycastle_rsa::$size::{CT_LEN, PK_LEN, RSASVE, SK_LEN, SS_LEN}; + use bouncycastle_rsa::$size::{CT_LEN, PK_LEN, SK_LEN, SS_LEN}; type PK = bouncycastle_rsa::rsasve::RsaKEMPublicKey<$L>; type SK = bouncycastle_rsa::rsasve::RsaKEMPrivateKey<$L, $HALF>; @@ -129,10 +130,11 @@ macro_rules! rsasve_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::( - openssl_keypair, false, - ); + TestFrameworkKEM::new(false, true).test_kem::<(), PK, SK, CT_LEN, SS_LEN>( + openssl_keypair, + (), + false, + ); } #[test] @@ -159,7 +161,7 @@ macro_rules! rsasve_suite { } /// OpenSSL encapsulated; this crate decapsulates. And the other way round: fed - /// OpenSSL's `Z` as its RNG output, `encaps_rng` must produce OpenSSL's `C` exactly + /// OpenSSL's `Z` as its RNG output, `encaps` must produce OpenSSL's `C` exactly /// (RSAEP is deterministic in `z`). #[test] fn openssl_rsasve_vectors() { @@ -171,12 +173,11 @@ macro_rules! rsasve_suite { let c = be_bytes::(enc["C"].as_str().unwrap()); let z = be_bytes::(enc["Z"].as_str().unwrap()); - let ss = RSASVE::decaps(&sk, &c).unwrap(); + let ss = sk.decaps(&c, ()).unwrap(); assert_eq!(ss.ref_to_bytes(), &z[..]); let (ss, ct) = - RSASVE::encaps_rng(&pk, &mut rng_emitting(z, SecurityStrength::_256bit)) - .unwrap(); + pk.encaps(&mut rng_emitting(z, SecurityStrength::_256bit), ()).unwrap(); assert_eq!(ct, c); assert_eq!(ss.ref_to_bytes(), &z[..]); } @@ -185,11 +186,11 @@ macro_rules! rsasve_suite { #[test] fn shared_secret_is_labelled_with_the_modulus_strength() { let (pk, sk) = openssl_keypair().unwrap(); - let (ss, ct) = RSASVE::encaps(&pk).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 = RSASVE::decaps(&sk, &ct).unwrap(); + 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); @@ -197,13 +198,11 @@ macro_rules! rsasve_suite { } #[test] - fn encaps_rng_accepts_exactly_the_modulus_strength_and_rejects_below_it() { + fn encaps_accepts_exactly_the_modulus_strength_and_rejects_below_it() { let (pk, _) = openssl_keypair().unwrap(); - assert!( - RSASVE::encaps_rng(&pk, &mut rng_emitting([0x5Au8; CT_LEN], $strength)).is_ok() - ); + assert!(pk.encaps(&mut rng_emitting([0x5Au8; CT_LEN], $strength), ()).is_ok()); assert!(matches!( - RSASVE::encaps_rng(&pk, &mut rng_emitting([0x5Au8; CT_LEN], $weaker)), + pk.encaps(&mut rng_emitting([0x5Au8; CT_LEN], $weaker), ()), Err(KEMError::RNGError(RNGError::SecurityStrengthInsufficientForAlgorithm)) )); } @@ -233,13 +232,11 @@ macro_rules! rsasve_suite { let mut stream = [0u8; 2 * CT_LEN]; stream[..CT_LEN].copy_from_slice(&bad); stream[CT_LEN..].copy_from_slice(&good); - let (ss, ct) = RSASVE::encaps_rng( - &pk, - &mut rng_emitting(stream, SecurityStrength::_256bit), - ) - .unwrap(); + let (ss, ct) = pk + .encaps(&mut rng_emitting(stream, SecurityStrength::_256bit), ()) + .unwrap(); assert_eq!(ss.ref_to_bytes(), &good[..]); - assert_eq!(RSASVE::decaps(&sk, &ct).unwrap().ref_to_bytes(), &good[..]); + assert_eq!(sk.decaps(&ct, ()).unwrap().ref_to_bytes(), &good[..]); } } } @@ -249,10 +246,7 @@ macro_rules! rsasve_suite { let (pk, _) = openssl_keypair().unwrap(); for stuck in [[0xFFu8; CT_LEN], [0u8; CT_LEN]] { assert!(matches!( - RSASVE::encaps_rng( - &pk, - &mut rng_emitting(stuck, SecurityStrength::_256bit) - ), + pk.encaps(&mut rng_emitting(stuck, SecurityStrength::_256bit), ()), Err(KEMError::GenericError(_)) )); } @@ -263,7 +257,7 @@ macro_rules! rsasve_suite { 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, _) = RSASVE::encaps_rng(&pk, &mut rng).unwrap(); + let (ss, _) = pk.encaps(&mut rng, ()).unwrap(); assert_eq!(ss.ref_to_bytes(), &[0x5Au8; CT_LEN][..]); } @@ -283,24 +277,10 @@ macro_rules! rsasve_suite { one[CT_LEN - 1] = 1; for bad in [[0u8; CT_LEN], one, n_minus_1, n, [0xFFu8; CT_LEN]] { - assert!(matches!( - RSASVE::decaps(&sk, &bad), - Err(KEMError::DecapsulationFailed) - )); + assert!(matches!(sk.decaps(&bad, ()), Err(KEMError::DecapsulationFailed))); } for good in [two, n_minus_2] { - assert!(RSASVE::decaps(&sk, &good).is_ok()); - } - } - - #[test] - fn recover_rejects_a_wrong_length_ciphertext() { - let (_, sk) = openssl_keypair().unwrap(); - for len in [0, CT_LEN - 1, CT_LEN + 1] { - assert!(matches!( - RSASVE::decaps(&sk, &vec![0x5Au8; len]), - Err(KEMError::LengthError(_)) - )); + assert!(sk.decaps(&good, ()).is_ok()); } } @@ -406,10 +386,10 @@ rsasve_suite!( ); /// 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_rng` reproduces `serverC` from `serverZ`. +/// 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, RSASVE}; + 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() @@ -433,11 +413,10 @@ fn acvp_kas_ifc_ssc_kas1_2048() { let pk = RSA2048KEMPublicKey::new(&limbs(s("iutN")), e).unwrap(); let c = be_bytes::(s("serverC")); let z = be_bytes::(s("serverZ")); - let recovered = RSASVE::decaps(&sk, &c).unwrap(); + let recovered = sk.decaps(&c, ()).unwrap(); if t["testPassed"].as_bool().unwrap() { assert_eq!(recovered.ref_to_bytes(), &z[..], "tcId {}", t["tcId"]); - let (_, ct) = - RSASVE::encaps_rng(&pk, &mut rng_emitting(z, SecurityStrength::_256bit)).unwrap(); + let (_, ct) = pk.encaps(&mut rng_emitting(z, SecurityStrength::_256bit), ()).unwrap(); assert_eq!(ct, c, "tcId {}", t["tcId"]); passed += 1; } else { @@ -452,7 +431,7 @@ fn acvp_kas_ifc_ssc_kas1_2048() { /// direction per case. #[test] fn acvp_kas_ifc_ssc_kas2_3072() { - use bouncycastle_rsa::rsa_3072::{CT_LEN, RSA3072KEMPrivateKey, RSA3072KEMPublicKey, RSASVE}; + 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() @@ -489,12 +468,11 @@ fn acvp_kas_ifc_ssc_kas2_3072() { for (pk, sk, c, z) in directions { let c = be_bytes::(c); let z = be_bytes::(z); - let recovered = RSASVE::decaps(sk, &c).unwrap(); + let recovered = sk.decaps(&c, ()).unwrap(); if ok { assert_eq!(recovered.ref_to_bytes(), &z[..], "tcId {}", t["tcId"]); let (_, ct) = - RSASVE::encaps_rng(pk, &mut rng_emitting(z, SecurityStrength::_256bit)) - .unwrap(); + 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"]); @@ -516,7 +494,7 @@ macro_rules! acvp_rsadp { ($name:ident, $size:ident, $bits:literal, $L:literal, $HALF:literal) => { #[test] fn $name() { - use bouncycastle_rsa::$size::{CT_LEN, RSASVE}; + use bouncycastle_rsa::$size::CT_LEN; type SK = bouncycastle_rsa::rsasve::RsaKEMPrivateKey<$L, $HALF>; let d = get_test_data("acvp/RSA-DecryptionPrimitive-Sp800-56Br2.json"); let group = d["testGroups"] @@ -540,7 +518,7 @@ macro_rules! acvp_rsadp { if t["testPassed"].as_bool().unwrap() { let pt = be_bytes::(s("pt")); assert_eq!( - RSASVE::decaps(&sk, &ct).unwrap().ref_to_bytes(), + sk.decaps(&ct, ()).unwrap().ref_to_bytes(), &pt[..], "tcId {}", t["tcId"] @@ -548,7 +526,7 @@ macro_rules! acvp_rsadp { passed += 1; } else { assert!( - matches!(RSASVE::decaps(&sk, &ct), Err(KEMError::DecapsulationFailed)), + matches!(sk.decaps(&ct, ()), Err(KEMError::DecapsulationFailed)), "tcId {}", t["tcId"] ); @@ -573,8 +551,8 @@ fn keygen_produces_working_kem_keys() { let (pk, sk) = RSASVE::keygen(&mut DefaultRNG::default()).unwrap(); assert_eq!(pk.e(), 65537); assert_eq!(pk.n(), sk.n()); - let (ss, ct) = RSASVE::encaps(&pk).unwrap(); - assert_eq!(RSASVE::decaps(&sk, &ct).unwrap(), ss); + 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 @@ -604,8 +582,8 @@ macro_rules! kem_keygen_round_trip { let (pk, sk) = RSASVE::keygen(&mut DefaultRNG::default()).unwrap(); assert_eq!(pk.e(), 65537); assert_eq!(pk.n(), sk.n()); - let (ss, ct) = RSASVE::encaps(&pk).unwrap(); - assert_eq!(RSASVE::decaps(&sk, &ct).unwrap(), ss); + let (ss, ct) = pk.encaps(&mut DefaultRNG::default(), ()).unwrap(); + assert_eq!(sk.decaps(&ct, ()).unwrap(), ss); } }; } From 16b6265ec082fb1ca849a74187b09913e7b7c623 Mon Sep 17 00:00:00 2001 From: David Hook Date: Sun, 8 Nov 2026 16:05:31 +1100 Subject: [PATCH 30/55] cli: the rsasve-* commands run through the KEM key roles, sharing mlkem's ciphertext reader Assisted-by: Claude:claude-mythos-5-1 --- cli/src/mlkem_cmd.rs | 5 ++++- cli/src/rsasve_cmd.rs | 26 ++++++++++++-------------- 2 files changed, 16 insertions(+), 15 deletions(-) diff --git a/cli/src/mlkem_cmd.rs b/cli/src/mlkem_cmd.rs index 4f1a4350..605ff050 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/rsasve_cmd.rs b/cli/src/rsasve_cmd.rs index 51743d9c..96c3c1d6 100644 --- a/cli/src/rsasve_cmd.rs +++ b/cli/src/rsasve_cmd.rs @@ -1,7 +1,7 @@ //! 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 `KEMEncapsulator`/`KEMDecapsulator` traits, is monomorphised once per size. +//! 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; @@ -23,10 +23,9 @@ use crate::helpers::{ write_bytes_or_hex_to_file, }; use bouncycastle::core::errors::KEMError; +use bouncycastle::core::kem_key::{DecapsulatingKey, EncapsulatingKey}; use bouncycastle::core::key_material::KeyMaterialTrait; -use bouncycastle::core::traits::{ - KEMDecapsulator, KEMEncapsulator, KEMPrivateKey, KEMPublicKey, RNG, -}; +use bouncycastle::core::traits::{KEMPrivateKey, KEMPublicKey, RNG}; use bouncycastle::rng::HashDRBG_SHA512; use bouncycastle::rsa::{rsa_2048, rsa_3072, rsa_4096, rsa_8192}; use clap::ValueEnum; @@ -59,9 +58,8 @@ fn require_secret(file: &Option, flag_name: &str) -> crate::helpers::Sec /// One modulus size's RSASVE, per `action`. fn rsasve_cmd< - PK: KEMPublicKey, - SK: KEMPrivateKey, - K: KEMEncapsulator + KEMDecapsulator, + PK: KEMPublicKey + EncapsulatingKey<(), CT_LEN, SS_LEN>, + SK: KEMPrivateKey + DecapsulatingKey<(), CT_LEN, SS_LEN>, const PK_LEN: usize, const SK_LEN: usize, const CT_LEN: usize, @@ -99,7 +97,7 @@ fn rsasve_cmd< ); exit(-1); }); - let (ss, ct) = K::encaps(&pk).unwrap_or_else(|e| { + let (ss, ct) = pk.encaps(&mut HashDRBG_SHA512::new_from_os(), ()).unwrap_or_else(|e| { eprintln!("Error: {alg_name} encapsulation failed: {e:?}"); exit(-1); }); @@ -123,8 +121,8 @@ fn rsasve_cmd< ); exit(-1); }); - // `decaps` reports a wrong-length ciphertext itself (as `LengthError`). - let ss = K::decaps(&sk, &read_input_file_or_stdin(ctfile)).unwrap_or_else(|e| { + 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); }); @@ -143,7 +141,7 @@ pub(crate) fn rsasve_2048_cmd( use rsa_2048::{ CT_LEN, PK_LEN, RSA2048KEMPrivateKey, RSA2048KEMPublicKey, RSASVE, SK_LEN, SS_LEN, }; - rsasve_cmd::( + rsasve_cmd::( action, RSASVE::keygen, skfile, @@ -164,7 +162,7 @@ pub(crate) fn rsasve_3072_cmd( use rsa_3072::{ CT_LEN, PK_LEN, RSA3072KEMPrivateKey, RSA3072KEMPublicKey, RSASVE, SK_LEN, SS_LEN, }; - rsasve_cmd::( + rsasve_cmd::( action, RSASVE::keygen, skfile, @@ -185,7 +183,7 @@ pub(crate) fn rsasve_4096_cmd( use rsa_4096::{ CT_LEN, PK_LEN, RSA4096KEMPrivateKey, RSA4096KEMPublicKey, RSASVE, SK_LEN, SS_LEN, }; - rsasve_cmd::( + rsasve_cmd::( action, RSASVE::keygen, skfile, @@ -206,7 +204,7 @@ pub(crate) fn rsasve_8192_cmd( use rsa_8192::{ CT_LEN, PK_LEN, RSA8192KEMPrivateKey, RSA8192KEMPublicKey, RSASVE, SK_LEN, SS_LEN, }; - rsasve_cmd::( + rsasve_cmd::( action, RSASVE::keygen, skfile, From a660320b70b0f038f19047ab3a7aac0384965097 Mon Sep 17 00:00:00 2001 From: David Hook Date: Sun, 8 Nov 2026 16:05:31 +1100 Subject: [PATCH 31/55] mem_usage_benches: the RSASVE harness calls the key roles Assisted-by: Claude:claude-mythos-5-1 --- mem_usage_benches/src/bench_rsa_mem_usage.rs | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/mem_usage_benches/src/bench_rsa_mem_usage.rs b/mem_usage_benches/src/bench_rsa_mem_usage.rs index 33dc730b..935dee09 100644 --- a/mem_usage_benches/src/bench_rsa_mem_usage.rs +++ b/mem_usage_benches/src/bench_rsa_mem_usage.rs @@ -30,11 +30,11 @@ #![allow(dead_code)] #![allow(unused_imports)] +use bouncycastle::core::kem_key::{DecapsulatingKey, EncapsulatingKey}; use bouncycastle::core::key_material::KeyMaterialTrait; use bouncycastle::core::signature_key::{DeterministicSigningKey, SigningKey, VerifyingKey}; use bouncycastle::core::traits::{ - KEMDecapsulator, KEMEncapsulator, KEMPrivateKey, KEMPublicKey, SignaturePrivateKey, - SignaturePublicKey, + KEMPrivateKey, KEMPublicKey, SignaturePrivateKey, SignaturePublicKey, }; use bouncycastle::rng::DefaultRNG; use bouncycastle::rsa::{rsa_1024, rsa_1536, rsa_2048, rsa_3072, rsa_4096, rsa_8192}; @@ -365,7 +365,7 @@ fn bench_2048_rsasve_encaps() { let sk = genuine_2048_key(); let pk = rsa_2048::RSA2048PublicKey::new(sk.n(), 0x10001).unwrap(); let pk = rsa_2048::RSA2048KEMPublicKey::from_bytes(&pk.encode()).unwrap(); - let (ss, ct) = rsa_2048::RSASVE::encaps(&pk).unwrap(); + let (ss, ct) = pk.encaps(&mut DefaultRNG::default(), ()).unwrap(); println!("{:x?}", ct); println!("{}", ss.key_len()); } @@ -377,7 +377,7 @@ fn bench_2048_rsasve_decaps() { let sk = rsa_2048::RSA2048KEMPrivateKey::from_bytes(&genuine_2048_key().encode()).unwrap(); let mut ct = [0x5Au8; rsa_2048::CT_LEN]; ct[0] = 0x01; // well inside (1, n - 1) - let ss = rsa_2048::RSASVE::decaps(&sk, &ct).unwrap(); + let ss = sk.decaps(&ct, ()).unwrap(); println!("{}", ss.key_len()); } @@ -388,7 +388,7 @@ fn bench_8192_rsasve_encaps() { let sk = genuine_8192_key(); let pk = rsa_8192::RSA8192PublicKey::new(sk.n(), 0x10001).unwrap(); let pk = rsa_8192::RSA8192KEMPublicKey::from_bytes(&pk.encode()).unwrap(); - let (ss, ct) = rsa_8192::RSASVE::encaps(&pk).unwrap(); + let (ss, ct) = pk.encaps(&mut DefaultRNG::default(), ()).unwrap(); println!("{:x?}", ct); println!("{}", ss.key_len()); } @@ -400,7 +400,7 @@ fn bench_8192_rsasve_decaps() { let sk = rsa_8192::RSA8192KEMPrivateKey::from_bytes(&genuine_8192_key().encode()).unwrap(); let mut ct = [0x5Au8; rsa_8192::CT_LEN]; ct[0] = 0x01; // well inside (1, n - 1) - let ss = rsa_8192::RSASVE::decaps(&sk, &ct).unwrap(); + let ss = sk.decaps(&ct, ()).unwrap(); println!("{}", ss.key_len()); } From 00c4b9896a734ad5266994712504f1bd5972a664 Mon Sep 17 00:00:00 2001 From: David Hook Date: Sun, 8 Nov 2026 16:10:48 +1100 Subject: [PATCH 32/55] rsa: the crate docs name the key roles, not the Signer/SignatureVerifier types the port replaced Assisted-by: Claude:claude-mythos-5-1 --- crypto/rsa/src/lib.rs | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/crypto/rsa/src/lib.rs b/crypto/rsa/src/lib.rs index e33f23e2..57f1a659 100644 --- a/crypto/rsa/src/lib.rs +++ b/crypto/rsa/src/lib.rs @@ -184,8 +184,8 @@ //! 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 also implements `bouncycastle_core`'s -//! `Signer`/`SignatureVerifier` traits (see `# Scope`), exercised through +//! own tests for the specifics at each size. Every pairing is a marker 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 @@ -235,9 +235,8 @@ //! 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 `L`, not by which hash or scheme fed into -//! RSASP1/RSAVP1's modular exponentiation. A `Signer`/`SignatureVerifier` streaming state -//! (`RSASSA_*` in each size module) additionally holds a clone of its key for its lifetime -- -//! the "SK size in memory" column, for a signer -- plus the hash state. +//! RSASP1/RSAVP1's modular exponentiation. A `SignatureSigner` / `SignatureVerifier` worker +//! borrows its key for its lifetime and holds the hash state beside it. //! //! # Security Considerations //! From eb4aefd59ad5fbf844cfbd747ba16d1def6b26bf Mon Sep 17 00:00:00 2001 From: David Hook Date: Fri, 13 Nov 2026 07:57:20 +1100 Subject: [PATCH 33/55] Merging fix/rsa-size-markers, which writes the RSA crate once per scheme over a modulus-size marker and gives RSASVE a KDF pairing: the six per-size modules each expanded the key types, the three signature schemes at every hash and RSASVE through macros over up to twelve const parameters, so a scheme was six copies and a signature of it unreadable. The size is now a marker type, RSA1024, RSA1536, RSA2048, RSA3072, RSA4096 and RSA8192 at the crate root, implementing size::RsaSize (the lengths as consts, the limb and byte arrays as associated types through a small Array trait, and forwarders to the public-key arithmetic at that width) and, from 2048 up, size::RsaSigningSize (FIPS 186-5 Table B.1's Miller-Rabin rounds, keygen, and the private key's arithmetic: the CRT exponentiation, the prime-width codecs and comparison, and the modulus from its primes), the latter the compile-time form of the crate's rule that RSA-1024 and RSA-1536 verify only: the private key's constructors and encoder, the signing roles, rsasp1, RSASVE's key generation and the KEM private key are all on impl, so no private key value and no private-key arithmetic exists at the two legacy sizes. The keys are RsaPublicKey and RsaPrivateKey, the schemes RSASSA_PKCS1_v1_5, RSASSA_PSS and RSASSA_PSS_SHAKE, named by scheme and hash through utils' ConstStr ("RSASSA-PSS-SHA256") at the lesser of the modulus's and the hash's strength, and the KEM RSASVE ("RSASVE-2048") over RsaKEMPublicKey and RsaKEMPrivateKey; the role traits that name a [u8; N] are implemented once each over an equality bound on the marker's array type, as the ECDSA and ML-DSA crates do, so a call needs no annotation beyond the algorithm; size::SignatureKeyPair and size::KemKeyPair hang the two generators on a signing size's marker. RSASP1 and RSAVP1 are rsasp1:: and rsavp1::; MGF1 and the EMSA encoders take the digest as a slice and the modulus length as the one const they need; the PSS signers hold the salt in a buffer sized for the largest hash. The per-size modules stay as alias modules (rsa_2048::RSASSA_PSS_SHA256 is RSASSA_PSS, RSA2048PrivateKey is RsaPrivateKey, SIG_LEN is RSA2048::K_LEN), so the CLI, the benches, the stack harness and every known-answer suite are unchanged in what they exercise. One behaviour is dropped: a private key built from CRT components of the wrong width was a decoding error at run time and is now a type error. RSASVE gains the pairing the KDF description was made for: SP 800-56B Rev. 2 passes the secret value Z through a key-derivation method (its Section 5.5) before any use, and rsasve_kdf.rs gives the key-establishment keys the KEM roles a second time over KdfParams<'p, HkdfDescription<'s, H>, SS_LEN>, the shape the ML-KEM pairings have: RSASVE_HKDF, named "RSASVE--HKDF-" at the lesser of the size's and the hash's strength, for any modulus size and any HMAC hash since the parameter type is the library's description and nothing foreign can be paired; the workers run RSASVE.GENERATE or RSASVE.RECOVER for Z into one local zeroized when it drops, build the HKDF engine from the description, derive the key of the length the parameters name (one byte to 255 hash outputs, checked at compile time where a worker is made) and cap its label at the algorithm's strength, with a ciphertext for a key the caller never got cleared and the caller's buffer left zeroized on every error; the description's salt and the info are what a token key reads to hand its device the same derivation. No CLI subcommand yet: the rsasve-* commands hand out the raw Z as before. Tests: the RSASVE suite's macros take the marker and the direct generic calls name it; rsasve_hkdf_tests runs the core framework KEM suite over RSA-2048 with HKDF-SHA256 and HKDF-SHA512, the derivation against HKDF by hand over the raw Z (the crate's example key, so no key generation), another info and the absent salt, the prefix and maximum lengths, the refused ciphertext, and the names and strengths at three sizes; keys_tests checks the CRT range checks at every signing size, the RSA-1024 and RSA-1536 suites the out-of-range signature representative through their own range check, and rsassa_worker_tests the three schemes' workers naming their algorithm and PSS's random-salt sign_from_hash drawing a fresh salt that verifies. Verified: the rsa suite (the 4096 and 8192 keygens still #[ignore]d), the rsa doctests, the cli suite, the all-targets build, nightly rustfmt, clippy adding nothing on the changed lines, rustdoc with warnings denied on the crate apart from modexp.rs's pre-existing private-item links. Mutants on apollo, scoped to the crate's sources against the subset of its suites the earlier runs validated: 1168 (639 caught, 362 unviable, 25 timeouts, 142 missed: keygen.rs's 65, where bounds were the only change and the file's mutants are the slow, nondeterministic ones documented before; the check_lengths and len_check const assertions; emsa_pkcs1_v1_5's checks noted as equivalent at their sites and MAX_T_LEN's arithmetic; the PSS encoders' step 3 length check that no modulus here reaches and their 8 * K_LEN arithmetic; mgf1's block count; modexp's disjoint-bit ORs; the defensive length checks in the KDF derivations; rsasve's kem_error arms, covered by the keygen test the scoped run skips; and the forwarders, worker names and random-salt entry points the final commit's tests close). Assisted-by: Claude:claude-mythos-5-1 --- crypto/rsa/Cargo.toml | 2 + crypto/rsa/src/emsa_pkcs1_v1_5.rs | 90 +- crypto/rsa/src/emsa_pss.rs | 128 ++- crypto/rsa/src/emsa_pss_shake.rs | 127 ++- crypto/rsa/src/keygen.rs | 12 +- crypto/rsa/src/keys.rs | 353 ++++---- crypto/rsa/src/lib.rs | 95 ++- crypto/rsa/src/mgf1.rs | 47 +- crypto/rsa/src/rsa_1024.rs | 80 +- crypto/rsa/src/rsa_1536.rs | 65 +- crypto/rsa/src/rsa_2048.rs | 242 ++---- crypto/rsa/src/rsa_3072.rs | 227 ++--- crypto/rsa/src/rsa_4096.rs | 227 ++--- crypto/rsa/src/rsa_8192.rs | 222 ++--- crypto/rsa/src/rsa_core.rs | 134 ++- crypto/rsa/src/rsassa_pkcs1_v1_5.rs | 473 +++-------- crypto/rsa/src/rsassa_pss.rs | 784 +++--------------- crypto/rsa/src/rsassa_pss_shake.rs | 742 +++-------------- crypto/rsa/src/rsasve.rs | 535 +++++------- crypto/rsa/src/rsasve_kdf.rs | 219 +++++ crypto/rsa/src/size.rs | 601 ++++++++++++++ crypto/rsa/tests/keys_tests.rs | 107 ++- crypto/rsa/tests/rsa_1024_tests.rs | 12 + crypto/rsa/tests/rsa_1536_tests.rs | 12 + crypto/rsa/tests/rsa_2048_pkcs1_v1_5_tests.rs | 5 +- .../rsa/tests/rsa_2048_pss_shake128_tests.rs | 19 +- crypto/rsa/tests/rsa_2048_pss_tests.rs | 19 +- crypto/rsa/tests/rsassa_worker_tests.rs | 108 +++ crypto/rsa/tests/rsasve_hkdf_tests.rs | 149 ++++ crypto/rsa/tests/rsasve_tests.rs | 69 +- 30 files changed, 2493 insertions(+), 3412 deletions(-) create mode 100644 crypto/rsa/src/rsasve_kdf.rs create mode 100644 crypto/rsa/src/size.rs create mode 100644 crypto/rsa/tests/rsassa_worker_tests.rs create mode 100644 crypto/rsa/tests/rsasve_hkdf_tests.rs diff --git a/crypto/rsa/Cargo.toml b/crypto/rsa/Cargo.toml index ae675a3f..129c3a81 100644 --- a/crypto/rsa/Cargo.toml +++ b/crypto/rsa/Cargo.toml @@ -6,6 +6,8 @@ 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-sha2.workspace = true bouncycastle-sha3.workspace = true diff --git a/crypto/rsa/src/emsa_pkcs1_v1_5.rs b/crypto/rsa/src/emsa_pkcs1_v1_5.rs index f52a13a8..3f71f701 100644 --- a/crypto/rsa/src/emsa_pkcs1_v1_5.rs +++ b/crypto/rsa/src/emsa_pkcs1_v1_5.rs @@ -25,18 +25,19 @@ use bouncycastle_core::traits::{AlgorithmOID, HashAlgParams}; /// support (SHA-3's largest output is 64 bytes), so each is a single length byte, not the /// multi-byte long form; `debug_assert`'d, since it can only fail on a hash this crate does not /// support, never on real input. -fn digest_info( - digest: &[u8; H_LEN], -) -> [u8; T_LEN] { - debug_assert_eq!(H_LEN, H::OUTPUT_LEN, "digest_info: H_LEN must match H::OUTPUT_LEN"); - let oid_der = H::OID_DER; - debug_assert!(oid_der.len() < 128 && H_LEN < 128, "DER length must fit in one byte"); +/// 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 " - debug_assert_eq!(T_LEN, 2 + outer_len, "digest_info: T_LEN must match the computed DER length"); - - let mut t = [0u8; T_LEN]; + 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; @@ -46,40 +47,30 @@ fn digest_info( - digest: &[u8; H_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 t: [u8; T_LEN] = digest_info::(digest); + 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"); + 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); + em[K_LEN - t_len - 1] = 0x00; + em[K_LEN - t_len..].copy_from_slice(&t[..t_len]); em } @@ -99,7 +90,7 @@ fn short_form_len(bytes: &[u8], pos: usize) -> Option { /// [`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; H_LEN]) -> bool { +fn decode_digest_info(t: &[u8], digest: &[u8]) -> bool { let mut pos = 0; if t.first() != Some(&0x30) { return false; @@ -149,7 +140,7 @@ fn decode_digest_info(t: &[u8], digest: &[u // 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 != H_LEN || pos + digest_len != t.len() { + if digest_len != digest.len() || pos + digest_len != t.len() { return false; } @@ -169,8 +160,8 @@ fn decode_digest_info(t: &[u8], digest: &[u /// 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; H_LEN], +pub fn emsa_pkcs1_v1_5_verify_from_hash( + digest: &[u8], em: &[u8; K_LEN], ) -> bool { if em[0] != 0x00 || em[1] != 0x01 { @@ -193,7 +184,7 @@ pub fn emsa_pkcs1_v1_5_verify_from_hash(&em[i + 1..], digest) + decode_digest_info::(&em[i + 1..], digest) } #[cfg(test)] @@ -215,20 +206,23 @@ mod tests { 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) + 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) + emsa_pkcs1_v1_5_verify_from_hash::(&digest, em) } #[test] fn digest_info_matches_rfc8017_sha256_prefix() { let digest = [0xabu8; 32]; - let t = digest_info::(&digest); + 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, @@ -241,7 +235,10 @@ mod tests { #[test] fn digest_info_matches_rfc8017_sha384_prefix() { let digest = [0xcdu8; 48]; - let t = digest_info::(&digest); + 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, @@ -254,7 +251,10 @@ mod tests { #[test] fn digest_info_matches_rfc8017_sha512_prefix() { let digest = [0xefu8; 64]; - let t = digest_info::(&digest); + 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, diff --git a/crypto/rsa/src/emsa_pss.rs b/crypto/rsa/src/emsa_pss.rs index f5292bee..e812af8d 100644 --- a/crypto/rsa/src/emsa_pss.rs +++ b/crypto/rsa/src/emsa_pss.rs @@ -10,8 +10,8 @@ //! 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::mgf1; -use bouncycastle_core::traits::HashOneShot; +use crate::mgf1::{MAX_HASH_LEN, mgf1}; +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 @@ -22,69 +22,65 @@ use bouncycastle_core::traits::HashOneShot; /// 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. -pub fn emsa_pss_encode_from_hash< - H: HashOneShot, - const H_LEN: usize, - const SEED_LEN: usize, - const S_LEN: usize, - const M_PRIME_LEN: usize, - const DB_LEN: usize, - const K_LEN: usize, ->( - m_hash: &[u8; H_LEN], - salt: &[u8; S_LEN], +/// 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 = H::OUTPUT_LEN` bytes here, the "typical" choice +/// of §9.1 note 4), 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] { - debug_assert_eq!(M_PRIME_LEN, 8 + H_LEN + S_LEN, "emsa_pss_encode: M_PRIME_LEN mismatch"); - debug_assert_eq!(DB_LEN, K_LEN - H_LEN - 1, "emsa_pss_encode: DB_LEN mismatch"); + let h_len = H::OUTPUT_LEN; + let s_len = salt.len(); + debug_assert_eq!(m_hash.len(), h_len, "emsa_pss_encode: mHash is one hash output"); debug_assert!( - K_LEN >= H_LEN + S_LEN + 2, + 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; M_PRIME_LEN]; - m_prime[8..8 + H_LEN].copy_from_slice(m_hash); - m_prime[8 + H_LEN..].copy_from_slice(salt); - let mut h = [0u8; H_LEN]; - H::hash_out(&m_prime, &mut h); + 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 array's initial value). - let mut db = [0u8; DB_LEN]; - db[DB_LEN - S_LEN - 1] = 0x01; - db[DB_LEN - S_LEN..].copy_from_slice(salt); + // 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), then clear the top bit (see module docs). - let db_mask: [u8; DB_LEN] = mgf1::(&h); - let mut masked_db = [0u8; DB_LEN]; - for i in 0..DB_LEN { - masked_db[i] = db[i] ^ db_mask[i]; + let mut db_mask = [0u8; K_LEN]; + mgf1::(&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]; } - masked_db[0] &= 0x7f; + em[0] &= 0x7f; // Step 12: EM = maskedDB || H || 0xbc. - let mut em = [0u8; K_LEN]; - em[..DB_LEN].copy_from_slice(&masked_db); - em[DB_LEN..DB_LEN + H_LEN].copy_from_slice(&h); + 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) from step 4 onward, with `emBits` fixed as -/// [`emsa_pss_encode_from_hash`]'s is and step 2's `mHash = Hash(M)` supplied by the caller the -/// same way. Step 1's message-length limit and step 3's minimum-`emLen` check are not reachable -/// for this crate's fixed sizes, for the same reasons given there. -pub fn emsa_pss_verify_from_hash< - H: HashOneShot, - const H_LEN: usize, - const SEED_LEN: usize, - const S_LEN: usize, - const M_PRIME_LEN: usize, - const DB_LEN: usize, - const K_LEN: usize, ->( - m_hash: &[u8; H_LEN], +/// 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 = H::OUTPUT_LEN`. +pub fn emsa_pss_verify_from_hash( + m_hash: &[u8], em: &[u8; K_LEN], ) -> bool { + let h_len = H::OUTPUT_LEN; + let s_len = h_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; @@ -93,39 +89,33 @@ pub fn emsa_pss_verify_from_hash< if em[0] & 0x80 != 0 { return false; } - // Step 5. - let mut masked_db = [0u8; DB_LEN]; - masked_db.copy_from_slice(&em[..DB_LEN]); - let mut h = [0u8; H_LEN]; - h.copy_from_slice(&em[DB_LEN..DB_LEN + H_LEN]); + let masked_db = &em[..db_len]; + let h = &em[db_len..db_len + h_len]; // Steps 7-9. - let db_mask: [u8; DB_LEN] = mgf1::(&h); - let mut db = [0u8; DB_LEN]; - for i in 0..DB_LEN { - db[i] = masked_db[i] ^ db_mask[i]; + let mut db = [0u8; K_LEN]; + mgf1::(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; + 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 mut salt = [0u8; S_LEN]; - salt.copy_from_slice(&db[DB_LEN - S_LEN..]); + 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; M_PRIME_LEN]; - m_prime[8..8 + H_LEN].copy_from_slice(m_hash); - m_prime[8 + H_LEN..].copy_from_slice(&salt); - let mut h_prime = [0u8; H_LEN]; - H::hash_out(&m_prime, &mut h_prime); - - h == h_prime + 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)] @@ -174,11 +164,11 @@ mod tests { } fn encode(message: &[u8], salt: &[u8; 32]) -> [u8; 256] { - emsa_pss_encode_from_hash::(&m_hash(message), salt) + 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) + emsa_pss_verify_from_hash::(&m_hash(message), em) } #[test] diff --git a/crypto/rsa/src/emsa_pss_shake.rs b/crypto/rsa/src/emsa_pss_shake.rs index d0056e34..d0ee936b 100644 --- a/crypto/rsa/src/emsa_pss_shake.rs +++ b/crypto/rsa/src/emsa_pss_shake.rs @@ -13,74 +13,72 @@ //! SHAKE256) -- already this crate's own "typical" salt-length convention for MGF1-based PSS, so //! no new relationship needs stating. -use bouncycastle_core::traits::{HashOneShot, XOF}; +use crate::mgf1::MAX_HASH_LEN; +use bouncycastle_core::traits::{HashAlgParams, HashOneShot, XOF}; /// EMSA-PSS-ENCODE (RFC 8017 §9.1.1) from step 3 onward with the mask generation function /// replaced by native SHAKE output (RFC 8702 §3.2.1), given steps 1-2's `mHash = Hash(M)` by the /// caller exactly as [`crate::emsa_pss::emsa_pss_encode_from_hash`] is. See the module docs for /// `emBits` and the salt argument. -pub fn emsa_pss_encode_shake_from_hash< - X: XOF + HashOneShot, - const H_LEN: usize, - const S_LEN: usize, - const M_PRIME_LEN: usize, - const DB_LEN: usize, - const K_LEN: usize, ->( - m_hash: &[u8; H_LEN], - salt: &[u8; S_LEN], +/// EMSA-PSS-ENCODE (RFC 8017 §9.1.1) with the XOF `X` as both the hash and the mask generation +/// function (RFC 8702 §3.2.1), from the message hash `m_hash` (`X::OUTPUT_LEN` bytes, the +/// output length §3.2.1 fixes for the XOF) and the salt (`sLen = X::OUTPUT_LEN`), into the +/// `K_LEN`-byte `EM`. +pub fn emsa_pss_encode_shake_from_hash( + m_hash: &[u8], + salt: &[u8], ) -> [u8; K_LEN] { - debug_assert_eq!(M_PRIME_LEN, 8 + H_LEN + S_LEN, "emsa_pss_encode_shake: M_PRIME_LEN mismatch"); - debug_assert_eq!(DB_LEN, K_LEN - H_LEN - 1, "emsa_pss_encode_shake: DB_LEN mismatch"); + let h_len = X::OUTPUT_LEN; + let s_len = salt.len(); + debug_assert_eq!(m_hash.len(), h_len, "emsa_pss_encode_shake: mHash is one output"); debug_assert!( - K_LEN >= H_LEN + S_LEN + 2, + K_LEN >= h_len + s_len + 2, "emsa_pss_encode_shake: 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; M_PRIME_LEN]; - m_prime[8..8 + H_LEN].copy_from_slice(m_hash); - m_prime[8 + H_LEN..].copy_from_slice(salt); - let mut h = [0u8; H_LEN]; - X::hash_out(&m_prime, &mut h); + 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]; + X::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 array's initial value). - let mut db = [0u8; DB_LEN]; - db[DB_LEN - S_LEN - 1] = 0x01; - db[DB_LEN - S_LEN..].copy_from_slice(salt); + // 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 SHAKE itself in place of MGF1 (RFC 8702 - // SS3.2.1), then clear the top bit (see module docs). - let mut db_mask = [0u8; DB_LEN]; - X::default().xof_out(&h, &mut db_mask); - let mut masked_db = [0u8; DB_LEN]; - for i in 0..DB_LEN { - masked_db[i] = db[i] ^ db_mask[i]; + // §3.2.1), then clear the top bit (see module docs). + let mut db_mask = [0u8; K_LEN]; + X::default().xof_out(&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]; } - masked_db[0] &= 0x7f; + em[0] &= 0x7f; // Step 12: EM = maskedDB || H || 0xbc. - let mut em = [0u8; K_LEN]; - em[..DB_LEN].copy_from_slice(&masked_db); - em[DB_LEN..DB_LEN + H_LEN].copy_from_slice(&h); + 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) from step 4 onward with the mask generation function -/// replaced by native SHAKE output, as [`emsa_pss_encode_shake_from_hash`], and step 2's -/// `mHash = Hash(M)` supplied by the caller the same way. -pub fn emsa_pss_verify_shake_from_hash< - X: XOF + HashOneShot, - const H_LEN: usize, - const S_LEN: usize, - const M_PRIME_LEN: usize, - const DB_LEN: usize, - const K_LEN: usize, ->( - m_hash: &[u8; H_LEN], +/// EMSA-PSS-VERIFY (RFC 8017 §9.1.2) with the XOF `X` as hash and mask (RFC 8702 §3.2.1), of +/// the `K_LEN`-byte `em` against the message hash `m_hash`, with `sLen = X::OUTPUT_LEN`. +pub fn emsa_pss_verify_shake_from_hash( + m_hash: &[u8], em: &[u8; K_LEN], ) -> bool { + let h_len = X::OUTPUT_LEN; + let s_len = h_len; + debug_assert_eq!(m_hash.len(), h_len, "emsa_pss_verify_shake: mHash is one output"); + 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; @@ -89,40 +87,33 @@ pub fn emsa_pss_verify_shake_from_hash< if em[0] & 0x80 != 0 { return false; } - // Step 5. - let mut masked_db = [0u8; DB_LEN]; - masked_db.copy_from_slice(&em[..DB_LEN]); - let mut h = [0u8; H_LEN]; - h.copy_from_slice(&em[DB_LEN..DB_LEN + H_LEN]); + let masked_db = &em[..db_len]; + let h = &em[db_len..db_len + h_len]; // Steps 7-9. - let mut db_mask = [0u8; DB_LEN]; - X::default().xof_out(&h, &mut db_mask); - let mut db = [0u8; DB_LEN]; - for i in 0..DB_LEN { - db[i] = masked_db[i] ^ db_mask[i]; + let mut db = [0u8; K_LEN]; + X::default().xof_out(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; + 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 mut salt = [0u8; S_LEN]; - salt.copy_from_slice(&db[DB_LEN - S_LEN..]); + 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; M_PRIME_LEN]; - m_prime[8..8 + H_LEN].copy_from_slice(m_hash); - m_prime[8 + H_LEN..].copy_from_slice(&salt); - let mut h_prime = [0u8; H_LEN]; - X::hash_out(&m_prime, &mut h_prime); - - h == h_prime + 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]; + X::hash_out(&m_prime[..8 + h_len + s_len], &mut h_prime[..h_len]); + h == &h_prime[..h_len] } #[cfg(test)] @@ -152,11 +143,11 @@ mod tests { } fn encode(message: &[u8], salt: &[u8; 32]) -> [u8; 256] { - emsa_pss_encode_shake_from_hash::(&m_hash(message), salt) + emsa_pss_encode_shake_from_hash::(&m_hash(message), salt) } fn verify(message: &[u8], em: &[u8; 256]) -> bool { - emsa_pss_verify_shake_from_hash::(&m_hash(message), em) + emsa_pss_verify_shake_from_hash::(&m_hash(message), em) } #[test] diff --git a/crypto/rsa/src/keygen.rs b/crypto/rsa/src/keygen.rs index 7e6c4057..80135672 100644 --- a/crypto/rsa/src/keygen.rs +++ b/crypto/rsa/src/keygen.rs @@ -26,6 +26,7 @@ use crate::keys::{RsaPrivateKey, RsaPublicKey}; 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; @@ -511,11 +512,14 @@ fn primes_too_close(p: &[u64; N], q: &[u64; N]) -> bool { /// `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( +pub fn keygen_from_rng( rng: &mut dyn RNG, rounds: NonZeroUsize, required_strength: SecurityStrength, -) -> Result<(RsaPublicKey, RsaPrivateKey), SignatureError> { +) -> Result<(RsaPublicKey, RsaPrivateKey), 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 { @@ -585,8 +589,8 @@ pub fn keygen_from_rng::from_crt_components(&p, &q, &d_p, &d_q, &q_inv)?; - let pk = RsaPublicKey::::new(sk.n(), PUBLIC_EXPONENT)?; + let sk = RsaPrivateKey::::from_crt_components(&p, &q, &d_p, &d_q, &q_inv)?; + let pk = RsaPublicKey::::new(sk.n(), PUBLIC_EXPONENT)?; return Ok((pk, sk)); } } diff --git a/crypto/rsa/src/keys.rs b/crypto/rsa/src/keys.rs index f541bc49..0e690546 100644 --- a/crypto/rsa/src/keys.rs +++ b/crypto/rsa/src/keys.rs @@ -1,55 +1,48 @@ //! RSA key types: [`RsaPublicKey`] (RFC 8017 §3.1's `(n, e)`) and [`RsaPrivateKey`] (§3.2's //! "second representation", the CRT quintuple `p`, `q`, `dP`, `dQ`, `qInv`), generic over the -//! modulus's limb count `L` and each prime's limb count `HALF`. +//! modulus size [`RsaSize`]. //! -//! Keys come either from [`crate::keygen`] (FIPS 186-5 Appendix A.1.3, via each size module's -//! `keygen`) or from externally supplied key material (e.g. loaded from CAVP/wycheproof test -//! vectors, or a key produced by another implementation) through [`RsaPrivateKey::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. +//! Keys come either from [`crate::keygen`] (FIPS 186-5 Appendix A.1.3, through +//! [`RsaSigningSize::keygen`]) or from externally supplied +//! key material (loaded from CAVP/wycheproof test vectors, or a key produced by another +//! implementation) through [`RsaPrivateKey::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. //! -//! Each concrete modulus size's aliases of these types (`crate::rsa_2048::RSA2048PrivateKey` and -//! siblings) implement `bouncycastle_core`'s `SignaturePrivateKey`/`SignaturePublicKey` traits, -//! in that size's module, with the byte layouts described on each type below; the generic types -//! here only carry the layout's implementation (`encode_raw`/`from_bytes_raw`, crate-private), -//! since the traits' `SK_LEN`/`PK_LEN` are fixed per size and stable Rust cannot derive them from -//! `L`. +//! The key types implement `bouncycastle_core`'s `SignaturePublicKey` / `SignaturePrivateKey`, +//! the private key only at a [`RsaSigningSize`], with the byte +//! layouts described on each type below. -use crate::codec::{be_bytes_from_limbs, limbs_from_be_bytes}; +use crate::size::{RsaSigningSize, RsaSize}; use bouncycastle_core::errors::SignatureError; use bouncycastle_core::security_strength::SecurityStrength; -use bouncycastle_ec::montgomery; -use bouncycastle_ec::nat; -use bouncycastle_utils::secret::{Secret, zeroize_in_place}; +use bouncycastle_core::traits::{SignaturePrivateKey, SignaturePublicKey}; +use bouncycastle_utils::secret::{Secret, ZeroizablePrimitive}; use core::fmt; use core::fmt::{Display, Formatter}; -/// An RSA public key: RFC 8017 §3.1's `(n, e)`. +/// An RSA public key: RFC 8017 §3.1's `(n, e)`, at the size `K`. /// /// # Encoding /// -/// `SignaturePublicKey::encode`/`from_bytes` (implemented per size, e.g. for -/// `crate::rsa_2048::RSA2048PublicKey`) use the raw layout `n || e`: `n` as `8 * L` big-endian -/// bytes (RFC 8017 §4.1's I2OSP), then `e` as 4 big-endian bytes, `PK_LEN = 8 * L + 4` in all. +/// `SignaturePublicKey::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. #[derive(Clone, Debug, PartialEq, Eq)] -pub struct RsaPublicKey { - n: [u64; L], +pub struct RsaPublicKey { + n: K::Limbs, e: u32, } -impl RsaPublicKey { +impl RsaPublicKey { /// Builds a public key from its modulus and exponent. Returns - /// `Err(`[`SignatureError::DecodingError`]`)` if `n` is even, or if `e` is even or less than 3 - /// (RFC 8017 §3.1: "the RSA public exponent e is an integer between 3 and n - 1"; the upper - /// bound is not checked here -- it needs a full multi-limb comparison against `n` for a - /// boundary no key from a real implementation will ever hit). There is no separate all-zero - /// check on `n`: a zero value's low limb is `0`, which the oddness check already rejects. - pub fn new(n: &[u64; L], e: u32) -> Result { - if n[0] & 1 == 0 { + /// `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 { @@ -60,8 +53,8 @@ impl RsaPublicKey { Ok(Self { n: *n, e }) } - /// The modulus `n`. - pub fn n(&self) -> &[u64; L] { + /// The modulus `n`, as little-endian limbs. + pub fn n(&self) -> &K::Limbs { &self.n } @@ -70,47 +63,53 @@ impl RsaPublicKey { self.e } - /// The `# Encoding` layout (see the type's docs), `n || e`, with `N_BYTES = 8 * L` and - /// `PK_LEN = N_BYTES + 4` supplied by the per-size `SignaturePublicKey` impl that wraps this. - pub(crate) fn encode_raw(&self) -> [u8; PK_LEN] { - debug_assert_eq!(N_BYTES, 8 * L, "RsaPublicKey::encode_raw needs N_BYTES == 8 * L"); - debug_assert_eq!( - PK_LEN, - N_BYTES + 4, - "RsaPublicKey::encode_raw needs PK_LEN == N_BYTES + 4" - ); - let mut out = [0u8; PK_LEN]; - out[..N_BYTES].copy_from_slice(&be_bytes_from_limbs::(&self.n)); - out[N_BYTES..].copy_from_slice(&self.e.to_be_bytes()); + /// 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 } - /// Decodes [`Self::encode_raw`]'s layout, validated the same way [`Self::new`] validates - /// `(n, e)`. Takes the exact-length array; the per-size `SignaturePublicKey::from_bytes` that - /// wraps this is where a wrong-length slice is rejected. - pub(crate) fn from_bytes_raw( - bytes: &[u8; PK_LEN], - ) -> Result { - debug_assert_eq!(N_BYTES, 8 * L, "RsaPublicKey::from_bytes_raw needs N_BYTES == 8 * L"); - debug_assert_eq!( - PK_LEN, - N_BYTES + 4, - "RsaPublicKey::from_bytes_raw needs PK_LEN == N_BYTES + 4" - ); - let n_bytes: [u8; N_BYTES] = bytes[..N_BYTES].try_into().expect("N_BYTES-byte slice"); - let n = limbs_from_be_bytes::(&n_bytes); - let e_bytes: [u8; 4] = bytes[N_BYTES..].try_into().expect("4-byte slice"); + /// 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)) } } -/// `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 +impl SignaturePublicKey for RsaPublicKey +where + K: RsaSize, +{ + fn encode(&self) -> [u8; PK_LEN] { + self.encode_raw() + } + + fn encode_out(&self, out: &mut [u8; PK_LEN]) -> usize { + *out = self.encode_raw(); + PK_LEN + } + + fn from_bytes(bytes: &[u8]) -> Result { + let bytes: &[u8; PK_LEN] = bytes.try_into().map_err(|_| { + SignatureError::DecodingError("an RSA public key is the modulus length plus four bytes") + })?; + Self::from_bytes_raw(bytes) + } +} + +/// `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 /// `SignaturePublicKey`'s `Display` supertrait; public data only, so nothing is redacted. -impl Display for RsaPublicKey { +impl Display for RsaPublicKey { fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { - write!(f, "RsaPublicKey<{L}> {{ n: ")?; - for limb in self.n.iter().rev() { + write!(f, "RsaPublicKey<{}> {{ n: ", K::NAME)?; + for limb in self.n.as_ref().iter().rev() { write!(f, "{limb:016x}")?; } write!(f, ", e: {:x} }}", self.e) @@ -118,10 +117,7 @@ impl Display for RsaPublicKey { } /// An RSA private key in RFC 8017 §3.2's CRT ("second representation") form: `p`, `q`, `dP`, -/// `dQ`, `qInv`. `L` (the modulus's limb count) must be exactly `2 * HALF`; like -/// `bouncycastle_ec::montgomery`'s `L2 = 2 * L`, that relationship is enforced at construction -/// (see [`Self::from_crt_components`]) rather than expressed in the type, because stable Rust has -/// no way to compute one const generic from another. +/// `dQ`, `qInv`, at the size `K`, each component a prime-width integer (`K::HalfLimbs`). /// /// `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 @@ -135,74 +131,64 @@ impl Display for RsaPublicKey { /// /// # Encoding /// -/// `SignaturePrivateKey::encode`/`from_bytes` (implemented per size, e.g. for -/// `crate::rsa_2048::RSA2048PrivateKey`) use the raw layout `p || q || dP || dQ || qInv`, each -/// `8 * HALF` big-endian bytes, `SK_LEN = 40 * HALF` 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. +/// `SignaturePrivateKey::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 RsaPrivateKey { - p: Secret<[u64; HALF]>, - q: Secret<[u64; HALF]>, - d_p: Secret<[u64; HALF]>, - d_q: Secret<[u64; HALF]>, - q_inv: Secret<[u64; HALF]>, - /// `n = p * q`, computed once here. Public: `n` is shared with the matching public key (RFC - /// 8017 §3.2, "the RSA modulus n is the same as in the corresponding RSA public key"). - n: [u64; L], +pub struct RsaPrivateKey { + 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, } -impl RsaPrivateKey { - /// Builds a private key from its CRT components. Returns - /// `Err(`[`SignatureError::DecodingError`]`)` if: - /// - /// * `L != 2 * HALF` (a caller programming error -- every concrete instantiation in this - /// crate pairs a fixed `L` with a fixed `HALF`, so this cannot happen through the crate's - /// own public API, only through an explicit, wrong turbofish); - /// * `p` or `q` is even or equal to each other. There is no separate all-zero check: a zero - /// value's low limb is `0`, which the oddness check already rejects. - /// * `dP >= p`, `dQ >= q`, or `qInv >= p` (RFC 8017 §3.2: `dP`/`dQ`/`qInv` are each "a - /// positive integer less than" their modulus). +// 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 RsaPrivateKey { + /// 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: &[u64; HALF], - q: &[u64; HALF], - d_p: &[u64; HALF], - d_q: &[u64; HALF], - q_inv: &[u64; HALF], + p: &K::HalfLimbs, + q: &K::HalfLimbs, + d_p: &K::HalfLimbs, + d_q: &K::HalfLimbs, + q_inv: &K::HalfLimbs, ) -> Result { - if L != 2 * HALF { - return Err(SignatureError::DecodingError("RSA modulus width must be 2 * prime width")); - } - if p[0] & 1 == 0 { + if p.as_ref()[0] & 1 == 0 { return Err(SignatureError::DecodingError("p must be odd")); } - if q[0] & 1 == 0 { + 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 nat::sub(d_p, p).1 != 1 { + if !K::half_is_less(d_p, p) { return Err(SignatureError::DecodingError("dP must be less than p")); } - if nat::sub(d_q, q).1 != 1 { + if !K::half_is_less(d_q, q) { return Err(SignatureError::DecodingError("dQ must be less than q")); } - if nat::sub(q_inv, p).1 != 1 { + if !K::half_is_less(q_inv, p) { return Err(SignatureError::DecodingError("qInv must be less than p")); } - // `L == 2 * HALF` (checked above), so this widening multiply's `L2 = L` output is exactly - // the modulus width -- `p * q` is exact, never reduced, since it is the modulus itself. - let n = montgomery::widening_mul::(p, q); + // `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::default(), - q: Secret::default(), - d_p: Secret::default(), - d_q: Secret::default(), - q_inv: Secret::default(), + p: Secret::new(), + q: Secret::new(), + d_p: Secret::new(), + d_q: Secret::new(), + q_inv: Secret::new(), n, }; *key.p = *p; @@ -212,107 +198,92 @@ impl RsaPrivateKey { *key.q_inv = *q_inv; Ok(key) } +} - /// The modulus `n = p * q`. - pub fn n(&self) -> &[u64; L] { +impl RsaPrivateKey { + /// The modulus `n = p * q`, as little-endian limbs. + pub fn n(&self) -> &K::Limbs { &self.n } - pub(crate) fn p(&self) -> &[u64; HALF] { + pub(crate) fn p(&self) -> &K::HalfLimbs { &self.p } - pub(crate) fn q(&self) -> &[u64; HALF] { + pub(crate) fn q(&self) -> &K::HalfLimbs { &self.q } - pub(crate) fn d_p(&self) -> &[u64; HALF] { + pub(crate) fn d_p(&self) -> &K::HalfLimbs { &self.d_p } - pub(crate) fn d_q(&self) -> &[u64; HALF] { + pub(crate) fn d_q(&self) -> &K::HalfLimbs { &self.d_q } - pub(crate) fn q_inv(&self) -> &[u64; HALF] { + pub(crate) fn q_inv(&self) -> &K::HalfLimbs { &self.q_inv } +} - /// The `# Encoding` layout (see the type's docs), `p || q || dP || dQ || qInv`, with - /// `HALF_BYTES = 8 * HALF` and `SK_LEN = 5 * HALF_BYTES` supplied by the per-size - /// `SignaturePrivateKey` impl that wraps this. - pub(crate) fn encode_raw(&self) -> [u8; SK_LEN] { - debug_assert_eq!( - HALF_BYTES, - 8 * HALF, - "RsaPrivateKey::encode_raw needs HALF_BYTES == 8 * HALF" - ); - debug_assert_eq!( - SK_LEN, - 5 * HALF_BYTES, - "RsaPrivateKey::encode_raw needs SK_LEN == 5 * HALF_BYTES" - ); - let mut out = [0u8; SK_LEN]; - out[..HALF_BYTES].copy_from_slice(&be_bytes_from_limbs::(&self.p)); - out[HALF_BYTES..2 * HALF_BYTES] - .copy_from_slice(&be_bytes_from_limbs::(&self.q)); - out[2 * HALF_BYTES..3 * HALF_BYTES] - .copy_from_slice(&be_bytes_from_limbs::(&self.d_p)); - out[3 * HALF_BYTES..4 * HALF_BYTES] - .copy_from_slice(&be_bytes_from_limbs::(&self.d_q)); - out[4 * HALF_BYTES..] - .copy_from_slice(&be_bytes_from_limbs::(&self.q_inv)); +impl RsaPrivateKey { + /// 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 } - /// Decodes [`Self::encode_raw`]'s layout, validated the same way - /// [`Self::from_crt_components`] validates its five components. Takes the exact-length array; - /// the per-size `SignaturePrivateKey::from_bytes` that wraps this is where a wrong-length - /// slice is rejected. - pub(crate) fn from_bytes_raw( - bytes: &[u8; SK_LEN], - ) -> Result { - debug_assert_eq!( - HALF_BYTES, - 8 * HALF, - "RsaPrivateKey::from_bytes_raw needs HALF_BYTES == 8 * HALF" - ); - debug_assert_eq!( - SK_LEN, - 5 * HALF_BYTES, - "RsaPrivateKey::from_bytes_raw needs SK_LEN == 5 * HALF_BYTES" - ); - // Borrowed, not copied: the caller's buffer is the one copy of the encoding. - let p_bytes: &[u8; HALF_BYTES] = bytes[..HALF_BYTES].try_into().expect("HALF_BYTES bytes"); - let q_bytes: &[u8; HALF_BYTES] = - bytes[HALF_BYTES..2 * HALF_BYTES].try_into().expect("HALF_BYTES bytes"); - let d_p_bytes: &[u8; HALF_BYTES] = - bytes[2 * HALF_BYTES..3 * HALF_BYTES].try_into().expect("HALF_BYTES bytes"); - let d_q_bytes: &[u8; HALF_BYTES] = - bytes[3 * HALF_BYTES..4 * HALF_BYTES].try_into().expect("HALF_BYTES bytes"); - let q_inv_bytes: &[u8; HALF_BYTES] = - bytes[4 * HALF_BYTES..].try_into().expect("HALF_BYTES bytes"); + /// 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) + } +} + +impl SignaturePrivateKey for RsaPrivateKey +where + K: RsaSigningSize + RsaSize, +{ + fn encode(&self) -> [u8; SK_LEN] { + self.encode_raw() + } + + fn encode_out(&self, out: &mut [u8; SK_LEN]) -> usize { + *out = self.encode_raw(); + SK_LEN + } - let mut p = limbs_from_be_bytes::(p_bytes); - let mut q = limbs_from_be_bytes::(q_bytes); - let mut d_p = limbs_from_be_bytes::(d_p_bytes); - let mut d_q = limbs_from_be_bytes::(d_q_bytes); - let mut q_inv = limbs_from_be_bytes::(q_inv_bytes); - let key = Self::from_crt_components(&p, &q, &d_p, &d_q, &q_inv); - // The five decoded components now live in the key's `Secret` fields (or the decoding was - // rejected); either way these copies are scrubbed before returning. - zeroize_in_place(&mut p); - zeroize_in_place(&mut q); - zeroize_in_place(&mut d_p); - zeroize_in_place(&mut d_q); - zeroize_in_place(&mut q_inv); - key + fn from_bytes(bytes: &[u8]) -> Result { + let bytes: &[u8; SK_LEN] = bytes.try_into().map_err(|_| { + SignatureError::DecodingError( + "an RSA private key is five components of half the modulus length", + ) + })?; + Self::from_bytes_raw(bytes) } } -/// The security strength SP 800-57 Part 1 Rev. 5 Table 2 assigns a modulus of `limbs` 64-bit -/// limbs: 2048 bits give 112, 3072 give 128 (4096 rounds down to the same), 7680 and above give -/// 192; anything narrower is below the table and reports [`SecurityStrength::None`]. +/// 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 { diff --git a/crypto/rsa/src/lib.rs b/crypto/rsa/src/lib.rs index 57f1a659..391756b6 100644 --- a/crypto/rsa/src/lib.rs +++ b/crypto/rsa/src/lib.rs @@ -9,42 +9,59 @@ //! # Scope //! //! Signature schemes, plus RSASVE as a KEM ([`rsasve`]; see below). There is no RSAES-OAEP or -//! RSAES-PKCS1-v1_5 encryption, and so no KTS-OAEP. Modulus sizes 2048 -//! through 8192 bits ([`rsa_2048`], [`rsa_3072`], [`rsa_4096`], [`rsa_8192`]) support both signing -//! and verification; 1024- and 1536-bit moduli ([`rsa_1024`], [`rsa_1536`]) support verification -//! only, enforced by the absence of a private-key type (and so of any signing-role impl) for -//! those sizes rather than a runtime check. -//! -//! Every (scheme, hash, modulus size) pairing is an algorithm marker type -//! (`RSASSA_PKCS1_v1_5_SHA256` and siblings in each size module) that the key role traits of -//! [`bouncycastle_core::signature_key`] are implemented over: the private key signs through +//! RSAES-PKCS1-v1_5 encryption, and so no KTS-OAEP. 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) and +//! [`RSASSA_PSS_SHAKE`](rsassa_pss_shake::RSASSA_PSS_SHAKE), named by scheme and hash +//! (`RSASSA-PSS-SHA256`) at the lesser of the modulus's and the hash's strength, and the keys +//! are [`RsaPublicKey`](keys::RsaPublicKey) and [`RsaPrivateKey`](keys::RsaPrivateKey). +//! The key role traits of [`bouncycastle_core::signature_key`] are implemented over every +//! pairing: the private key signs through //! [`SigningKey`](bouncycastle_core::signature_key::SigningKey) for RSASSA-PSS (a fresh salt from //! the caller's RNG per signer) and //! [`DeterministicSigningKey`](bouncycastle_core::signature_key::DeterministicSigningKey) for //! RSASSA-PKCS1-v1_5, and the public key verifies through //! [`VerifyingKey`](bouncycastle_core::signature_key::VerifyingKey); one-shot or streaming, the //! same API shape as this workspace's ECDSA, SM2 and ML-DSA crates. One key type serves every -//! scheme and hash, so a call names the marker: `SigningKey::::sign(&sk, -//! &mut rng, msg, None)`. The key types implement -//! [`SignaturePrivateKey`](bouncycastle_core::traits::SignaturePrivateKey)/[`SignaturePublicKey`](bouncycastle_core::traits::SignaturePublicKey) -//! per size, and each signing size's module offers `keygen(rng)` (FIPS 186-5 Appendix A.1.3, in -//! [`keygen`]), as the ECDSA crate's curves do. The generic `rsassa_*` modules also expose -//! `*_from_hash` entry points that take the message hash rather than the message, for a caller -//! that already holds the digest. +//! scheme and hash, so a call names the algorithm: `SigningKey::, +//! 256>::sign(&sk, &mut rng, msg, None)`. The key types implement +//! [`SignaturePrivateKey`](bouncycastle_core::traits::SignaturePrivateKey)/[`SignaturePublicKey`](bouncycastle_core::traits::SignaturePublicKey), +//! and a signing size generates a pair through [`RsaSigningSize::keygen`](size::RsaSigningSize::keygen) +//! or [`size::SignatureKeyPair`] (`RSA2048::generate_signature_key_pair(&mut rng)`, FIPS 186-5 +//! Appendix A.1.3, in [`keygen`]). The `rsassa_*` modules also expose `*_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`, `RSA2048PrivateKey` is +//! `RsaPrivateKey`, `SIG_LEN` is `RSA2048::K_LEN`), for code that works at one size. //! //! 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` in each of the 2048/3072/4096/8192 size modules. +//! 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 (`RSA2048KEMPrivateKey`/`RSA2048KEMPublicKey` and siblings), which are -//! kept apart from the signing key types; see [`rsasve`]'s `# Key separation`. Key generation is -//! `RSASVE::keygen(rng)`, the same FIPS 186-5 generator the signature keys use. The -//! shared secret is RSASVE's raw secret value `Z`, the full modulus length. It is not a derived key. +//! 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 ([`rsa_2048`]), the way -//! code written against those traits (and this workspace's CLI) uses every signature scheme: +//! 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: //! //! ``` //! use bouncycastle_core::signature_key::{DeterministicSigningKey, SigningKey, VerifyingKey}; @@ -164,6 +181,18 @@ //! .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()); @@ -184,9 +213,10 @@ //! 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 a marker the key types' `SigningKey` -//! / `DeterministicSigningKey` / `VerifyingKey` roles name (see `# Scope`), exercised through -//! `bouncycastle_core_test_framework`'s shared signature conformance suite at each size. +//! 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 @@ -195,7 +225,8 @@ //! ([`rsa_2048`], [`rsa_3072`]) and SHAKE256 with RSA-4096 ([`rsa_4096`]), each validated against //! its own genuine Wycheproof `rsa_pss_*_shake*_test.json` vectors. //! -//! RSASVE ([`rsasve`]) is implemented at 2048/3072/4096/8192. It is validated against NIST +//! 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 @@ -212,7 +243,7 @@ //! | RSA-4096 | 516 | 520 | 1280 | 1792 | //! | RSA-8192 | 1028 | 1032 | 2560 | 3584 | //! -//! The RSASVE key types (`RSAKEMPublicKey`/`RSAKEMPrivateKey`) have the same encodings +//! 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). @@ -229,12 +260,12 @@ //! All values are in bytes. "On disk" is the `SignaturePublicKey`/`SignaturePrivateKey` 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_LEN = 8 * L` bytes: 128/192/256/384/512/1024 for +//! 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 `L`, not by which hash or scheme fed into +//! 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. //! @@ -332,3 +363,7 @@ pub mod rsassa_pkcs1_v1_5; pub mod rsassa_pss; pub mod rsassa_pss_shake; 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 index 0c36b761..326cc255 100644 --- a/crypto/rsa/src/mgf1.rs +++ b/crypto/rsa/src/mgf1.rs @@ -3,7 +3,7 @@ //! always the hash's own `hLen`-byte output) rather than MGF1's fully general arbitrary-length //! seed: `mgfSeed` here is always exactly `H_LEN` bytes. -use bouncycastle_core::traits::HashOneShot; +use bouncycastle_core::traits::{HashAlgParams, HashOneShot}; /// 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 @@ -13,28 +13,28 @@ use bouncycastle_core::traits::HashOneShot; /// (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. -pub fn mgf1( - seed: &[u8; H_LEN], -) -> [u8; MASK_LEN] { - debug_assert_eq!(SEED_LEN, H_LEN + 4, "mgf1 needs SEED_LEN == H_LEN + 4"); +/// The largest hash output MGF1 is used with here, SHA-512's. +pub(crate) const MAX_HASH_LEN: usize = 64; - let mut mask = [0u8; MASK_LEN]; +/// 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 { - let mut input = [0u8; SEED_LEN]; - input[..H_LEN].copy_from_slice(seed); - input[H_LEN..].copy_from_slice(&counter.to_be_bytes()); - - let mut block = [0u8; H_LEN]; - H::hash_out(&input, &mut block); - - let take = core::cmp::min(H_LEN, MASK_LEN - offset); + 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; } - mask } #[cfg(test)] @@ -58,7 +58,8 @@ mod tests { /// 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 mask: [u8; 223] = mgf1::(&SEED); + 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, @@ -71,12 +72,14 @@ mod tests { /// `MASK_LEN = 10`, shorter than one hash block: exercises truncation of the very first block. #[test] fn mgf1_truncates_within_the_first_block() { - let mask: [u8; 10] = mgf1::(&SEED); + 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 longer: [u8; 223] = mgf1::(&SEED); + let mut longer = [0u8; 223]; + mgf1::(&SEED, &mut longer); assert_eq!(mask, longer[..10]); } @@ -84,8 +87,10 @@ mod tests { /// last. #[test] fn mgf1_spans_multiple_counter_blocks() { - let mask: [u8; 70] = mgf1::(&SEED); - let longer: [u8; 223] = mgf1::(&SEED); + let mut mask = [0u8; 70]; + mgf1::(&SEED, &mut mask); + let mut longer = [0u8; 223]; + mgf1::(&SEED, &mut longer); assert_eq!(mask, longer[..70]); } } diff --git a/crypto/rsa/src/rsa_1024.rs b/crypto/rsa/src/rsa_1024.rs index b2106569..9a7d2516 100644 --- a/crypto/rsa/src/rsa_1024.rs +++ b/crypto/rsa/src/rsa_1024.rs @@ -1,75 +1,23 @@ -//! RSA-1024: verification only. `L = 16` (1024 bits). There is no `RSA1024PrivateKey` and no -//! signing function -- per this crate's `# Scope` (see `src/lib.rs`), a 1024-bit modulus is for -//! verifying signatures made elsewhere (legacy interoperability), not for producing new ones, and -//! that is enforced by the absent type rather than a runtime check. -//! -//! Only SHA-256 and SHA-384 PKCS#1 v1.5 are wired up: Wycheproof's own -//! `rsa_pkcs1_1024_sig_gen_test.json` has no SHA-512 group at 1024 bits (unlike every other size -//! this crate offers) and no PSS vectors at all, so there is nothing to validate a SHA-512 or PSS -//! pairing against at this size -- both remain mathematically expressible through -//! [`crate::rsassa_pkcs1_v1_5`]/[`crate::rsassa_pss`] directly if a caller ever needs them, just -//! not exposed here without real vectors behind them. -//! -//! The same verification-only scope holds for the `bouncycastle_core` trait types -//! ([`RSASSA_PKCS1_v1_5_SHA256`], [`RSASSA_PKCS1_v1_5_SHA384`]): [`RSA1024PublicKey`] implements -//! `VerifyingKey` for them, but no key implements `DeterministicSigningKey`, because the signing -//! role is only implemented where the private key type implements `SignaturePrivateKey`, and -//! `RsaPrivateKey<16, 8>` does not (no size module declares it). Enforced by the compiler, as -//! this doctest pins: -//! -//! ```compile_fail,E0277 -//! use bouncycastle_core::signature_key::DeterministicSigningKey; -//! use bouncycastle_rsa::keys::RsaPrivateKey; -//! use bouncycastle_rsa::rsa_1024::{RSASSA_PKCS1_v1_5_SHA256, SIG_LEN}; -//! -//! fn sign_1024(sk: &RsaPrivateKey<16, 8>) { -//! // error: the trait bound `RsaPrivateKey<16, 8>: DeterministicSigningKey<..>` is not satisfied. -//! let _ = DeterministicSigningKey::::sign_deterministic(sk, b"", None); -//! } -//! ``` +//! 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::keys::RsaPublicKey; use crate::rsassa_pkcs1_v1_5::RSASSA_PKCS1_v1_5; -use bouncycastle_core::errors::SignatureError; -use bouncycastle_core::traits::SignaturePublicKey; +pub use crate::size::RSA1024; +use crate::size::RsaSize; use bouncycastle_sha2::{SHA256, SHA384}; /// An RSA-1024 public key. -pub type RSA1024PublicKey = RsaPublicKey<16>; +pub type RSA1024PublicKey = RsaPublicKey; +/// 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; -/// Encoded length of an [`RSA1024PublicKey`] under [`SignaturePublicKey`]: 128 + 4 bytes (see -/// [`RsaPublicKey`]'s `# Encoding`). -pub const PK_LEN: usize = 132; -/// Signature length: `k`, the modulus length in octets (RFC 8017 §8.2.1 step 2.c). -pub const SIG_LEN: usize = 128; - -impl SignaturePublicKey for RSA1024PublicKey { - fn encode(&self) -> [u8; PK_LEN] { - self.encode_raw::<128, PK_LEN>() - } - - fn encode_out(&self, out: &mut [u8; PK_LEN]) -> usize { - *out = self.encode_raw::<128, PK_LEN>(); - PK_LEN - } - - fn from_bytes(bytes: &[u8]) -> Result { - let bytes: &[u8; PK_LEN] = bytes - .try_into() - .map_err(|_| SignatureError::DecodingError("RSA-1024 public key must be 132 bytes"))?; - Self::from_bytes_raw::<128, PK_LEN>(bytes) - } -} - -/// RSASSA-PKCS1-v1_5/SHA-256 over RSA-1024 as a `SignatureVerifier` only (see the module docs): -/// [`RSASSA_PKCS1_v1_5`] at this size's widths. The signing-side -/// widths the generic type also needs (`HALF = 8`, `HALF2 = 16`, `HALF21 = 17`, `SK_LEN = 320`) -/// are what an RSA-1024 CRT key would have if one existed; they name the type but nothing uses -/// them, since the signing-role impl they would feed does not exist for `RsaPrivateKey<16, 8>`. +/// 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/SHA-384 over RSA-1024, verify-only; see [`RSASSA_PKCS1_v1_5_SHA256`]. +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; +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 index 6771d752..41b79fe2 100644 --- a/crypto/rsa/src/rsa_1536.rs +++ b/crypto/rsa/src/rsa_1536.rs @@ -1,59 +1,26 @@ -//! RSA-1536: verification only. `L = 24` (1536 bits). As with [`crate::rsa_1024`], there is no -//! `RSA1536PrivateKey` and no signing function -- see that module's docs and this crate's -//! `# Scope` for why. -//! -//! Only PKCS#1 v1.5 is wired up: Wycheproof has no PSS vectors at 1536 bits (nor, realistically, -//! would PSS be paired with a modulus this small in practice -- it postdates PKCS#1 v1.5 and -//! became common alongside longer keys), so there is nothing to validate a PSS pairing against at -//! this size. -//! -//! The `SignatureVerifier` types ([`RSASSA_PKCS1_v1_5_SHA256`] and siblings) are verify-only for -//! the same reason and in the same way as [`crate::rsa_1024`]'s -- see that module's docs. +//! 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::keys::RsaPublicKey; use crate::rsassa_pkcs1_v1_5::RSASSA_PKCS1_v1_5; -use bouncycastle_core::errors::SignatureError; -use bouncycastle_core::traits::SignaturePublicKey; +pub use crate::size::RSA1536; +use crate::size::RsaSize; use bouncycastle_sha2::{SHA256, SHA384, SHA512}; /// An RSA-1536 public key. -pub type RSA1536PublicKey = RsaPublicKey<24>; +pub type RSA1536PublicKey = RsaPublicKey; +/// 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; -/// Encoded length of an [`RSA1536PublicKey`] under [`SignaturePublicKey`]: 192 + 4 bytes (see -/// [`RsaPublicKey`]'s `# Encoding`). -pub const PK_LEN: usize = 196; -/// Signature length: `k`, the modulus length in octets (RFC 8017 §8.2.1 step 2.c). -pub const SIG_LEN: usize = 192; - -impl SignaturePublicKey for RSA1536PublicKey { - fn encode(&self) -> [u8; PK_LEN] { - self.encode_raw::<192, PK_LEN>() - } - - fn encode_out(&self, out: &mut [u8; PK_LEN]) -> usize { - *out = self.encode_raw::<192, PK_LEN>(); - PK_LEN - } - - fn from_bytes(bytes: &[u8]) -> Result { - let bytes: &[u8; PK_LEN] = bytes - .try_into() - .map_err(|_| SignatureError::DecodingError("RSA-1536 public key must be 196 bytes"))?; - Self::from_bytes_raw::<192, PK_LEN>(bytes) - } -} - -/// RSASSA-PKCS1-v1_5/SHA-256 over RSA-1536 as a `SignatureVerifier` only -- see -/// [`crate::rsa_1024::RSASSA_PKCS1_v1_5_SHA256`] for why the signing-side widths (`HALF = 12`, -/// `SK_LEN = 480`) are named but inert. +/// 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/SHA-384 over RSA-1536, verify-only; see [`RSASSA_PKCS1_v1_5_SHA256`]. +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/SHA-512 over RSA-1536, verify-only; see [`RSASSA_PKCS1_v1_5_SHA256`]. +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; +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 index 7bdaee52..51b59040 100644 --- a/crypto/rsa/src/rsa_2048.rs +++ b/crypto/rsa/src/rsa_2048.rs @@ -1,211 +1,69 @@ -//! RSA-2048: the generic engine ([`crate::modexp`], [`crate::rsa_core`], [`crate::rsassa_pkcs1_v1_5`], -//! [`crate::rsassa_pss`]) wired to concrete widths -- `L = 32` (2048 bits), `HALF = 16` (1024-bit -//! CRT primes) -- so a caller using this size doesn't thread const-generic width parameters -//! through every call. One file per modulus size, matching [`crate::keys::RsaPrivateKey`]'s own -//! `` shape; `rsa_1024`/`rsa_3072`/`rsa_4096`/`rsa_8192` are the same pattern at their -//! own widths. PSS's salt length is fixed to each hash's own output length (`H_LEN`) throughout, -//! matching RFC 8017 §9.1 note 4's "typical" choice and Wycheproof's own -//! `rsa_pss_2048_sha256_mgf1_32_test.json`/`..._sha384_mgf1_48_test.json`. -//! -//! Each (scheme, hash) pairing is an algorithm marker the key role traits are implemented over -//! ([`RSASSA_PKCS1_v1_5_SHA256`], [`RSASSA_PSS_SHA256`], [`RSASSA_PSS_SHAKE128`], ...): one-shot -//! or streaming, with PSS's salt from the RNG handed to `create_signer` or fixed through `set_salt` -//! on the signer. The key types implement -//! `SignaturePrivateKey`/`SignaturePublicKey` here, at this size's [`SK_LEN`]/[`PK_LEN`]. +//! RSA-2048: the generic types at this size, as aliases over the marker [`RSA2048`]: +//! the key types, `keygen`, every (scheme, hash) pairing offered at this size, and RSASVE. +//! 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::keys::{RsaPrivateKey, RsaPublicKey}; use crate::rsassa_pkcs1_v1_5::RSASSA_PKCS1_v1_5; use crate::rsassa_pss::RSASSA_PSS; use crate::rsassa_pss_shake::RSASSA_PSS_SHAKE; -use crate::rsasve::{RsaKEMPrivateKey, RsaKEMPublicKey, RsasveDecapsulator, RsasveEncapsulator}; -use bouncycastle_core::errors::{KEMError, SignatureError}; -use bouncycastle_core::kem_key::{DecapsulatingKey, EncapsulatingKey}; -use bouncycastle_core::security_strength::SecurityStrength; -use bouncycastle_core::traits::{ - KEMPrivateKey, KEMPublicKey, RNG, SignaturePrivateKey, SignaturePublicKey, -}; +use crate::rsasve::{RsaKEMPrivateKey, RsaKEMPublicKey}; +pub use crate::size::RSA2048; +use crate::size::{RsaSigningSize, RsaSize}; +use bouncycastle_core::errors::SignatureError; +use bouncycastle_core::traits::RNG; use bouncycastle_sha2::{SHA256, SHA384, SHA512}; use bouncycastle_sha3::SHAKE128; -use core::num::NonZeroUsize; -/// An RSA-2048 private key (`p`, `q` each 1024 bits). -pub type RSA2048PrivateKey = RsaPrivateKey<32, 16>; /// An RSA-2048 public key. -pub type RSA2048PublicKey = RsaPublicKey<32>; - -/// Encoded length of an [`RSA2048PrivateKey`] under [`SignaturePrivateKey`]: `p || q || dP || dQ -/// || qInv`, five 128-byte values (see [`RsaPrivateKey`]'s `# Encoding`). -pub const SK_LEN: usize = 640; -/// Encoded length of an [`RSA2048PublicKey`] under [`SignaturePublicKey`]: `n || e`, 256 + 4 -/// bytes (see [`RsaPublicKey`]'s `# Encoding`). -pub const PK_LEN: usize = 260; -/// Signature length: `k`, the modulus length in octets (RFC 8017 §8.1.1/§8.2.1 step 2.c). -pub const SIG_LEN: usize = 256; - -/// As [`keygen`], but sourcing the candidates from the caller-provided RNG, which must offer a -/// security strength of at least 112 bits (SP 800-57 Part 1 Rev. 5, Table 2, `k = 2048`). Each -/// candidate prime gets 5 Miller-Rabin rounds: FIPS 186-5 Table B.1's row for 1024-bit `p` and `q` at an error probability of `2^-112`, RSA-2048's security strength (SP 800-57 Part 1 Rev. 5, Table 2). +pub type RSA2048PublicKey = RsaPublicKey; +/// 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; +/// An RSA-2048 private key. +pub type RSA2048PrivateKey = RsaPrivateKey; +/// Encoded length of an RSA-2048 private key: `p || q || dP || dQ || qInv`. +pub const SK_LEN: usize = RSA2048::SK_LEN; + +/// FIPS 186-5 Appendix A.1.3 key generation at RSA-2048: [`RsaSigningSize::keygen`]. +/// +/// # Errors +/// As [`RsaSigningSize::keygen`]. pub fn keygen(rng: &mut dyn RNG) -> Result<(RSA2048PublicKey, RSA2048PrivateKey), SignatureError> { - crate::keygen::keygen_from_rng::<16, 32, 33>( - rng, - NonZeroUsize::new(5).expect("nonzero literal"), - SecurityStrength::_112bit, - ) -} - -impl SignaturePrivateKey for RSA2048PrivateKey { - fn encode(&self) -> [u8; SK_LEN] { - self.encode_raw::<128, SK_LEN>() - } - - fn encode_out(&self, out: &mut [u8; SK_LEN]) -> usize { - *out = self.encode_raw::<128, SK_LEN>(); - SK_LEN - } - - fn from_bytes(bytes: &[u8]) -> Result { - let bytes: &[u8; SK_LEN] = bytes - .try_into() - .map_err(|_| SignatureError::DecodingError("RSA-2048 private key must be 640 bytes"))?; - Self::from_bytes_raw::<128, SK_LEN>(bytes) - } + RSA2048::keygen(rng) } -impl SignaturePublicKey for RSA2048PublicKey { - fn encode(&self) -> [u8; PK_LEN] { - self.encode_raw::<256, PK_LEN>() - } - - fn encode_out(&self, out: &mut [u8; PK_LEN]) -> usize { - *out = self.encode_raw::<256, PK_LEN>(); - PK_LEN - } - - fn from_bytes(bytes: &[u8]) -> Result { - let bytes: &[u8; PK_LEN] = bytes - .try_into() - .map_err(|_| SignatureError::DecodingError("RSA-2048 public key must be 260 bytes"))?; - Self::from_bytes_raw::<256, PK_LEN>(bytes) - } -} - -/// RSASSA-PKCS1-v1_5/SHA-256 over RSA-2048 through the key role traits: [`RSASSA_PKCS1_v1_5`] -/// at this size's widths. Deterministic: PKCS#1 v1.5 has no randomness, so it is the -/// `DeterministicSigningKey` role and always reproduces the same signature. +/// 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/SHA-384 over RSA-2048; see [`RSASSA_PKCS1_v1_5_SHA256`]. +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/SHA-512 over RSA-2048; see [`RSASSA_PKCS1_v1_5_SHA256`]. +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/SHA-256 (MGF1-SHA-256, 32-byte salt) over RSA-2048 through the key role traits: -/// [`RSASSA_PSS`] at this size's widths, drawing its salt from the RNG handed to `SigningKey::create_signer` -/// unless `set_salt` on the signer replaces it (see that type's docs). +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/SHA-384 (48-byte salt) over RSA-2048; see [`RSASSA_PSS_SHA256`]. +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/SHA-512 (64-byte salt) over RSA-2048; see [`RSASSA_PSS_SHA256`]. +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-SHAKE128 (RFC 8702 §3.2.1) over RSA-2048 through the key role traits: -/// [`RSASSA_PSS_SHAKE`] at this size's widths. +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_SHAKE; - -/// An RSA-2048 private key-establishment key for [`RSASVE`], kept apart from the signing key type -/// [`RSA2048PrivateKey`] (see [`crate::rsasve`]'s `# Key separation`). It uses the same `SK_LEN`-byte -/// encoding. -pub type RSA2048KEMPrivateKey = RsaKEMPrivateKey<32, 16>; -/// An RSA-2048 public key-establishment key for [`RSASVE`]; see [`RSA2048KEMPrivateKey`]. It uses -/// the same `PK_LEN`-byte encoding. -pub type RSA2048KEMPublicKey = RsaKEMPublicKey<32>; - -/// [`RSASVE`] ciphertext length: `nLen`, the modulus length in octets (SP 800-56B Rev. 2 -/// §7.2.1.2's output `C`). -pub const CT_LEN: usize = 256; -/// [`RSASVE`] shared-secret length: also `nLen` (§7.2.1.2's output `Z`). This is the raw secret -/// value, not a derived key: see [`crate::rsasve`]. -pub const SS_LEN: usize = 256; - -/// RSASVE (SP 800-56B Rev. 2 §7.2.1) over RSA-2048, the algorithm the KEM roles of -/// [`RSA2048KEMPublicKey`] and [`RSA2048KEMPrivateKey`] name: -/// [`crate::rsasve::RSASVE`] at this size's widths and its 112-bit security strength. -pub type RSASVE = crate::rsasve::RSASVE<32, 64, 65, 16, 32, 33, 256, 112>; - -impl RSASVE { - /// As [`Self::keygen`], but sourcing the candidates from the caller-provided RNG, with the - /// same RNG requirements as [`keygen`]. - pub fn keygen( - rng: &mut dyn RNG, - ) -> Result<(RSA2048KEMPublicKey, RSA2048KEMPrivateKey), KEMError> { - crate::rsasve::keygen_from(keygen(rng)) - } -} - -impl EncapsulatingKey<(), CT_LEN, SS_LEN> for RSA2048KEMPublicKey { - type Algorithm = RSASVE; - type Encapsulator<'k> = RsasveEncapsulator<'k, 32, 64, 65, 256, 112>; - - /// The raw KEM takes nothing beyond the key, so this never fails. - fn create_encapsulator<'k>(&'k self, _params: ()) -> Result, KEMError> { - Ok(RsasveEncapsulator::new(self)) - } -} - -impl DecapsulatingKey<(), CT_LEN, SS_LEN> for RSA2048KEMPrivateKey { - type Algorithm = RSASVE; - type Decapsulator<'k> = RsasveDecapsulator<'k, 32, 64, 65, 16, 32, 33, 256, 112>; - - /// The raw KEM takes nothing beyond the key, so this never fails. - fn create_decapsulator<'k>(&'k self, _params: ()) -> Result, KEMError> { - Ok(RsasveDecapsulator::new(self)) - } -} - -impl KEMPrivateKey for RSA2048KEMPrivateKey { - fn encode(&self) -> [u8; SK_LEN] { - self.0.encode_raw::<128, SK_LEN>() - } - - fn encode_out(&self, out: &mut [u8; SK_LEN]) -> usize { - *out = self.0.encode_raw::<128, SK_LEN>(); - SK_LEN - } - - fn from_bytes(bytes: &[u8]) -> Result { - let bytes: &[u8; SK_LEN] = bytes - .try_into() - .map_err(|_| KEMError::DecodingError("RSA-2048 private key must be 640 bytes"))?; - crate::rsasve::private_key_from_bytes::<32, 16, 128, SK_LEN>(bytes) - } -} - -impl KEMPublicKey for RSA2048KEMPublicKey { - fn encode(&self) -> [u8; PK_LEN] { - self.0.encode_raw::<256, PK_LEN>() - } - - fn encode_out(&self, out: &mut [u8; PK_LEN]) -> usize { - *out = self.0.encode_raw::<256, PK_LEN>(); - PK_LEN - } - - fn from_bytes(bytes: &[u8]) -> Result { - let bytes: &[u8; PK_LEN] = bytes - .try_into() - .map_err(|_| KEMError::DecodingError("RSA-2048 public key must be 260 bytes"))?; - crate::rsasve::public_key_from_bytes::<32, 256, PK_LEN>(bytes) - } -} +pub type RSASSA_PSS_SHAKE128 = RSASSA_PSS_SHAKE; + +/// 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; diff --git a/crypto/rsa/src/rsa_3072.rs b/crypto/rsa/src/rsa_3072.rs index 4c31346d..2c31476b 100644 --- a/crypto/rsa/src/rsa_3072.rs +++ b/crypto/rsa/src/rsa_3072.rs @@ -1,196 +1,69 @@ -//! RSA-3072: `L = 48` (3072 bits), `HALF = 24` (1536-bit CRT primes). See [`crate::rsa_2048`]'s -//! docs for the pattern every concrete modulus size in this crate follows. +//! RSA-3072: the generic types at this size, as aliases over the marker [`RSA3072`]: +//! the key types, `keygen`, every (scheme, hash) pairing offered at this size, and RSASVE. +//! 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::keys::{RsaPrivateKey, RsaPublicKey}; use crate::rsassa_pkcs1_v1_5::RSASSA_PKCS1_v1_5; use crate::rsassa_pss::RSASSA_PSS; use crate::rsassa_pss_shake::RSASSA_PSS_SHAKE; -use crate::rsasve::{RsaKEMPrivateKey, RsaKEMPublicKey, RsasveDecapsulator, RsasveEncapsulator}; -use bouncycastle_core::errors::{KEMError, SignatureError}; -use bouncycastle_core::kem_key::{DecapsulatingKey, EncapsulatingKey}; -use bouncycastle_core::security_strength::SecurityStrength; -use bouncycastle_core::traits::{ - KEMPrivateKey, KEMPublicKey, RNG, SignaturePrivateKey, SignaturePublicKey, -}; +use crate::rsasve::{RsaKEMPrivateKey, RsaKEMPublicKey}; +pub use crate::size::RSA3072; +use crate::size::{RsaSigningSize, RsaSize}; +use bouncycastle_core::errors::SignatureError; +use bouncycastle_core::traits::RNG; use bouncycastle_sha2::{SHA256, SHA384, SHA512}; use bouncycastle_sha3::SHAKE128; -use core::num::NonZeroUsize; -/// An RSA-3072 private key (`p`, `q` each 1536 bits). -pub type RSA3072PrivateKey = RsaPrivateKey<48, 24>; /// An RSA-3072 public key. -pub type RSA3072PublicKey = RsaPublicKey<48>; - -/// Encoded length of an [`RSA3072PrivateKey`] under [`SignaturePrivateKey`]: five 192-byte -/// values (see [`RsaPrivateKey`]'s `# Encoding`). -pub const SK_LEN: usize = 960; -/// Encoded length of an [`RSA3072PublicKey`] under [`SignaturePublicKey`]: 384 + 4 bytes (see -/// [`RsaPublicKey`]'s `# Encoding`). -pub const PK_LEN: usize = 388; -/// Signature length: `k`, the modulus length in octets (RFC 8017 §8.1.1/§8.2.1 step 2.c). -pub const SIG_LEN: usize = 384; - -/// As [`keygen`], but sourcing the candidates from the caller-provided RNG, which must offer a -/// security strength of at least 128 bits (SP 800-57 Part 1 Rev. 5, Table 2, `k = 3072`). Each -/// candidate prime gets 4 Miller-Rabin rounds: FIPS 186-5 Table B.1's row for 1536-bit `p` and `q` at an error probability of `2^-128`, RSA-3072's security strength (SP 800-57 Part 1 Rev. 5, Table 2). +pub type RSA3072PublicKey = RsaPublicKey; +/// 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; +/// An RSA-3072 private key. +pub type RSA3072PrivateKey = RsaPrivateKey; +/// Encoded length of an RSA-3072 private key: `p || q || dP || dQ || qInv`. +pub const SK_LEN: usize = RSA3072::SK_LEN; + +/// FIPS 186-5 Appendix A.1.3 key generation at RSA-3072: [`RsaSigningSize::keygen`]. +/// +/// # Errors +/// As [`RsaSigningSize::keygen`]. pub fn keygen(rng: &mut dyn RNG) -> Result<(RSA3072PublicKey, RSA3072PrivateKey), SignatureError> { - crate::keygen::keygen_from_rng::<24, 48, 49>( - rng, - NonZeroUsize::new(4).expect("nonzero literal"), - SecurityStrength::_128bit, - ) -} - -impl SignaturePrivateKey for RSA3072PrivateKey { - fn encode(&self) -> [u8; SK_LEN] { - self.encode_raw::<192, SK_LEN>() - } - - fn encode_out(&self, out: &mut [u8; SK_LEN]) -> usize { - *out = self.encode_raw::<192, SK_LEN>(); - SK_LEN - } - - fn from_bytes(bytes: &[u8]) -> Result { - let bytes: &[u8; SK_LEN] = bytes - .try_into() - .map_err(|_| SignatureError::DecodingError("RSA-3072 private key must be 960 bytes"))?; - Self::from_bytes_raw::<192, SK_LEN>(bytes) - } + RSA3072::keygen(rng) } -impl SignaturePublicKey for RSA3072PublicKey { - fn encode(&self) -> [u8; PK_LEN] { - self.encode_raw::<384, PK_LEN>() - } - - fn encode_out(&self, out: &mut [u8; PK_LEN]) -> usize { - *out = self.encode_raw::<384, PK_LEN>(); - PK_LEN - } - - fn from_bytes(bytes: &[u8]) -> Result { - let bytes: &[u8; PK_LEN] = bytes - .try_into() - .map_err(|_| SignatureError::DecodingError("RSA-3072 public key must be 388 bytes"))?; - Self::from_bytes_raw::<384, PK_LEN>(bytes) - } -} - -/// RSASSA-PKCS1-v1_5/SHA-256 over RSA-3072 through the key role traits; see -/// [`crate::rsa_2048::RSASSA_PKCS1_v1_5_SHA256`] for the pattern. +/// 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/SHA-384 over RSA-3072. +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/SHA-512 over RSA-3072. +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/SHA-256 over RSA-3072 through the key role traits; see -/// [`crate::rsa_2048::RSASSA_PSS_SHA256`] for the pattern (including where the salt comes from). +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/SHA-384 over RSA-3072. +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/SHA-512 over RSA-3072. +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-SHAKE128 (RFC 8702 §3.2.1) over RSA-3072 through the key role traits. +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_SHAKE; - -/// An RSA-3072 private key-establishment key for [`RSASVE`], kept apart from the signing key type -/// [`RSA3072PrivateKey`] (see [`crate::rsasve`]'s `# Key separation`). It uses the same `SK_LEN`-byte -/// encoding. -pub type RSA3072KEMPrivateKey = RsaKEMPrivateKey<48, 24>; -/// An RSA-3072 public key-establishment key for [`RSASVE`]; see [`RSA3072KEMPrivateKey`]. It uses -/// the same `PK_LEN`-byte encoding. -pub type RSA3072KEMPublicKey = RsaKEMPublicKey<48>; - -/// [`RSASVE`] ciphertext length: `nLen`, the modulus length in octets (SP 800-56B Rev. 2 -/// §7.2.1.2's output `C`). -pub const CT_LEN: usize = 384; -/// [`RSASVE`] shared-secret length: also `nLen` (§7.2.1.2's output `Z`). This is the raw secret -/// value, not a derived key: see [`crate::rsasve`]. -pub const SS_LEN: usize = 384; - -/// RSASVE (SP 800-56B Rev. 2 §7.2.1) over RSA-3072, the algorithm the KEM roles of -/// [`RSA3072KEMPublicKey`] and [`RSA3072KEMPrivateKey`] name: -/// [`crate::rsasve::RSASVE`] at this size's widths and its 128-bit security strength. -pub type RSASVE = crate::rsasve::RSASVE<48, 96, 97, 24, 48, 49, 384, 128>; - -impl RSASVE { - /// As [`Self::keygen`], but sourcing the candidates from the caller-provided RNG, with the - /// same RNG requirements as [`keygen`]. - pub fn keygen( - rng: &mut dyn RNG, - ) -> Result<(RSA3072KEMPublicKey, RSA3072KEMPrivateKey), KEMError> { - crate::rsasve::keygen_from(keygen(rng)) - } -} - -impl EncapsulatingKey<(), CT_LEN, SS_LEN> for RSA3072KEMPublicKey { - type Algorithm = RSASVE; - type Encapsulator<'k> = RsasveEncapsulator<'k, 48, 96, 97, 384, 128>; - - /// The raw KEM takes nothing beyond the key, so this never fails. - fn create_encapsulator<'k>(&'k self, _params: ()) -> Result, KEMError> { - Ok(RsasveEncapsulator::new(self)) - } -} - -impl DecapsulatingKey<(), CT_LEN, SS_LEN> for RSA3072KEMPrivateKey { - type Algorithm = RSASVE; - type Decapsulator<'k> = RsasveDecapsulator<'k, 48, 96, 97, 24, 48, 49, 384, 128>; - - /// The raw KEM takes nothing beyond the key, so this never fails. - fn create_decapsulator<'k>(&'k self, _params: ()) -> Result, KEMError> { - Ok(RsasveDecapsulator::new(self)) - } -} - -impl KEMPrivateKey for RSA3072KEMPrivateKey { - fn encode(&self) -> [u8; SK_LEN] { - self.0.encode_raw::<192, SK_LEN>() - } - - fn encode_out(&self, out: &mut [u8; SK_LEN]) -> usize { - *out = self.0.encode_raw::<192, SK_LEN>(); - SK_LEN - } - - fn from_bytes(bytes: &[u8]) -> Result { - let bytes: &[u8; SK_LEN] = bytes - .try_into() - .map_err(|_| KEMError::DecodingError("RSA-3072 private key must be 960 bytes"))?; - crate::rsasve::private_key_from_bytes::<48, 24, 192, SK_LEN>(bytes) - } -} - -impl KEMPublicKey for RSA3072KEMPublicKey { - fn encode(&self) -> [u8; PK_LEN] { - self.0.encode_raw::<384, PK_LEN>() - } - - fn encode_out(&self, out: &mut [u8; PK_LEN]) -> usize { - *out = self.0.encode_raw::<384, PK_LEN>(); - PK_LEN - } - - fn from_bytes(bytes: &[u8]) -> Result { - let bytes: &[u8; PK_LEN] = bytes - .try_into() - .map_err(|_| KEMError::DecodingError("RSA-3072 public key must be 388 bytes"))?; - crate::rsasve::public_key_from_bytes::<48, 384, PK_LEN>(bytes) - } -} +pub type RSASSA_PSS_SHAKE128 = RSASSA_PSS_SHAKE; + +/// 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; diff --git a/crypto/rsa/src/rsa_4096.rs b/crypto/rsa/src/rsa_4096.rs index 966f8a87..daa91d76 100644 --- a/crypto/rsa/src/rsa_4096.rs +++ b/crypto/rsa/src/rsa_4096.rs @@ -1,196 +1,69 @@ -//! RSA-4096: `L = 64` (4096 bits), `HALF = 32` (2048-bit CRT primes). See [`crate::rsa_2048`]'s -//! docs for the pattern every concrete modulus size in this crate follows. +//! RSA-4096: the generic types at this size, as aliases over the marker [`RSA4096`]: +//! the key types, `keygen`, every (scheme, hash) pairing offered at this size, and RSASVE. +//! 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::keys::{RsaPrivateKey, RsaPublicKey}; use crate::rsassa_pkcs1_v1_5::RSASSA_PKCS1_v1_5; use crate::rsassa_pss::RSASSA_PSS; use crate::rsassa_pss_shake::RSASSA_PSS_SHAKE; -use crate::rsasve::{RsaKEMPrivateKey, RsaKEMPublicKey, RsasveDecapsulator, RsasveEncapsulator}; -use bouncycastle_core::errors::{KEMError, SignatureError}; -use bouncycastle_core::kem_key::{DecapsulatingKey, EncapsulatingKey}; -use bouncycastle_core::security_strength::SecurityStrength; -use bouncycastle_core::traits::{ - KEMPrivateKey, KEMPublicKey, RNG, SignaturePrivateKey, SignaturePublicKey, -}; +use crate::rsasve::{RsaKEMPrivateKey, RsaKEMPublicKey}; +pub use crate::size::RSA4096; +use crate::size::{RsaSigningSize, RsaSize}; +use bouncycastle_core::errors::SignatureError; +use bouncycastle_core::traits::RNG; use bouncycastle_sha2::{SHA256, SHA384, SHA512}; use bouncycastle_sha3::SHAKE256; -use core::num::NonZeroUsize; -/// An RSA-4096 private key (`p`, `q` each 2048 bits). -pub type RSA4096PrivateKey = RsaPrivateKey<64, 32>; /// An RSA-4096 public key. -pub type RSA4096PublicKey = RsaPublicKey<64>; - -/// Encoded length of an [`RSA4096PrivateKey`] under [`SignaturePrivateKey`]: five 256-byte -/// values (see [`RsaPrivateKey`]'s `# Encoding`). -pub const SK_LEN: usize = 1280; -/// Encoded length of an [`RSA4096PublicKey`] under [`SignaturePublicKey`]: 512 + 4 bytes (see -/// [`RsaPublicKey`]'s `# Encoding`). -pub const PK_LEN: usize = 516; -/// Signature length: `k`, the modulus length in octets (RFC 8017 §8.1.1/§8.2.1 step 2.c). -pub const SIG_LEN: usize = 512; - -/// As [`keygen`], but sourcing the candidates from the caller-provided RNG, which must offer a -/// security strength of at least 128 bits: SP 800-57 Part 1 Rev. 5, Table 2 lists 128 for `k = 3072` and 192 for `k = 7680`, so 4096 is at least 128. Each -/// candidate prime gets 4 Miller-Rabin rounds: FIPS 186-5 Table B.1's row for 2048-bit `p` and `q` at an error probability of `2^-144` (the strength Table B.1 itself pairs with this size). +pub type RSA4096PublicKey = RsaPublicKey; +/// 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; +/// An RSA-4096 private key. +pub type RSA4096PrivateKey = RsaPrivateKey; +/// Encoded length of an RSA-4096 private key: `p || q || dP || dQ || qInv`. +pub const SK_LEN: usize = RSA4096::SK_LEN; + +/// FIPS 186-5 Appendix A.1.3 key generation at RSA-4096: [`RsaSigningSize::keygen`]. +/// +/// # Errors +/// As [`RsaSigningSize::keygen`]. pub fn keygen(rng: &mut dyn RNG) -> Result<(RSA4096PublicKey, RSA4096PrivateKey), SignatureError> { - crate::keygen::keygen_from_rng::<32, 64, 65>( - rng, - NonZeroUsize::new(4).expect("nonzero literal"), - SecurityStrength::_128bit, - ) -} - -impl SignaturePrivateKey for RSA4096PrivateKey { - fn encode(&self) -> [u8; SK_LEN] { - self.encode_raw::<256, SK_LEN>() - } - - fn encode_out(&self, out: &mut [u8; SK_LEN]) -> usize { - *out = self.encode_raw::<256, SK_LEN>(); - SK_LEN - } - - fn from_bytes(bytes: &[u8]) -> Result { - let bytes: &[u8; SK_LEN] = bytes.try_into().map_err(|_| { - SignatureError::DecodingError("RSA-4096 private key must be 1280 bytes") - })?; - Self::from_bytes_raw::<256, SK_LEN>(bytes) - } + RSA4096::keygen(rng) } -impl SignaturePublicKey for RSA4096PublicKey { - fn encode(&self) -> [u8; PK_LEN] { - self.encode_raw::<512, PK_LEN>() - } - - fn encode_out(&self, out: &mut [u8; PK_LEN]) -> usize { - *out = self.encode_raw::<512, PK_LEN>(); - PK_LEN - } - - fn from_bytes(bytes: &[u8]) -> Result { - let bytes: &[u8; PK_LEN] = bytes - .try_into() - .map_err(|_| SignatureError::DecodingError("RSA-4096 public key must be 516 bytes"))?; - Self::from_bytes_raw::<512, PK_LEN>(bytes) - } -} - -/// RSASSA-PKCS1-v1_5/SHA-256 over RSA-4096 through the key role traits; see -/// [`crate::rsa_2048::RSASSA_PKCS1_v1_5_SHA256`] for the pattern. +/// 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/SHA-384 over RSA-4096. +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/SHA-512 over RSA-4096. +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/SHA-256 over RSA-4096 through the key role traits; see -/// [`crate::rsa_2048::RSASSA_PSS_SHA256`] for the pattern (including where the salt comes from). +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/SHA-384 over RSA-4096. +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/SHA-512 over RSA-4096. +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-SHAKE256 (RFC 8702 §3.2.1) over RSA-4096 through the key role traits. +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_SHAKE; - -/// An RSA-4096 private key-establishment key for [`RSASVE`], kept apart from the signing key type -/// [`RSA4096PrivateKey`] (see [`crate::rsasve`]'s `# Key separation`). It uses the same `SK_LEN`-byte -/// encoding. -pub type RSA4096KEMPrivateKey = RsaKEMPrivateKey<64, 32>; -/// An RSA-4096 public key-establishment key for [`RSASVE`]; see [`RSA4096KEMPrivateKey`]. It uses -/// the same `PK_LEN`-byte encoding. -pub type RSA4096KEMPublicKey = RsaKEMPublicKey<64>; - -/// [`RSASVE`] ciphertext length: `nLen`, the modulus length in octets (SP 800-56B Rev. 2 -/// §7.2.1.2's output `C`). -pub const CT_LEN: usize = 512; -/// [`RSASVE`] shared-secret length: also `nLen` (§7.2.1.2's output `Z`). This is the raw secret -/// value, not a derived key: see [`crate::rsasve`]. -pub const SS_LEN: usize = 512; - -/// RSASVE (SP 800-56B Rev. 2 §7.2.1) over RSA-4096, the algorithm the KEM roles of -/// [`RSA4096KEMPublicKey`] and [`RSA4096KEMPrivateKey`] name: -/// [`crate::rsasve::RSASVE`] at this size's widths and its 128-bit security strength. -pub type RSASVE = crate::rsasve::RSASVE<64, 128, 129, 32, 64, 65, 512, 128>; - -impl RSASVE { - /// As [`Self::keygen`], but sourcing the candidates from the caller-provided RNG, with the - /// same RNG requirements as [`keygen`]. - pub fn keygen( - rng: &mut dyn RNG, - ) -> Result<(RSA4096KEMPublicKey, RSA4096KEMPrivateKey), KEMError> { - crate::rsasve::keygen_from(keygen(rng)) - } -} - -impl EncapsulatingKey<(), CT_LEN, SS_LEN> for RSA4096KEMPublicKey { - type Algorithm = RSASVE; - type Encapsulator<'k> = RsasveEncapsulator<'k, 64, 128, 129, 512, 128>; - - /// The raw KEM takes nothing beyond the key, so this never fails. - fn create_encapsulator<'k>(&'k self, _params: ()) -> Result, KEMError> { - Ok(RsasveEncapsulator::new(self)) - } -} - -impl DecapsulatingKey<(), CT_LEN, SS_LEN> for RSA4096KEMPrivateKey { - type Algorithm = RSASVE; - type Decapsulator<'k> = RsasveDecapsulator<'k, 64, 128, 129, 32, 64, 65, 512, 128>; - - /// The raw KEM takes nothing beyond the key, so this never fails. - fn create_decapsulator<'k>(&'k self, _params: ()) -> Result, KEMError> { - Ok(RsasveDecapsulator::new(self)) - } -} - -impl KEMPrivateKey for RSA4096KEMPrivateKey { - fn encode(&self) -> [u8; SK_LEN] { - self.0.encode_raw::<256, SK_LEN>() - } - - fn encode_out(&self, out: &mut [u8; SK_LEN]) -> usize { - *out = self.0.encode_raw::<256, SK_LEN>(); - SK_LEN - } - - fn from_bytes(bytes: &[u8]) -> Result { - let bytes: &[u8; SK_LEN] = bytes - .try_into() - .map_err(|_| KEMError::DecodingError("RSA-4096 private key must be 1280 bytes"))?; - crate::rsasve::private_key_from_bytes::<64, 32, 256, SK_LEN>(bytes) - } -} - -impl KEMPublicKey for RSA4096KEMPublicKey { - fn encode(&self) -> [u8; PK_LEN] { - self.0.encode_raw::<512, PK_LEN>() - } - - fn encode_out(&self, out: &mut [u8; PK_LEN]) -> usize { - *out = self.0.encode_raw::<512, PK_LEN>(); - PK_LEN - } - - fn from_bytes(bytes: &[u8]) -> Result { - let bytes: &[u8; PK_LEN] = bytes - .try_into() - .map_err(|_| KEMError::DecodingError("RSA-4096 public key must be 516 bytes"))?; - crate::rsasve::public_key_from_bytes::<64, 512, PK_LEN>(bytes) - } -} +pub type RSASSA_PSS_SHAKE256 = RSASSA_PSS_SHAKE; + +/// 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; diff --git a/crypto/rsa/src/rsa_8192.rs b/crypto/rsa/src/rsa_8192.rs index b547531c..2c280771 100644 --- a/crypto/rsa/src/rsa_8192.rs +++ b/crypto/rsa/src/rsa_8192.rs @@ -1,190 +1,64 @@ -//! RSA-8192: `L = 128` (8192 bits), `HALF = 64` (4096-bit CRT primes). See [`crate::rsa_2048`]'s -//! docs for the pattern every concrete modulus size in this crate follows. +//! RSA-8192: the generic types at this size, as aliases over the marker [`RSA8192`]: +//! the key types, `keygen`, every (scheme, hash) pairing offered at this size, and RSASVE. +//! 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::keys::{RsaPrivateKey, RsaPublicKey}; use crate::rsassa_pkcs1_v1_5::RSASSA_PKCS1_v1_5; use crate::rsassa_pss::RSASSA_PSS; -use crate::rsasve::{RsaKEMPrivateKey, RsaKEMPublicKey, RsasveDecapsulator, RsasveEncapsulator}; -use bouncycastle_core::errors::{KEMError, SignatureError}; -use bouncycastle_core::kem_key::{DecapsulatingKey, EncapsulatingKey}; -use bouncycastle_core::security_strength::SecurityStrength; -use bouncycastle_core::traits::{ - KEMPrivateKey, KEMPublicKey, RNG, SignaturePrivateKey, SignaturePublicKey, -}; +use crate::rsasve::{RsaKEMPrivateKey, RsaKEMPublicKey}; +pub use crate::size::RSA8192; +use crate::size::{RsaSigningSize, RsaSize}; +use bouncycastle_core::errors::SignatureError; +use bouncycastle_core::traits::RNG; use bouncycastle_sha2::{SHA256, SHA384, SHA512}; -use core::num::NonZeroUsize; -/// An RSA-8192 private key (`p`, `q` each 4096 bits). -pub type RSA8192PrivateKey = RsaPrivateKey<128, 64>; /// An RSA-8192 public key. -pub type RSA8192PublicKey = RsaPublicKey<128>; - -/// Encoded length of an [`RSA8192PrivateKey`] under [`SignaturePrivateKey`]: five 512-byte -/// values (see [`RsaPrivateKey`]'s `# Encoding`). -pub const SK_LEN: usize = 2560; -/// Encoded length of an [`RSA8192PublicKey`] under [`SignaturePublicKey`]: 1024 + 4 bytes (see -/// [`RsaPublicKey`]'s `# Encoding`). -pub const PK_LEN: usize = 1028; -/// Signature length: `k`, the modulus length in octets (RFC 8017 §8.1.1/§8.2.1 step 2.c). -pub const SIG_LEN: usize = 1024; - -/// As [`keygen`], but sourcing the candidates from the caller-provided RNG, which must offer a -/// security strength of at least 192 bits (SP 800-57 Part 1 Rev. 5, Table 2: `k = 7680` gives 192, and 8192 exceeds it). Each -/// candidate prime gets 4 Miller-Rabin rounds: FIPS 186-5 Table B.1 stops at 2048-bit primes; Appendix C.1's formula (2), which reproduces every entry of that table, gives 3 rounds for 4096-bit primes at `2^-192` (RSA-8192 exceeds SP 800-57's 7680-bit/192-bit row) and 5 at `2^-256`, so 4 is taken, matching the table's last row with margin. +pub type RSA8192PublicKey = RsaPublicKey; +/// 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; +/// An RSA-8192 private key. +pub type RSA8192PrivateKey = RsaPrivateKey; +/// Encoded length of an RSA-8192 private key: `p || q || dP || dQ || qInv`. +pub const SK_LEN: usize = RSA8192::SK_LEN; + +/// FIPS 186-5 Appendix A.1.3 key generation at RSA-8192: [`RsaSigningSize::keygen`]. +/// +/// # Errors +/// As [`RsaSigningSize::keygen`]. pub fn keygen(rng: &mut dyn RNG) -> Result<(RSA8192PublicKey, RSA8192PrivateKey), SignatureError> { - crate::keygen::keygen_from_rng::<64, 128, 129>( - rng, - NonZeroUsize::new(4).expect("nonzero literal"), - SecurityStrength::_192bit, - ) -} - -impl SignaturePrivateKey for RSA8192PrivateKey { - fn encode(&self) -> [u8; SK_LEN] { - self.encode_raw::<512, SK_LEN>() - } - - fn encode_out(&self, out: &mut [u8; SK_LEN]) -> usize { - *out = self.encode_raw::<512, SK_LEN>(); - SK_LEN - } - - fn from_bytes(bytes: &[u8]) -> Result { - let bytes: &[u8; SK_LEN] = bytes.try_into().map_err(|_| { - SignatureError::DecodingError("RSA-8192 private key must be 2560 bytes") - })?; - Self::from_bytes_raw::<512, SK_LEN>(bytes) - } + RSA8192::keygen(rng) } -impl SignaturePublicKey for RSA8192PublicKey { - fn encode(&self) -> [u8; PK_LEN] { - self.encode_raw::<1024, PK_LEN>() - } - - fn encode_out(&self, out: &mut [u8; PK_LEN]) -> usize { - *out = self.encode_raw::<1024, PK_LEN>(); - PK_LEN - } - - fn from_bytes(bytes: &[u8]) -> Result { - let bytes: &[u8; PK_LEN] = bytes - .try_into() - .map_err(|_| SignatureError::DecodingError("RSA-8192 public key must be 1028 bytes"))?; - Self::from_bytes_raw::<1024, PK_LEN>(bytes) - } -} - -/// RSASSA-PKCS1-v1_5/SHA-256 over RSA-8192 through the key role traits; see -/// [`crate::rsa_2048::RSASSA_PKCS1_v1_5_SHA256`] for the pattern. +/// 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/SHA-384 over RSA-8192. +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/SHA-512 over RSA-8192. +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/SHA-256 over RSA-8192 through the key role traits; see -/// [`crate::rsa_2048::RSASSA_PSS_SHA256`] for the pattern (including where the salt comes from). +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/SHA-384 over RSA-8192. +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/SHA-512 over RSA-8192. +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 private key-establishment key for [`RSASVE`], kept apart from the signing key type -/// [`RSA8192PrivateKey`] (see [`crate::rsasve`]'s `# Key separation`). It uses the same `SK_LEN`-byte -/// encoding. -pub type RSA8192KEMPrivateKey = RsaKEMPrivateKey<128, 64>; -/// An RSA-8192 public key-establishment key for [`RSASVE`]; see [`RSA8192KEMPrivateKey`]. It uses -/// the same `PK_LEN`-byte encoding. -pub type RSA8192KEMPublicKey = RsaKEMPublicKey<128>; - -/// [`RSASVE`] ciphertext length: `nLen`, the modulus length in octets (SP 800-56B Rev. 2 -/// §7.2.1.2's output `C`). -pub const CT_LEN: usize = 1024; -/// [`RSASVE`] shared-secret length: also `nLen` (§7.2.1.2's output `Z`). This is the raw secret -/// value, not a derived key: see [`crate::rsasve`]. -pub const SS_LEN: usize = 1024; - -/// RSASVE (SP 800-56B Rev. 2 §7.2.1) over RSA-8192, the algorithm the KEM roles of -/// [`RSA8192KEMPublicKey`] and [`RSA8192KEMPrivateKey`] name: -/// [`crate::rsasve::RSASVE`] at this size's widths and its 192-bit security strength. -pub type RSASVE = crate::rsasve::RSASVE<128, 256, 257, 64, 128, 129, 1024, 192>; - -impl RSASVE { - /// As [`Self::keygen`], but sourcing the candidates from the caller-provided RNG, with the - /// same RNG requirements as [`keygen`]. - pub fn keygen( - rng: &mut dyn RNG, - ) -> Result<(RSA8192KEMPublicKey, RSA8192KEMPrivateKey), KEMError> { - crate::rsasve::keygen_from(keygen(rng)) - } -} - -impl EncapsulatingKey<(), CT_LEN, SS_LEN> for RSA8192KEMPublicKey { - type Algorithm = RSASVE; - type Encapsulator<'k> = RsasveEncapsulator<'k, 128, 256, 257, 1024, 192>; - - /// The raw KEM takes nothing beyond the key, so this never fails. - fn create_encapsulator<'k>(&'k self, _params: ()) -> Result, KEMError> { - Ok(RsasveEncapsulator::new(self)) - } -} - -impl DecapsulatingKey<(), CT_LEN, SS_LEN> for RSA8192KEMPrivateKey { - type Algorithm = RSASVE; - type Decapsulator<'k> = RsasveDecapsulator<'k, 128, 256, 257, 64, 128, 129, 1024, 192>; - - /// The raw KEM takes nothing beyond the key, so this never fails. - fn create_decapsulator<'k>(&'k self, _params: ()) -> Result, KEMError> { - Ok(RsasveDecapsulator::new(self)) - } -} - -impl KEMPrivateKey for RSA8192KEMPrivateKey { - fn encode(&self) -> [u8; SK_LEN] { - self.0.encode_raw::<512, SK_LEN>() - } - - fn encode_out(&self, out: &mut [u8; SK_LEN]) -> usize { - *out = self.0.encode_raw::<512, SK_LEN>(); - SK_LEN - } - - fn from_bytes(bytes: &[u8]) -> Result { - let bytes: &[u8; SK_LEN] = bytes - .try_into() - .map_err(|_| KEMError::DecodingError("RSA-8192 private key must be 2560 bytes"))?; - crate::rsasve::private_key_from_bytes::<128, 64, 512, SK_LEN>(bytes) - } -} - -impl KEMPublicKey for RSA8192KEMPublicKey { - fn encode(&self) -> [u8; PK_LEN] { - self.0.encode_raw::<1024, PK_LEN>() - } - - fn encode_out(&self, out: &mut [u8; PK_LEN]) -> usize { - *out = self.0.encode_raw::<1024, PK_LEN>(); - PK_LEN - } - - fn from_bytes(bytes: &[u8]) -> Result { - let bytes: &[u8; PK_LEN] = bytes - .try_into() - .map_err(|_| KEMError::DecodingError("RSA-8192 public key must be 1028 bytes"))?; - crate::rsasve::public_key_from_bytes::<128, 1024, PK_LEN>(bytes) - } -} +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; diff --git a/crypto/rsa/src/rsa_core.rs b/crypto/rsa/src/rsa_core.rs index 13139c55..0a3437f8 100644 --- a/crypto/rsa/src/rsa_core.rs +++ b/crypto/rsa/src/rsa_core.rs @@ -12,6 +12,7 @@ use crate::keys::{RsaPrivateKey, RsaPublicKey}; 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; @@ -22,61 +23,45 @@ use bouncycastle_utils::secret::{Secret, zeroize_in_place}; /// /// 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: &RsaPublicKey, - s: &[u64; L], -) -> Result<[u64; L], SignatureError> { - if nat::sub(s, pk.n()).1 != 1 { +pub(crate) fn rsavp1( + pk: &RsaPublicKey, + 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(public_exp::(pk, s)) + Ok(K::public_exp(pk.n(), pk.e(), s)) } -/// `x^e mod n` under the public key, with no range check of its own: RSAVP1's step 2 (RFC 8017 -/// §5.2.2), shared with any other primitive that exponentiates by `e` -- each caller applies its -/// own specification's range check on `x` first, since those differ (RFC 8017 §5.2.2 step 1 -/// accepts "between 0 and n - 1"). +/// `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( - pk: &RsaPublicKey, + n: &[u64; L], + e: u32, x: &[u64; L], ) -> [u64; L] { - let ctx = MontgomeryContext::::new(pk.n()) + let ctx = MontgomeryContext::::new(n) .expect("RsaPublicKey::new already validated n is odd and nonzero"); - let mut e_limbs = [0u64; L]; - e_limbs[0] = pk.e() as u64; - + e_limbs[0] = e as u64; mod_pow::(x, &e_limbs, &ctx) } -/// RSASP1 (RFC 8017 §5.2.1), CRT form (step 2.b, two-prime case): `s1 = m^dP mod p`, `s2 = m^dQ -/// mod q`, `h = (s1 - s2) * qInv mod p`, `s = s2 + q * h`. -/// -/// Step 1's range check ("If the message representative m is not between 0 and n - 1, output -/// 'message representative out of range'") is `Err(`[`SignatureError::DecodingError`]`)` here. -pub(crate) fn rsasp1< - const L: usize, - const L2: usize, - const L21: usize, - const HALF: usize, - const HALF2: usize, - const HALF21: usize, ->( - sk: &RsaPrivateKey, - m: &[u64; L], -) -> Result<[u64; L], SignatureError> { - if nat::sub(m, sk.n()).1 != 1 { +pub(crate) fn rsasp1( + sk: &RsaPrivateKey, + 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(crt_exp::(sk, m)) + Ok(K::crt_exp(sk, m)) } -/// `m^d mod n` through the CRT quintuple, with no range check of its own: RSASP1's step 2.b (RFC -/// 8017 §5.2.1, two-prime case), shared with any other primitive that exponentiates by the private -/// key -- each caller applies its own specification's range check on `m` first, since those -/// differ (RFC 8017 §5.2.1 step 1 accepts "between 0 and n - 1"). `m < n` is all this function -/// itself relies on. +/// 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, @@ -85,50 +70,35 @@ pub(crate) fn crt_exp< const HALF2: usize, const HALF21: usize, >( - sk: &RsaPrivateKey, + p: &[u64; HALF], + q: &[u64; HALF], + d_p: &[u64; HALF], + d_q: &[u64; HALF], + q_inv: &[u64; HALF], m: &[u64; L], ) -> [u64; L] { - // The two contexts hold `p` and `q`; `Secret` scrubs them on return. let mut ctx_p = Secret::>::new(); - *ctx_p = MontgomeryContext::::new(sk.p()) + *ctx_p = MontgomeryContext::::new(p) .expect("RsaPrivateKey::from_crt_components already validated p is odd and nonzero"); let mut ctx_q = Secret::>::new(); - *ctx_q = MontgomeryContext::::new(sk.q()) + *ctx_q = MontgomeryContext::::new(q) .expect("RsaPrivateKey::from_crt_components already validated q is odd and nonzero"); - - // RFC 8017 §5.2.1 step 2.b.1: reducing `m` (n-width) down to each prime's width is not itself - // part of the RFC's stated steps, which write "m^dP mod p" as if `m` already fit -- but `m` - // is as wide as `n = p * q`, so a real implementation must reduce it first. `p`/`q` are - // private key material, so this uses the constant-time (in the modulus) `reduce_wide`, not - // `bouncycastle_ec`-style variable-time reduction (which is only safe for RSA's *public* `n`). - let mut m_mod_p = reduce_wide::(m, sk.p()); - let mut m_mod_q = reduce_wide::(m, sk.q()); - - let mut s1 = mod_pow::(&m_mod_p, sk.d_p(), &ctx_p); - let mut s2 = mod_pow::(&m_mod_q, sk.d_q(), &ctx_q); - - // Step 2.b.3: `h = (s1 - s2) * qInv mod p`, which needs `s2` reduced mod `p` first. RFC 8017 - // does not require `p` and `q` to be close in magnitude (only that both are the modulus's two - // prime factors), so `s2 < q` gives no useful bound relative to `p` in general -- see - // `RsaPrivateKey`'s docs. `reduce_wide` (built for exactly this: reducing a value wider than - // its target modulus, constant-time in that modulus) handles the general case; it does not - // require its first width to exceed its second. - let mut s2_mod_p = reduce_wide::(&s2, sk.p()); - let mut diff = sub_mod::(&s1, &s2_mod_p, sk.p()); - let mut h = mul_mod::(&diff, sk.q_inv(), &ctx_p); - - // Step 2.b.4: `s = s2 + q * h`. `h < p` and `q * h < q * p = n`, and CRT recombination - // guarantees `s2 + q*h < n` (Garner's algorithm's own correctness property), so this widening - // multiply-then-add cannot overflow `L` limbs. - let mut q_h = montgomery::widening_mul::(sk.q(), &h); + // 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 RsaPrivateKey's 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"); - - // Everything above but `s` is a function of the private primes -- a half-signature alone - // factors `n`, through `gcd(s - s1, n)` -- so it is scrubbed before returning, as - // QUALITY_AND_STYLE.md asks of a secret-holding local. `s` is the caller's. zeroize_in_place(&mut m_mod_p); zeroize_in_place(&mut m_mod_q); zeroize_in_place(&mut s1); @@ -153,7 +123,9 @@ mod tests { use super::*; - fn keypair() -> RsaPrivateKey<32, 16> { + use crate::size::RSA2048; + + fn keypair() -> RsaPrivateKey { let p: [u64; 16] = [ 0xfec673c1b07d4997, 0x98c9e3737faecc8b, 0x01369d6bebcfd19b, 0x8aadc1799d493a6e, 0x958ca74fe2a455a1, 0x686e62c9e375661d, 0xbf73814b7bf6fe14, 0x791ffe2d364719e4, @@ -188,7 +160,7 @@ mod tests { .expect("genuine CRT components must be accepted") } - fn public_key(sk: &RsaPrivateKey<32, 16>) -> RsaPublicKey<32> { + fn public_key(sk: &RsaPrivateKey) -> RsaPublicKey { RsaPublicKey::new(sk.n(), 0x00010001).expect("e = 65537 is valid") } @@ -218,10 +190,10 @@ mod tests { 0xe6407b5fa454d3c9, 0x7c66144074c5739e, 0x72db535464e48005, 0x3e7bf2011ccdf96c, ]; - let s = rsasp1::<32, 64, 65, 16, 32, 33>(&sk, &m).expect("m is in range"); + let s = rsasp1::(&sk, &m).expect("m is in range"); assert_eq!(s, expected_s); - let recovered = rsavp1::<32, 64, 65>(&pk, &s).expect("s is in range"); + let recovered = rsavp1::(&pk, &s).expect("s is in range"); assert_eq!(recovered, m); } @@ -252,9 +224,9 @@ mod tests { 0xbcda0d67e80f74f5, 0xe8b549b81d5eb31d, 0xf1d74cf682145c5d, 0x74643dc08434c3e1, ]; - let s2 = rsasp1::<32, 64, 65, 16, 32, 33>(&sk, &m2).expect("m2 is in range"); + let s2 = rsasp1::(&sk, &m2).expect("m2 is in range"); assert_eq!(s2, expected_s2); - assert_eq!(rsavp1::<32, 64, 65>(&pk, &s2).expect("s2 is in range"), m2); + assert_eq!(rsavp1::(&pk, &s2).expect("s2 is in range"), m2); } #[test] @@ -262,7 +234,7 @@ mod tests { let sk = keypair(); let out_of_range = *sk.n(); assert!(matches!( - rsasp1::<32, 64, 65, 16, 32, 33>(&sk, &out_of_range), + rsasp1::(&sk, &out_of_range), Err(SignatureError::DecodingError(_)) )); } @@ -273,7 +245,7 @@ mod tests { let pk = public_key(&sk); let out_of_range = *pk.n(); assert!(matches!( - rsavp1::<32, 64, 65>(&pk, &out_of_range), + rsavp1::(&pk, &out_of_range), Err(SignatureError::DecodingError(_)) )); } diff --git a/crypto/rsa/src/rsassa_pkcs1_v1_5.rs b/crypto/rsa/src/rsassa_pkcs1_v1_5.rs index 41ec71d1..604f38b8 100644 --- a/crypto/rsa/src/rsassa_pkcs1_v1_5.rs +++ b/crypto/rsa/src/rsassa_pkcs1_v1_5.rs @@ -1,176 +1,77 @@ -//! RSASSA-PKCS1-v1_5 (RFC 8017 §8.2): sign and verify, built on [`crate::rsa_core`]'s -//! RSASP1/RSAVP1 and [`crate::emsa_pkcs1_v1_5`]'s deterministic encoding. Generic over every -//! width this crate's arithmetic needs (`L`/`L2`/`L21` for the modulus, `HALF`/`HALF2`/`HALF21` -//! for each CRT prime, `K_LEN = 8 * L` for the encoded message/signature byte length) and over -//! the hash function `H` (`H_LEN`/`T_LEN` sized to it) -- a concrete modulus size wires these to -//! literals (e.g. RSA-2048/SHA-256 in [`crate::rsa_2048`]) rather than a caller choosing them. -//! -//! [`RSASSA_PKCS1_v1_5`] is the algorithm marker the key role traits ([`DeterministicSigningKey`], -//! [`VerifyingKey`]) are implemented over at those widths -- one-shot and streaming, with a -//! `&[u8]`-typed signature on the verify side -- on top of [`sign_from_hash`]/[`verify_from_hash`], -//! which take the message hash rather than the message and are the pre-hash entry points for a -//! caller that has already computed it. +//! RSASSA-PKCS1-v1_5 (RFC 8017 §8.2): sign and verify, built on `rsa_core`'s RSASP1/RSAVP1 and +//! `emsa_pkcs1_v1_5`'s deterministic encoding, once over the modulus size `K` ([`RsaSize`]) +//! and the hash `H`. [`RSASSA_PKCS1_v1_5`] is the algorithm marker the key role traits +//! ([`DeterministicSigningKey`], [`VerifyingKey`]) are implemented over -- one-shot and +//! streaming, with a `&[u8]`-typed signature on the verify side -- on top of +//! [`sign_from_hash`]/[`verify_from_hash`], which take the message hash rather than the message +//! and are the pre-hash entry points for a caller that has already computed it. -use crate::codec::{be_bytes_from_limbs, limbs_from_be_bytes}; use crate::emsa_pkcs1_v1_5::{emsa_pkcs1_v1_5_encode_from_hash, emsa_pkcs1_v1_5_verify_from_hash}; -use crate::keys::{RsaPrivateKey, RsaPublicKey, modulus_strength}; +use crate::keys::{RsaPrivateKey, RsaPublicKey}; +use crate::mgf1::MAX_HASH_LEN; use crate::rsa_core::{rsasp1, rsavp1}; +use crate::size::{RsaSigningSize, RsaSize, min_strength}; use bouncycastle_core::errors::SignatureError; use bouncycastle_core::security_strength::SecurityStrength; use bouncycastle_core::signature_key::{DeterministicSigningKey, SignatureAlgorithm, VerifyingKey}; use bouncycastle_core::traits::{ - Algorithm, AlgorithmInfo, AlgorithmOID, HashAlgParams, HashOneShot, SignaturePrivateKey, - SignaturePublicKey, SignatureSigner, SignatureVerifier, + Algorithm, AlgorithmInfo, AlgorithmOID, HashAlgParams, HashOneShot, SignatureSigner, + SignatureVerifier, }; +use bouncycastle_utils::const_str::ConstStr; use core::marker::PhantomData; -/// RSASSA-PKCS1-v1_5 (RFC 8017 §8.2) over `H`, at a modulus of `L` limbs: the algorithm marker the key role -/// traits are implemented over, with every width fixed by the aliases in the size modules -/// (`rsa_2048::RSASSA_PKCS1_v1_5_SHA256` and siblings). -/// `RsaPrivateKey` signs through [`DeterministicSigningKey`]: PKCS#1 v1.5 draws nothing, so the -/// same key and message always give the same signature. -/// `RsaPublicKey` verifies through [`VerifyingKey`]. One key type serves every scheme and hash, so -/// a call names the marker: `DeterministicSigningKey::::...(&sk, ..)`. `ctx` is -/// accepted and ignored, since RSA has no context string. +/// 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`] signs through [`DeterministicSigningKey`] at a signing size: PKCS#1 v1.5 +/// draws nothing, so the same key and message always give the same signature. +/// [`RsaPublicKey`] verifies through [`VerifyingKey`] at any size. One key type serves every +/// scheme and hash, so a call names the marker: +/// `DeterministicSigningKey::::sign_deterministic(&sk, ..)`. +/// `ctx` is accepted and ignored, since RSA has no context string. #[allow(non_camel_case_types)] -pub struct RSASSA_PKCS1_v1_5< - H, - const H_LEN: usize, - const T_LEN: usize, - const L: usize, - const L2: usize, - const L21: usize, - const HALF: usize, - const HALF2: usize, - const HALF21: usize, - const K_LEN: usize, - const SK_LEN: usize, - const PK_LEN: usize, -> { - _hash: PhantomData, +pub struct RSASSA_PKCS1_v1_5 { + _params: PhantomData<(K, H)>, } -impl< - H, - const H_LEN: usize, - const T_LEN: usize, - const L: usize, - const L2: usize, - const L21: usize, - const HALF: usize, - const HALF2: usize, - const HALF21: usize, - const K_LEN: usize, - const SK_LEN: usize, - const PK_LEN: usize, -> Algorithm - for RSASSA_PKCS1_v1_5 -{ - const ALG_NAME: &'static str = "RSASSA-PKCS1-v1_5"; - /// From the modulus width, by SP 800-57 Part 1 Rev. 5 Table 2; see [`modulus_strength`]. - const MAX_SECURITY_STRENGTH: SecurityStrength = modulus_strength(L); +impl RSASSA_PKCS1_v1_5 { + const NAME: ConstStr<40> = ConstStr::concat(&["RSASSA-PKCS1-v1_5-", H::ALG_NAME]); } -impl< - H, - const H_LEN: usize, - const T_LEN: usize, - const L: usize, - const L2: usize, - const L21: usize, - const HALF: usize, - const HALF2: usize, - const HALF21: usize, - const K_LEN: usize, - const SK_LEN: usize, - const PK_LEN: usize, -> SignatureAlgorithm - for RSASSA_PKCS1_v1_5 -{ +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); } -/// The signer the key hands out; it hashes the message and finishes with [`RSASSA_PKCS1_v1_5`]'s encoding and -/// RSASP1. -pub struct RsaPkcs1v15Signer< - 'k, - H, - const H_LEN: usize, - const T_LEN: usize, - const L: usize, - const L2: usize, - const L21: usize, - const HALF: usize, - const HALF2: usize, - const HALF21: usize, - const K_LEN: usize, - const SK_LEN: usize, - const PK_LEN: usize, -> { - sk: &'k RsaPrivateKey, +impl SignatureAlgorithm for RSASSA_PKCS1_v1_5 {} + +/// The signer [`DeterministicSigningKey::create_signer_deterministic`] hands out: the key, +/// borrowed, and the running hash. +pub struct RsaPkcs1v15Signer<'k, K: RsaSize, H> { + sk: &'k RsaPrivateKey, hash: H, } -/// The verifier the key hands out: hashes the message and finishes with RSAVP1 and the -/// encoding's verification. -pub struct RsaPkcs1v15Verifier< - 'k, - H, - const H_LEN: usize, - const T_LEN: usize, - const L: usize, - const L2: usize, - const L21: usize, - const HALF: usize, - const HALF2: usize, - const HALF21: usize, - const K_LEN: usize, - const SK_LEN: usize, - const PK_LEN: usize, -> { - pk: &'k RsaPublicKey, +/// The verifier [`VerifyingKey::create_verifier`] hands out: the key, borrowed, and the running +/// hash. +pub struct RsaPkcs1v15Verifier<'k, K: RsaSize, H> { + pk: &'k RsaPublicKey, hash: H, } -impl< - H: HashOneShot + HashAlgParams + AlgorithmOID, - const H_LEN: usize, - const T_LEN: usize, - const L: usize, - const L2: usize, - const L21: usize, - const HALF: usize, - const HALF2: usize, - const HALF21: usize, - const K_LEN: usize, - const SK_LEN: usize, - const PK_LEN: usize, -> - DeterministicSigningKey< - RSASSA_PKCS1_v1_5, - K_LEN, - > for RsaPrivateKey +impl DeterministicSigningKey, K_LEN> + for RsaPrivateKey where - // Only a private key type this crate has declared signable (a `SignaturePrivateKey` impl in - // its size module) signs: the verify-only sizes, RSA-1024/1536, have none, so this impl does - // not exist for them -- compile-time enforcement of the crate's `# Scope`. - RsaPrivateKey: SignaturePrivateKey, + // 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. + K: RsaSigningSize + RsaSize, + H: HashOneShot + HashAlgParams + AlgorithmOID, { type Signer<'k> - = RsaPkcs1v15Signer< - 'k, - H, - H_LEN, - T_LEN, - L, - L2, - L21, - HALF, - HALF2, - HALF21, - K_LEN, - SK_LEN, - PK_LEN, - > + = RsaPkcs1v15Signer<'k, K, H> where Self: 'k; @@ -182,43 +83,13 @@ where } } -impl< - H: HashOneShot + HashAlgParams + AlgorithmOID, - const H_LEN: usize, - const T_LEN: usize, - const L: usize, - const L2: usize, - const L21: usize, - const HALF: usize, - const HALF2: usize, - const HALF21: usize, - const K_LEN: usize, - const SK_LEN: usize, - const PK_LEN: usize, -> - VerifyingKey< - RSASSA_PKCS1_v1_5, - K_LEN, - > for RsaPublicKey +impl VerifyingKey, K_LEN> for RsaPublicKey where - RsaPublicKey: SignaturePublicKey, + K: RsaSize, + H: HashOneShot + HashAlgParams + AlgorithmOID, { type Verifier<'k> - = RsaPkcs1v15Verifier< - 'k, - H, - H_LEN, - T_LEN, - L, - L2, - L21, - HALF, - HALF2, - HALF21, - K_LEN, - SK_LEN, - PK_LEN, - > + = RsaPkcs1v15Verifier<'k, K, H> where Self: 'k; @@ -230,84 +101,29 @@ where } } -impl< - H: HashOneShot + HashAlgParams + AlgorithmOID, - const H_LEN: usize, - const T_LEN: usize, - const L: usize, - const L2: usize, - const L21: usize, - const HALF: usize, - const HALF2: usize, - const HALF21: usize, - const K_LEN: usize, - const SK_LEN: usize, - const PK_LEN: usize, -> AlgorithmInfo - for RsaPkcs1v15Signer< - '_, - H, - H_LEN, - T_LEN, - L, - L2, - L21, - HALF, - HALF2, - HALF21, - K_LEN, - SK_LEN, - PK_LEN, - > -{ +impl AlgorithmInfo for RsaPkcs1v15Signer<'_, K, H> { fn alg_name(&self) -> &'static str { - as Algorithm>::ALG_NAME + RSASSA_PKCS1_v1_5::::ALG_NAME } fn max_security_strength(&self) -> SecurityStrength { - as Algorithm>::MAX_SECURITY_STRENGTH + RSASSA_PKCS1_v1_5::::MAX_SECURITY_STRENGTH } } -impl< +impl SignatureSigner for RsaPkcs1v15Signer<'_, K, H> +where + K: RsaSigningSize + RsaSize, H: HashOneShot + HashAlgParams + AlgorithmOID, - const H_LEN: usize, - const T_LEN: usize, - const L: usize, - const L2: usize, - const L21: usize, - const HALF: usize, - const HALF2: usize, - const HALF21: usize, - const K_LEN: usize, - const SK_LEN: usize, - const PK_LEN: usize, -> SignatureSigner - for RsaPkcs1v15Signer< - '_, - H, - H_LEN, - T_LEN, - L, - L2, - L21, - HALF, - HALF2, - HALF21, - K_LEN, - SK_LEN, - PK_LEN, - > { fn do_update(&mut self, msg_chunk: &[u8]) { self.hash.do_update(msg_chunk); } fn do_final(self) -> Result<[u8; K_LEN], SignatureError> { - // The encoding's first step, `Hash(M)`, completed here over the streamed chunks. - let mut m_hash = [0u8; H_LEN]; - self.hash.do_final_out(&mut m_hash); - sign_from_hash::(self.sk, &m_hash) + let mut m_hash = [0u8; MAX_HASH_LEN]; + self.hash.do_final_out(&mut m_hash[..H::OUTPUT_LEN]); + sign_from_hash::(self.sk, &m_hash[..H::OUTPUT_LEN]) } fn do_final_out(self, output: &mut [u8; K_LEN]) -> Result { @@ -317,155 +133,80 @@ impl< } } -impl< - H: HashOneShot + HashAlgParams + AlgorithmOID, - const H_LEN: usize, - const T_LEN: usize, - const L: usize, - const L2: usize, - const L21: usize, - const HALF: usize, - const HALF2: usize, - const HALF21: usize, - const K_LEN: usize, - const SK_LEN: usize, - const PK_LEN: usize, -> AlgorithmInfo - for RsaPkcs1v15Verifier< - '_, - H, - H_LEN, - T_LEN, - L, - L2, - L21, - HALF, - HALF2, - HALF21, - K_LEN, - SK_LEN, - PK_LEN, - > -{ +impl AlgorithmInfo for RsaPkcs1v15Verifier<'_, K, H> { fn alg_name(&self) -> &'static str { - as Algorithm>::ALG_NAME + RSASSA_PKCS1_v1_5::::ALG_NAME } fn max_security_strength(&self) -> SecurityStrength { - as Algorithm>::MAX_SECURITY_STRENGTH + RSASSA_PKCS1_v1_5::::MAX_SECURITY_STRENGTH } } -impl< +impl SignatureVerifier for RsaPkcs1v15Verifier<'_, K, H> +where + K: RsaSize, H: HashOneShot + HashAlgParams + AlgorithmOID, - const H_LEN: usize, - const T_LEN: usize, - const L: usize, - const L2: usize, - const L21: usize, - const HALF: usize, - const HALF2: usize, - const HALF21: usize, - const K_LEN: usize, - const SK_LEN: usize, - const PK_LEN: usize, -> SignatureVerifier - for RsaPkcs1v15Verifier< - '_, - H, - H_LEN, - T_LEN, - L, - L2, - L21, - HALF, - HALF2, - HALF21, - K_LEN, - SK_LEN, - PK_LEN, - > { fn do_update(&mut self, msg_chunk: &[u8]) { self.hash.do_update(msg_chunk); } fn do_verify_final(self, sig: &[u8]) -> Result<(), SignatureError> { - // RFC 8017 §8.1.2 / §8.2.2 step 1, "Length checking: If the length of the signature S is - // not k octets, output "invalid signature" and stop", reported as the length error the - // shared suite expects for a signature of the wrong size. + // RFC 8017 §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 mut m_hash = [0u8; H_LEN]; - self.hash.do_final_out(&mut m_hash); + let mut m_hash = [0u8; MAX_HASH_LEN]; + self.hash.do_final_out(&mut m_hash[..H::OUTPUT_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, sig) + verify_from_hash::(self.pk, &m_hash[..H::OUTPUT_LEN], sig) .map_err(|_| SignatureError::SignatureVerificationFailed) } } -/// RSASSA-PKCS1-V1_5-SIGN (RFC 8017 §8.2.1), `S = I2OSP(RSASP1(K, OS2IP(EM)), k)` with -/// `EM = EMSA-PKCS1-V1_5-ENCODE(M, k)`, given the message's hash `digest` (`H`'s output over `M`) -/// rather than `M` itself: the entry point for a caller that hashed the message incrementally -/// (the [`DeterministicSigningKey`] impl) or already holds the digest. Step 1's two errors ("message too long" -- -/// unreachable, since the encoding's length is fixed at compile time by `K_LEN` -- and "RSA -/// modulus too short") are folded into [`emsa_pkcs1_v1_5_encode_from_hash`]'s `debug_assert`, not -/// raised here as a runtime error, for the reason given there. The `H` bound is only what [`emsa_pkcs1_v1_5_encode_from_hash`] needs to build the -/// `DigestInfo`; no hashing happens here. -pub fn sign_from_hash< +/// RSASSA-PKCS1-V1_5-SIGN (RFC 8017 §8.2.1) from the message hash (`H::OUTPUT_LEN` bytes): the +/// EMSA-PKCS1-v1_5 encoding of `digest`, then RSASP1. +/// +/// # Errors +/// [`SignatureError::DecodingError`] if the encoded message is not below `n`, which no modulus +/// with its top bit set allows. +pub fn sign_from_hash( + sk: &RsaPrivateKey, + digest: &[u8], +) -> Result<[u8; K_LEN], SignatureError> +where + K: RsaSigningSize + RsaSize, H: HashAlgParams + AlgorithmOID, - const H_LEN: usize, - const T_LEN: usize, - const L: usize, - const L2: usize, - const L21: usize, - const HALF: usize, - const HALF2: usize, - const HALF21: usize, - const K_LEN: usize, ->( - sk: &RsaPrivateKey, - digest: &[u8; H_LEN], -) -> Result<[u8; K_LEN], SignatureError> { - let em = emsa_pkcs1_v1_5_encode_from_hash::(digest); - let m = limbs_from_be_bytes::(&em); - let s = rsasp1::(sk, &m)?; - Ok(be_bytes_from_limbs::(&s)) +{ + let em = emsa_pkcs1_v1_5_encode_from_hash::(digest); + let m = K::limbs_from_be_bytes(&em); + let s = rsasp1::(sk, &m)?; + Ok(K::be_bytes_from_limbs(&s)) } -/// RSASSA-PKCS1-V1_5-VERIFY (RFC 8017 §8.2.2), given the message's hash `digest` rather than the -/// message (the counterpart of [`sign_from_hash`]): recovers `EM' = I2OSP(RSAVP1((n, e), -/// OS2IP(S)), k)` and checks it against `digest` via [`emsa_pkcs1_v1_5_verify_from_hash`] -- a -/// decode, not RFC 8017's own step 4 (re-encode and compare bytes to `EM'`), because a byte -/// comparison against this crate's own (always-`NULL`-including) encoding would reject an -/// otherwise-valid signature whose `DigestInfo` omits the `AlgorithmIdentifier`'s `NULL` -/// parameters -- a real-world leniency that function's docs explain. Step 1's length check (`S` -/// must be exactly `k` octets) doesn't apply here: `signature` is a fixed `K_LEN`-byte array, so a -/// wrong length is a type error at the call site; the [`VerifyingKey`] impl, which takes a -/// `&[u8]`, performs it. Step 2's "signature representative out of range" surfaces as -/// [`rsavp1`]'s own `Err`, propagated directly rather than folded into "invalid signature": a -/// caller working through CAVP/wycheproof-style vectors needs to tell "malformed input" apart from -/// "well-formed but wrong", the same distinction RFC 8017 itself draws by giving the range check -/// its own error text (the trait impl folds it, per step 2.b). -pub fn verify_from_hash< - H: AlgorithmOID, - const H_LEN: usize, - const L: usize, - const L2: usize, - const L21: usize, - const K_LEN: usize, ->( - pk: &RsaPublicKey, - digest: &[u8; H_LEN], +/// RSASSA-PKCS1-V1_5-VERIFY (RFC 8017 §8.2.2) from the message hash: RSAVP1, then the EMSA +/// decoding compared against `digest`. +/// +/// # Errors +/// [`SignatureError::DecodingError`] for a signature representative not below `n` (step 2.b's +/// "invalid signature" from RSAVP1), [`SignatureError::SignatureVerificationFailed`] for an +/// encoding that does not match. +pub fn verify_from_hash( + pk: &RsaPublicKey, + digest: &[u8], signature: &[u8; K_LEN], -) -> Result<(), SignatureError> { - let s = limbs_from_be_bytes::(signature); - let m = rsavp1::(pk, &s)?; - let em_prime = be_bytes_from_limbs::(&m); +) -> Result<(), SignatureError> +where + K: RsaSize, + H: AlgorithmOID, +{ + let s = K::limbs_from_be_bytes(signature); + let m = rsavp1::(pk, &s)?; + let em_prime = K::be_bytes_from_limbs(&m); - if emsa_pkcs1_v1_5_verify_from_hash::(digest, &em_prime) { + if emsa_pkcs1_v1_5_verify_from_hash::(digest, &em_prime) { Ok(()) } else { Err(SignatureError::SignatureVerificationFailed) diff --git a/crypto/rsa/src/rsassa_pss.rs b/crypto/rsa/src/rsassa_pss.rs index 0e4b2185..533af1e1 100644 --- a/crypto/rsa/src/rsassa_pss.rs +++ b/crypto/rsa/src/rsassa_pss.rs @@ -1,288 +1,84 @@ -//! RSASSA-PSS (RFC 8017 §8.1): sign and verify, built on [`crate::rsa_core`]'s RSASP1/RSAVP1 and -//! [`crate::emsa_pss`]'s probabilistic encoding. Generic over the same width parameters as -//! [`crate::rsassa_pkcs1_v1_5`] plus PSS's own `S_LEN` (salt length) and `M_PRIME_LEN` -//! (`8 + H_LEN + S_LEN`); a concrete modulus size wires these to literals (RSA-2048/SHA-256 in -//! [`crate::rsa_2048`]). -//! -//! As in [`crate::rsassa_pkcs1_v1_5`], [`RSASSA_PSS`] is the algorithm marker the key role +//! RSASSA-PSS (RFC 8017 §8.1): sign and verify, built on `rsa_core`'s RSASP1/RSAVP1 and +//! `emsa_pss`'s probabilistic encoding, once over the modulus size `K` ([`RsaSize`]) and the +//! hash `H` (also MGF1's hash). [`RSASSA_PSS`] is the algorithm marker the key role //! traits are implemented over, on top of the `*_from_hash` functions, which take the message -//! hash rather than the message; the salt comes from the RNG handed to -//! [`SigningKey::create_signer`], and [`RsaPssSigner::set_salt`] replaces it for a known answer. +//! hash rather than the message; the salt, one hash output long (RFC 8017 §9.1 note 4's +//! "typical" choice), comes from the RNG handed to [`SigningKey::create_signer`], and +//! [`RsaPssSigner::set_salt`] replaces it for a known answer. -use crate::codec::{be_bytes_from_limbs, limbs_from_be_bytes}; use crate::emsa_pss::{emsa_pss_encode_from_hash, emsa_pss_verify_from_hash}; -use crate::keys::{RsaPrivateKey, RsaPublicKey, modulus_strength}; +use crate::keys::{RsaPrivateKey, RsaPublicKey}; +use crate::mgf1::MAX_HASH_LEN; use crate::rsa_core::{rsasp1, rsavp1}; +use crate::size::{RsaSigningSize, RsaSize, min_strength}; use bouncycastle_core::errors::SignatureError; use bouncycastle_core::security_strength::SecurityStrength; use bouncycastle_core::signature_key::{SignatureAlgorithm, SigningKey, VerifyingKey}; use bouncycastle_core::traits::{ - Algorithm, AlgorithmInfo, HashOneShot, RNG, SignaturePrivateKey, SignaturePublicKey, - SignatureSigner, SignatureVerifier, + Algorithm, AlgorithmInfo, HashAlgParams, HashOneShot, RNG, SignatureSigner, SignatureVerifier, }; +use bouncycastle_utils::const_str::ConstStr; use core::marker::PhantomData; -/// RSASSA-PSS (RFC 8017 §8.1) over `H`, with MGF1 over `H`, at a modulus of `L` limbs: the algorithm marker the key role -/// traits are implemented over, with every width fixed by the aliases in the size modules -/// (`rsa_2048::RSASSA_PSS_SHA256` and siblings). -/// `RsaPrivateKey` signs through [`SigningKey`]: a fresh `S_LEN`-byte salt from the caller's RNG -/// per signer (EMSA-PSS-ENCODE step 4), so two signatures of one message differ. -/// `RsaPublicKey` verifies through [`VerifyingKey`]. One key type serves every scheme and hash, so -/// a call names the marker: `SigningKey::::...(&sk, ..)`. `ctx` is -/// accepted and ignored, since RSA has no context string. +/// RSASSA-PSS (RFC 8017 §8.1) over the hash `H`, with MGF1 over `H`, at the modulus size `K`: the algorithm marker the key role traits are implemented +/// over, named `RSASSA-PSS-` (`RSASSA-PSS-SHA256`), at the lesser of the size's and the hash's +/// strength. [`RsaPrivateKey`] signs through [`SigningKey`] at a signing size: a fresh salt, one +/// hash output long, from the caller's RNG per signer (EMSA-PSS-ENCODE step 4), so two +/// signatures of one message differ. [`RsaPublicKey`] verifies through [`VerifyingKey`] at any +/// size. One key type serves every scheme and hash, so a call names the marker: +/// `SigningKey::::sign(&sk, ..)`. `ctx` is accepted and +/// ignored, since RSA has no context string. #[allow(non_camel_case_types)] -pub struct RSASSA_PSS< - H, - const H_LEN: usize, - const SEED_LEN: usize, - const S_LEN: usize, - const M_PRIME_LEN: usize, - const DB_LEN: usize, - const L: usize, - const L2: usize, - const L21: usize, - const HALF: usize, - const HALF2: usize, - const HALF21: usize, - const K_LEN: usize, - const SK_LEN: usize, - const PK_LEN: usize, -> { - _hash: PhantomData, +pub struct RSASSA_PSS { + _params: PhantomData<(K, H)>, } -impl< - H, - const H_LEN: usize, - const SEED_LEN: usize, - const S_LEN: usize, - const M_PRIME_LEN: usize, - const DB_LEN: usize, - const L: usize, - const L2: usize, - const L21: usize, - const HALF: usize, - const HALF2: usize, - const HALF21: usize, - const K_LEN: usize, - const SK_LEN: usize, - const PK_LEN: usize, -> Algorithm - for RSASSA_PSS< - H, - H_LEN, - SEED_LEN, - S_LEN, - M_PRIME_LEN, - DB_LEN, - L, - L2, - L21, - HALF, - HALF2, - HALF21, - K_LEN, - SK_LEN, - PK_LEN, - > -{ - const ALG_NAME: &'static str = "RSASSA-PSS"; - /// From the modulus width, by SP 800-57 Part 1 Rev. 5 Table 2; see [`modulus_strength`]. - const MAX_SECURITY_STRENGTH: SecurityStrength = modulus_strength(L); +impl RSASSA_PSS { + const NAME: ConstStr<40> = ConstStr::concat(&["RSASSA-PSS-", H::ALG_NAME]); } -impl< - H, - const H_LEN: usize, - const SEED_LEN: usize, - const S_LEN: usize, - const M_PRIME_LEN: usize, - const DB_LEN: usize, - const L: usize, - const L2: usize, - const L21: usize, - const HALF: usize, - const HALF2: usize, - const HALF21: usize, - const K_LEN: usize, - const SK_LEN: usize, - const PK_LEN: usize, -> SignatureAlgorithm - for RSASSA_PSS< - H, - H_LEN, - SEED_LEN, - S_LEN, - M_PRIME_LEN, - DB_LEN, - L, - L2, - L21, - HALF, - HALF2, - HALF21, - K_LEN, - SK_LEN, - PK_LEN, - > -{ +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); } -/// The signer the key hands out; it hashes the message and finishes with [`RSASSA_PSS`]'s encoding and -/// RSASP1. `set_salt` replaces the drawn salt, for a known-answer test; the signature then depends on the key and message alone. -pub struct RsaPssSigner< - 'k, - H, - const H_LEN: usize, - const SEED_LEN: usize, - const S_LEN: usize, - const M_PRIME_LEN: usize, - const DB_LEN: usize, - const L: usize, - const L2: usize, - const L21: usize, - const HALF: usize, - const HALF2: usize, - const HALF21: usize, - const K_LEN: usize, - const SK_LEN: usize, - const PK_LEN: usize, -> { - sk: &'k RsaPrivateKey, +impl SignatureAlgorithm for RSASSA_PSS {} + +/// The signer [`SigningKey::create_signer`] hands out: the key, borrowed, the running hash and +/// the salt (the first `H::OUTPUT_LEN` bytes of the buffer). +pub struct RsaPssSigner<'k, K: RsaSize, H> { + sk: &'k RsaPrivateKey, hash: H, - salt: [u8; S_LEN], + salt: [u8; MAX_HASH_LEN], } -impl< - 'k, - H: HashOneShot, - const H_LEN: usize, - const SEED_LEN: usize, - const S_LEN: usize, - const M_PRIME_LEN: usize, - const DB_LEN: usize, - const L: usize, - const L2: usize, - const L21: usize, - const HALF: usize, - const HALF2: usize, - const HALF21: usize, - const K_LEN: usize, - const SK_LEN: usize, - const PK_LEN: usize, -> - RsaPssSigner< - 'k, - H, - H_LEN, - SEED_LEN, - S_LEN, - M_PRIME_LEN, - DB_LEN, - L, - L2, - L21, - HALF, - HALF2, - HALF21, - K_LEN, - SK_LEN, - PK_LEN, - > -{ - /// Replaces the salt drawn at creation with `salt`, for a known-answer test against a - /// published salt; the signature then depends on the key and message alone. - pub fn set_salt(&mut self, salt: [u8; S_LEN]) { - self.salt = salt; +impl RsaPssSigner<'_, K, H> { + /// Replaces the salt drawn when the signer was created, for a known-answer test; `N` must be + /// the hash's output length, which is checked when the call is compiled. + pub fn set_salt(&mut self, salt: [u8; N]) { + const { assert!(N == H::OUTPUT_LEN, "the PSS salt is one hash output long") }; + self.salt[..N].copy_from_slice(&salt); } } -/// The verifier the key hands out: hashes the message and finishes with RSAVP1 and the -/// encoding's verification. -pub struct RsaPssVerifier< - 'k, - H, - const H_LEN: usize, - const SEED_LEN: usize, - const S_LEN: usize, - const M_PRIME_LEN: usize, - const DB_LEN: usize, - const L: usize, - const L2: usize, - const L21: usize, - const HALF: usize, - const HALF2: usize, - const HALF21: usize, - const K_LEN: usize, - const SK_LEN: usize, - const PK_LEN: usize, -> { - pk: &'k RsaPublicKey, +/// The verifier [`VerifyingKey::create_verifier`] hands out: the key, borrowed, and the running +/// hash. +pub struct RsaPssVerifier<'k, K: RsaSize, H> { + pk: &'k RsaPublicKey, hash: H, } -impl< - H: HashOneShot, - const H_LEN: usize, - const SEED_LEN: usize, - const S_LEN: usize, - const M_PRIME_LEN: usize, - const DB_LEN: usize, - const L: usize, - const L2: usize, - const L21: usize, - const HALF: usize, - const HALF2: usize, - const HALF21: usize, - const K_LEN: usize, - const SK_LEN: usize, - const PK_LEN: usize, -> - SigningKey< - RSASSA_PSS< - H, - H_LEN, - SEED_LEN, - S_LEN, - M_PRIME_LEN, - DB_LEN, - L, - L2, - L21, - HALF, - HALF2, - HALF21, - K_LEN, - SK_LEN, - PK_LEN, - >, - K_LEN, - > for RsaPrivateKey +impl SigningKey, K_LEN> for RsaPrivateKey where - // Only a private key type this crate has declared signable (a `SignaturePrivateKey` impl in - // its size module) signs: the verify-only sizes, RSA-1024/1536, have none, so this impl does - // not exist for them -- compile-time enforcement of the crate's `# Scope`. - RsaPrivateKey: SignaturePrivateKey, + // 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. + K: RsaSigningSize + RsaSize, + H: HashOneShot + HashAlgParams, { type Signer<'k> - = RsaPssSigner< - 'k, - H, - H_LEN, - SEED_LEN, - S_LEN, - M_PRIME_LEN, - DB_LEN, - L, - L2, - L21, - HALF, - HALF2, - HALF21, - K_LEN, - SK_LEN, - PK_LEN, - > + = RsaPssSigner<'k, K, H> where Self: 'k; @@ -292,71 +88,19 @@ where _ctx: Option<&[u8]>, ) -> Result, SignatureError> { // EMSA-PSS-ENCODE step 4's salt, drawn when the signer is created, as ECDSA draws `k`. - let mut salt = [0u8; S_LEN]; - rng.next_bytes_out(&mut salt).map_err(SignatureError::RNGError)?; + let mut salt = [0u8; MAX_HASH_LEN]; + rng.next_bytes_out(&mut salt[..H::OUTPUT_LEN]).map_err(SignatureError::RNGError)?; Ok(RsaPssSigner { sk: self, hash: H::default(), salt }) } } -impl< - H: HashOneShot, - const H_LEN: usize, - const SEED_LEN: usize, - const S_LEN: usize, - const M_PRIME_LEN: usize, - const DB_LEN: usize, - const L: usize, - const L2: usize, - const L21: usize, - const HALF: usize, - const HALF2: usize, - const HALF21: usize, - const K_LEN: usize, - const SK_LEN: usize, - const PK_LEN: usize, -> - VerifyingKey< - RSASSA_PSS< - H, - H_LEN, - SEED_LEN, - S_LEN, - M_PRIME_LEN, - DB_LEN, - L, - L2, - L21, - HALF, - HALF2, - HALF21, - K_LEN, - SK_LEN, - PK_LEN, - >, - K_LEN, - > for RsaPublicKey +impl VerifyingKey, K_LEN> for RsaPublicKey where - RsaPublicKey: SignaturePublicKey, + K: RsaSize, + H: HashOneShot + HashAlgParams, { type Verifier<'k> - = RsaPssVerifier< - 'k, - H, - H_LEN, - SEED_LEN, - S_LEN, - M_PRIME_LEN, - DB_LEN, - L, - L2, - L21, - HALF, - HALF2, - HALF21, - K_LEN, - SK_LEN, - PK_LEN, - > + = RsaPssVerifier<'k, K, H> where Self: 'k; @@ -368,142 +112,33 @@ where } } -impl< - H: HashOneShot, - const H_LEN: usize, - const SEED_LEN: usize, - const S_LEN: usize, - const M_PRIME_LEN: usize, - const DB_LEN: usize, - const L: usize, - const L2: usize, - const L21: usize, - const HALF: usize, - const HALF2: usize, - const HALF21: usize, - const K_LEN: usize, - const SK_LEN: usize, - const PK_LEN: usize, -> AlgorithmInfo - for RsaPssSigner< - '_, - H, - H_LEN, - SEED_LEN, - S_LEN, - M_PRIME_LEN, - DB_LEN, - L, - L2, - L21, - HALF, - HALF2, - HALF21, - K_LEN, - SK_LEN, - PK_LEN, - > -{ +impl AlgorithmInfo for RsaPssSigner<'_, K, H> { fn alg_name(&self) -> &'static str { - as Algorithm>::ALG_NAME + RSASSA_PSS::::ALG_NAME } fn max_security_strength(&self) -> SecurityStrength { - as Algorithm>::MAX_SECURITY_STRENGTH + RSASSA_PSS::::MAX_SECURITY_STRENGTH } } -impl< - H: HashOneShot, - const H_LEN: usize, - const SEED_LEN: usize, - const S_LEN: usize, - const M_PRIME_LEN: usize, - const DB_LEN: usize, - const L: usize, - const L2: usize, - const L21: usize, - const HALF: usize, - const HALF2: usize, - const HALF21: usize, - const K_LEN: usize, - const SK_LEN: usize, - const PK_LEN: usize, -> SignatureSigner - for RsaPssSigner< - '_, - H, - H_LEN, - SEED_LEN, - S_LEN, - M_PRIME_LEN, - DB_LEN, - L, - L2, - L21, - HALF, - HALF2, - HALF21, - K_LEN, - SK_LEN, - PK_LEN, - > +impl SignatureSigner for RsaPssSigner<'_, K, H> +where + K: RsaSigningSize + RsaSize, + H: HashOneShot + HashAlgParams, { fn do_update(&mut self, msg_chunk: &[u8]) { self.hash.do_update(msg_chunk); } fn do_final(self) -> Result<[u8; K_LEN], SignatureError> { - // The encoding's first step, `Hash(M)`, completed here over the streamed chunks. - let mut m_hash = [0u8; H_LEN]; - self.hash.do_final_out(&mut m_hash); - sign_from_hash_with_salt::< - H, - H_LEN, - SEED_LEN, - S_LEN, - M_PRIME_LEN, - DB_LEN, - L, - L2, - L21, - HALF, - HALF2, - HALF21, - K_LEN, - >(self.sk, &m_hash, &self.salt) + let mut m_hash = [0u8; MAX_HASH_LEN]; + self.hash.do_final_out(&mut m_hash[..H::OUTPUT_LEN]); + sign_from_hash_with_salt::( + self.sk, + &m_hash[..H::OUTPUT_LEN], + &self.salt[..H::OUTPUT_LEN], + ) } fn do_final_out(self, output: &mut [u8; K_LEN]) -> Result { @@ -513,242 +148,99 @@ impl< } } -impl< - H: HashOneShot, - const H_LEN: usize, - const SEED_LEN: usize, - const S_LEN: usize, - const M_PRIME_LEN: usize, - const DB_LEN: usize, - const L: usize, - const L2: usize, - const L21: usize, - const HALF: usize, - const HALF2: usize, - const HALF21: usize, - const K_LEN: usize, - const SK_LEN: usize, - const PK_LEN: usize, -> AlgorithmInfo - for RsaPssVerifier< - '_, - H, - H_LEN, - SEED_LEN, - S_LEN, - M_PRIME_LEN, - DB_LEN, - L, - L2, - L21, - HALF, - HALF2, - HALF21, - K_LEN, - SK_LEN, - PK_LEN, - > -{ +impl AlgorithmInfo for RsaPssVerifier<'_, K, H> { fn alg_name(&self) -> &'static str { - as Algorithm>::ALG_NAME + RSASSA_PSS::::ALG_NAME } fn max_security_strength(&self) -> SecurityStrength { - as Algorithm>::MAX_SECURITY_STRENGTH + RSASSA_PSS::::MAX_SECURITY_STRENGTH } } -impl< - H: HashOneShot, - const H_LEN: usize, - const SEED_LEN: usize, - const S_LEN: usize, - const M_PRIME_LEN: usize, - const DB_LEN: usize, - const L: usize, - const L2: usize, - const L21: usize, - const HALF: usize, - const HALF2: usize, - const HALF21: usize, - const K_LEN: usize, - const SK_LEN: usize, - const PK_LEN: usize, -> SignatureVerifier - for RsaPssVerifier< - '_, - H, - H_LEN, - SEED_LEN, - S_LEN, - M_PRIME_LEN, - DB_LEN, - L, - L2, - L21, - HALF, - HALF2, - HALF21, - K_LEN, - SK_LEN, - PK_LEN, - > +impl SignatureVerifier for RsaPssVerifier<'_, K, H> +where + K: RsaSize, + H: HashOneShot + HashAlgParams, { fn do_update(&mut self, msg_chunk: &[u8]) { self.hash.do_update(msg_chunk); } fn do_verify_final(self, sig: &[u8]) -> Result<(), SignatureError> { - // RFC 8017 §8.1.2 / §8.2.2 step 1, "Length checking: If the length of the signature S is - // not k octets, output "invalid signature" and stop", reported as the length error the - // shared suite expects for a signature of the wrong size. + // RFC 8017 §8.1.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 mut m_hash = [0u8; H_LEN]; - self.hash.do_final_out(&mut m_hash); - // 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, sig, - ) - .map_err(|_| SignatureError::SignatureVerificationFailed) + let mut m_hash = [0u8; MAX_HASH_LEN]; + self.hash.do_final_out(&mut m_hash[..H::OUTPUT_LEN]); + verify_from_hash::(self.pk, &m_hash[..H::OUTPUT_LEN], sig) + .map_err(|_| SignatureError::SignatureVerificationFailed) } } -/// RSASSA-PSS-SIGN (RFC 8017 §8.1.1) with the salt supplied directly rather than drawn from an -/// RNG, given the message's hash `m_hash` (`H`'s output over the message) rather than the message -/// itself -- what [`RsaPssSigner`]'s `do_final` calls once it has hashed the streamed -/// message and settled the salt. EMSA-PSS is randomized only in its choice of salt (§9.1's own -/// note 5), so a fixed salt makes this deterministic and directly testable against a known salt. -pub fn sign_from_hash_with_salt< - H: HashOneShot, - const H_LEN: usize, - const SEED_LEN: usize, - const S_LEN: usize, - const M_PRIME_LEN: usize, - const DB_LEN: usize, - const L: usize, - const L2: usize, - const L21: usize, - const HALF: usize, - const HALF2: usize, - const HALF21: usize, - const K_LEN: usize, ->( - sk: &RsaPrivateKey, - m_hash: &[u8; H_LEN], - salt: &[u8; S_LEN], -) -> Result<[u8; K_LEN], SignatureError> { - let em = emsa_pss_encode_from_hash::( - m_hash, salt, - ); - let m = limbs_from_be_bytes::(&em); - let s = rsasp1::(sk, &m)?; - Ok(be_bytes_from_limbs::(&s)) +/// RSASSA-PSS-SIGN (RFC 8017 §8.1.1) from the message hash (`H::OUTPUT_LEN` bytes) with the +/// salt given (the same length): the EMSA-PSS encoding, then RSASP1. The known-answer entry +/// point; [`sign_from_hash`] draws the salt. +/// +/// # Errors +/// [`SignatureError::DecodingError`] if the encoded message is not below `n`, which the +/// encoding's cleared top bit rules out. +pub fn sign_from_hash_with_salt( + sk: &RsaPrivateKey, + m_hash: &[u8], + salt: &[u8], +) -> Result<[u8; K_LEN], SignatureError> +where + K: RsaSigningSize + RsaSize, + H: HashOneShot + HashAlgParams, +{ + let em = emsa_pss_encode_from_hash::(m_hash, salt); + let m = K::limbs_from_be_bytes(&em); + let s = rsasp1::(sk, &m)?; + Ok(K::be_bytes_from_limbs(&s)) } -/// RSASSA-PSS-SIGN (RFC 8017 §8.1.1) given the message's hash `m_hash` instead of the message: -/// draws a fresh `S_LEN`-byte salt from `rng` (EMSA-PSS-ENCODE step 4) and hands both to +/// RSASSA-PSS-SIGN (RFC 8017 §8.1.1) from the message hash, with a fresh salt of one hash +/// output drawn from `rng` (EMSA-PSS-ENCODE step 4). +/// +/// # Errors +/// [`SignatureError::RNGError`] if the RNG fails to deliver; otherwise as /// [`sign_from_hash_with_salt`]. -pub fn sign_from_hash< - H: HashOneShot, - const H_LEN: usize, - const SEED_LEN: usize, - const S_LEN: usize, - const M_PRIME_LEN: usize, - const DB_LEN: usize, - const L: usize, - const L2: usize, - const L21: usize, - const HALF: usize, - const HALF2: usize, - const HALF21: usize, - const K_LEN: usize, ->( - sk: &RsaPrivateKey, - m_hash: &[u8; H_LEN], +pub fn sign_from_hash( + sk: &RsaPrivateKey, + m_hash: &[u8], rng: &mut dyn RNG, -) -> Result<[u8; K_LEN], SignatureError> { - let mut salt = [0u8; S_LEN]; - rng.next_bytes_out(&mut salt).map_err(SignatureError::RNGError)?; - sign_from_hash_with_salt::< - H, - H_LEN, - SEED_LEN, - S_LEN, - M_PRIME_LEN, - DB_LEN, - L, - L2, - L21, - HALF, - HALF2, - HALF21, - K_LEN, - >(sk, m_hash, &salt) +) -> Result<[u8; K_LEN], SignatureError> +where + K: RsaSigningSize + RsaSize, + H: HashOneShot + HashAlgParams, +{ + let mut salt = [0u8; MAX_HASH_LEN]; + rng.next_bytes_out(&mut salt[..H::OUTPUT_LEN]).map_err(SignatureError::RNGError)?; + sign_from_hash_with_salt::(sk, m_hash, &salt[..H::OUTPUT_LEN]) } -/// RSASSA-PSS-VERIFY (RFC 8017 §8.1.2) given the message's hash `m_hash` instead of the message -/// (the counterpart of [`sign_from_hash`]): recovers `EM = I2OSP(RSAVP1((n, e), OS2IP(S)), -/// emLen)` and checks it against `m_hash` via EMSA-PSS-VERIFY, which recovers the salt from `EM` -/// itself (§9.1.2) rather than needing it supplied. RSAVP1's range error propagates as its own -/// `Err`, as in [`crate::rsassa_pkcs1_v1_5::verify_from_hash`]. -pub fn verify_from_hash< - H: HashOneShot, - const H_LEN: usize, - const SEED_LEN: usize, - const S_LEN: usize, - const M_PRIME_LEN: usize, - const DB_LEN: usize, - const L: usize, - const L2: usize, - const L21: usize, - const K_LEN: usize, ->( - pk: &RsaPublicKey, - m_hash: &[u8; H_LEN], +/// RSASSA-PSS-VERIFY (RFC 8017 §8.1.2) from the message hash: RSAVP1, then the EMSA-PSS +/// verification against `m_hash`. +/// +/// # Errors +/// [`SignatureError::DecodingError`] for a signature representative not below `n` (step 2.b's +/// "invalid signature" from RSAVP1), [`SignatureError::SignatureVerificationFailed`] for an +/// encoding that does not verify. +pub fn verify_from_hash( + pk: &RsaPublicKey, + m_hash: &[u8], signature: &[u8; K_LEN], -) -> Result<(), SignatureError> { - let s = limbs_from_be_bytes::(signature); - let m = rsavp1::(pk, &s)?; - let em = be_bytes_from_limbs::(&m); - - if emsa_pss_verify_from_hash::( - m_hash, &em, - ) { +) -> Result<(), SignatureError> +where + K: RsaSize, + H: HashOneShot + HashAlgParams, +{ + let s = K::limbs_from_be_bytes(signature); + let m = rsavp1::(pk, &s)?; + let em = K::be_bytes_from_limbs(&m); + if emsa_pss_verify_from_hash::(m_hash, &em) { Ok(()) } else { Err(SignatureError::SignatureVerificationFailed) diff --git a/crypto/rsa/src/rsassa_pss_shake.rs b/crypto/rsa/src/rsassa_pss_shake.rs index f8f4da7f..4ad8432c 100644 --- a/crypto/rsa/src/rsassa_pss_shake.rs +++ b/crypto/rsa/src/rsassa_pss_shake.rs @@ -1,272 +1,84 @@ //! RSASSA-PSS with SHAKE128 or SHAKE256 as both the hash and the (native, non-MGF1) mask //! generation function -- `id-RSASSA-PSS-SHAKE128`/`id-RSASSA-PSS-SHAKE256` (RFC 8702 §3.2.1). -//! Otherwise identical to [`crate::rsassa_pss`] (RFC 8017 §8.1): same RSASP1/RSAVP1 orchestration, -//! same fresh-salt-per-signature approach, just built on [`crate::emsa_pss_shake`] in place of -//! [`crate::emsa_pss`] -- and the same [`RSASSA_PSS_SHAKE`] marker over `*_from_hash` functions, -//! with `X: XOF` in place of `H: Hash` and no `SEED_LEN` (there is no MGF1 counter to size). +//! Otherwise identical to [`crate::rsassa_pss`] (RFC 8017 §8.1): same RSASP1/RSAVP1 +//! orchestration, same fresh-salt-per-signature approach, just built on `emsa_pss_shake` in +//! place of `emsa_pss` -- and the same [`RSASSA_PSS_SHAKE`] marker over `*_from_hash` +//! functions, with `X: XOF` in place of `H: Hash`. -use crate::codec::{be_bytes_from_limbs, limbs_from_be_bytes}; use crate::emsa_pss_shake::{emsa_pss_encode_shake_from_hash, emsa_pss_verify_shake_from_hash}; -use crate::keys::{RsaPrivateKey, RsaPublicKey, modulus_strength}; +use crate::keys::{RsaPrivateKey, RsaPublicKey}; +use crate::mgf1::MAX_HASH_LEN; use crate::rsa_core::{rsasp1, rsavp1}; +use crate::size::{RsaSigningSize, RsaSize, min_strength}; use bouncycastle_core::errors::SignatureError; use bouncycastle_core::security_strength::SecurityStrength; use bouncycastle_core::signature_key::{SignatureAlgorithm, SigningKey, VerifyingKey}; use bouncycastle_core::traits::{ - Algorithm, AlgorithmInfo, HashOneShot, RNG, SignaturePrivateKey, SignaturePublicKey, - SignatureSigner, SignatureVerifier, XOF, + Algorithm, AlgorithmInfo, HashAlgParams, HashOneShot, RNG, SignatureSigner, SignatureVerifier, + XOF, }; +use bouncycastle_utils::const_str::ConstStr; use core::marker::PhantomData; -/// RSASSA-PSS with a SHAKE XOF `X` as both hash and mask (RFC 8702 §3.2.1), at a modulus of `L` limbs: the algorithm marker the key role -/// traits are implemented over, with every width fixed by the aliases in the size modules -/// (`rsa_2048::RSASSA_PSS_SHAKE_SHA256` and siblings). -/// `RsaPrivateKey` signs through [`SigningKey`]: a fresh `S_LEN`-byte salt from the caller's RNG -/// per signer (EMSA-PSS-ENCODE step 4), so two signatures of one message differ. -/// `RsaPublicKey` verifies through [`VerifyingKey`]. One key type serves every scheme and hash, so -/// a call names the marker: `SigningKey::::...(&sk, ..)`. `ctx` is -/// accepted and ignored, since RSA has no context string. +/// RSASSA-PSS with a SHAKE XOF `X` as both hash and mask (RFC 8702 §3.2.1), at the modulus size `K`: the algorithm marker the key role traits are implemented +/// over, named `RSASSA-PSS-` (`RSASSA-PSS-SHAKE128`), at the lesser of the size's and the hash's +/// strength. [`RsaPrivateKey`] signs through [`SigningKey`] at a signing size: a fresh salt, one +/// hash output long, from the caller's RNG per signer (EMSA-PSS-ENCODE step 4), so two +/// signatures of one message differ. [`RsaPublicKey`] verifies through [`VerifyingKey`] at any +/// size. One key type serves every scheme and hash, so a call names the marker: +/// `SigningKey::::sign(&sk, ..)`. `ctx` is accepted and +/// ignored, since RSA has no context string. #[allow(non_camel_case_types)] -pub struct RSASSA_PSS_SHAKE< - X, - const H_LEN: usize, - const S_LEN: usize, - const M_PRIME_LEN: usize, - const DB_LEN: usize, - const L: usize, - const L2: usize, - const L21: usize, - const HALF: usize, - const HALF2: usize, - const HALF21: usize, - const K_LEN: usize, - const SK_LEN: usize, - const PK_LEN: usize, -> { - _hash: PhantomData, +pub struct RSASSA_PSS_SHAKE { + _params: PhantomData<(K, X)>, } -impl< - X, - const H_LEN: usize, - const S_LEN: usize, - const M_PRIME_LEN: usize, - const DB_LEN: usize, - const L: usize, - const L2: usize, - const L21: usize, - const HALF: usize, - const HALF2: usize, - const HALF21: usize, - const K_LEN: usize, - const SK_LEN: usize, - const PK_LEN: usize, -> Algorithm - for RSASSA_PSS_SHAKE< - X, - H_LEN, - S_LEN, - M_PRIME_LEN, - DB_LEN, - L, - L2, - L21, - HALF, - HALF2, - HALF21, - K_LEN, - SK_LEN, - PK_LEN, - > -{ - const ALG_NAME: &'static str = "RSASSA-PSS-SHAKE"; - /// From the modulus width, by SP 800-57 Part 1 Rev. 5 Table 2; see [`modulus_strength`]. - const MAX_SECURITY_STRENGTH: SecurityStrength = modulus_strength(L); +impl RSASSA_PSS_SHAKE { + const NAME: ConstStr<40> = ConstStr::concat(&["RSASSA-PSS-", X::ALG_NAME]); } -impl< - X, - const H_LEN: usize, - const S_LEN: usize, - const M_PRIME_LEN: usize, - const DB_LEN: usize, - const L: usize, - const L2: usize, - const L21: usize, - const HALF: usize, - const HALF2: usize, - const HALF21: usize, - const K_LEN: usize, - const SK_LEN: usize, - const PK_LEN: usize, -> SignatureAlgorithm - for RSASSA_PSS_SHAKE< - X, - H_LEN, - S_LEN, - M_PRIME_LEN, - DB_LEN, - L, - L2, - L21, - HALF, - HALF2, - HALF21, - K_LEN, - SK_LEN, - PK_LEN, - > -{ +impl Algorithm for RSASSA_PSS_SHAKE { + const ALG_NAME: &'static str = Self::NAME.as_str(); + const MAX_SECURITY_STRENGTH: SecurityStrength = + min_strength(K::STRENGTH, X::MAX_SECURITY_STRENGTH); } -/// The signer the key hands out; it hashes the message and finishes with [`RSASSA_PSS_SHAKE`]'s encoding and -/// RSASP1. `set_salt` replaces the drawn salt, for a known-answer test; the signature then depends on the key and message alone. -pub struct RsaPssShakeSigner< - 'k, - X, - const H_LEN: usize, - const S_LEN: usize, - const M_PRIME_LEN: usize, - const DB_LEN: usize, - const L: usize, - const L2: usize, - const L21: usize, - const HALF: usize, - const HALF2: usize, - const HALF21: usize, - const K_LEN: usize, - const SK_LEN: usize, - const PK_LEN: usize, -> { - sk: &'k RsaPrivateKey, +impl SignatureAlgorithm for RSASSA_PSS_SHAKE {} + +/// The signer [`SigningKey::create_signer`] hands out: the key, borrowed, the running hash and +/// the salt (the first `X::OUTPUT_LEN` bytes of the buffer). +pub struct RsaPssShakeSigner<'k, K: RsaSize, X> { + sk: &'k RsaPrivateKey, hash: X, - salt: [u8; S_LEN], + salt: [u8; MAX_HASH_LEN], } -impl< - 'k, - X: XOF + HashOneShot, - const H_LEN: usize, - const S_LEN: usize, - const M_PRIME_LEN: usize, - const DB_LEN: usize, - const L: usize, - const L2: usize, - const L21: usize, - const HALF: usize, - const HALF2: usize, - const HALF21: usize, - const K_LEN: usize, - const SK_LEN: usize, - const PK_LEN: usize, -> - RsaPssShakeSigner< - 'k, - X, - H_LEN, - S_LEN, - M_PRIME_LEN, - DB_LEN, - L, - L2, - L21, - HALF, - HALF2, - HALF21, - K_LEN, - SK_LEN, - PK_LEN, - > -{ - /// Replaces the salt drawn at creation with `salt`, for a known-answer test against a - /// published salt; the signature then depends on the key and message alone. - pub fn set_salt(&mut self, salt: [u8; S_LEN]) { - self.salt = salt; +impl RsaPssShakeSigner<'_, K, X> { + /// Replaces the salt drawn when the signer was created, for a known-answer test; `N` must be + /// the hash's output length, which is checked when the call is compiled. + pub fn set_salt(&mut self, salt: [u8; N]) { + const { assert!(N == X::OUTPUT_LEN, "the PSS salt is one hash output long") }; + self.salt[..N].copy_from_slice(&salt); } } -/// The verifier the key hands out: hashes the message and finishes with RSAVP1 and the -/// encoding's verification. -pub struct RsaPssShakeVerifier< - 'k, - X, - const H_LEN: usize, - const S_LEN: usize, - const M_PRIME_LEN: usize, - const DB_LEN: usize, - const L: usize, - const L2: usize, - const L21: usize, - const HALF: usize, - const HALF2: usize, - const HALF21: usize, - const K_LEN: usize, - const SK_LEN: usize, - const PK_LEN: usize, -> { - pk: &'k RsaPublicKey, +/// The verifier [`VerifyingKey::create_verifier`] hands out: the key, borrowed, and the running +/// hash. +pub struct RsaPssShakeVerifier<'k, K: RsaSize, X> { + pk: &'k RsaPublicKey, hash: X, } -impl< - X: XOF + HashOneShot, - const H_LEN: usize, - const S_LEN: usize, - const M_PRIME_LEN: usize, - const DB_LEN: usize, - const L: usize, - const L2: usize, - const L21: usize, - const HALF: usize, - const HALF2: usize, - const HALF21: usize, - const K_LEN: usize, - const SK_LEN: usize, - const PK_LEN: usize, -> - SigningKey< - RSASSA_PSS_SHAKE< - X, - H_LEN, - S_LEN, - M_PRIME_LEN, - DB_LEN, - L, - L2, - L21, - HALF, - HALF2, - HALF21, - K_LEN, - SK_LEN, - PK_LEN, - >, - K_LEN, - > for RsaPrivateKey +impl SigningKey, K_LEN> for RsaPrivateKey where - // Only a private key type this crate has declared signable (a `SignaturePrivateKey` impl in - // its size module) signs: the verify-only sizes, RSA-1024/1536, have none, so this impl does - // not exist for them -- compile-time enforcement of the crate's `# Scope`. - RsaPrivateKey: SignaturePrivateKey, + // 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. + K: RsaSigningSize + RsaSize, + X: XOF + HashOneShot + HashAlgParams, { type Signer<'k> - = RsaPssShakeSigner< - 'k, - X, - H_LEN, - S_LEN, - M_PRIME_LEN, - DB_LEN, - L, - L2, - L21, - HALF, - HALF2, - HALF21, - K_LEN, - SK_LEN, - PK_LEN, - > + = RsaPssShakeSigner<'k, K, X> where Self: 'k; @@ -276,68 +88,19 @@ where _ctx: Option<&[u8]>, ) -> Result, SignatureError> { // EMSA-PSS-ENCODE step 4's salt, drawn when the signer is created, as ECDSA draws `k`. - let mut salt = [0u8; S_LEN]; - rng.next_bytes_out(&mut salt).map_err(SignatureError::RNGError)?; + let mut salt = [0u8; MAX_HASH_LEN]; + rng.next_bytes_out(&mut salt[..X::OUTPUT_LEN]).map_err(SignatureError::RNGError)?; Ok(RsaPssShakeSigner { sk: self, hash: X::default(), salt }) } } -impl< - X: XOF + HashOneShot, - const H_LEN: usize, - const S_LEN: usize, - const M_PRIME_LEN: usize, - const DB_LEN: usize, - const L: usize, - const L2: usize, - const L21: usize, - const HALF: usize, - const HALF2: usize, - const HALF21: usize, - const K_LEN: usize, - const SK_LEN: usize, - const PK_LEN: usize, -> - VerifyingKey< - RSASSA_PSS_SHAKE< - X, - H_LEN, - S_LEN, - M_PRIME_LEN, - DB_LEN, - L, - L2, - L21, - HALF, - HALF2, - HALF21, - K_LEN, - SK_LEN, - PK_LEN, - >, - K_LEN, - > for RsaPublicKey +impl VerifyingKey, K_LEN> for RsaPublicKey where - RsaPublicKey: SignaturePublicKey, + K: RsaSize, + X: XOF + HashOneShot + HashAlgParams, { type Verifier<'k> - = RsaPssShakeVerifier< - 'k, - X, - H_LEN, - S_LEN, - M_PRIME_LEN, - DB_LEN, - L, - L2, - L21, - HALF, - HALF2, - HALF21, - K_LEN, - SK_LEN, - PK_LEN, - > + = RsaPssShakeVerifier<'k, K, X> where Self: 'k; @@ -349,135 +112,33 @@ where } } -impl< - X: XOF + HashOneShot, - const H_LEN: usize, - const S_LEN: usize, - const M_PRIME_LEN: usize, - const DB_LEN: usize, - const L: usize, - const L2: usize, - const L21: usize, - const HALF: usize, - const HALF2: usize, - const HALF21: usize, - const K_LEN: usize, - const SK_LEN: usize, - const PK_LEN: usize, -> AlgorithmInfo - for RsaPssShakeSigner< - '_, - X, - H_LEN, - S_LEN, - M_PRIME_LEN, - DB_LEN, - L, - L2, - L21, - HALF, - HALF2, - HALF21, - K_LEN, - SK_LEN, - PK_LEN, - > -{ +impl AlgorithmInfo for RsaPssShakeSigner<'_, K, X> { fn alg_name(&self) -> &'static str { - as Algorithm>::ALG_NAME + RSASSA_PSS_SHAKE::::ALG_NAME } fn max_security_strength(&self) -> SecurityStrength { - as Algorithm>::MAX_SECURITY_STRENGTH + RSASSA_PSS_SHAKE::::MAX_SECURITY_STRENGTH } } -impl< - X: XOF + HashOneShot, - const H_LEN: usize, - const S_LEN: usize, - const M_PRIME_LEN: usize, - const DB_LEN: usize, - const L: usize, - const L2: usize, - const L21: usize, - const HALF: usize, - const HALF2: usize, - const HALF21: usize, - const K_LEN: usize, - const SK_LEN: usize, - const PK_LEN: usize, -> SignatureSigner - for RsaPssShakeSigner< - '_, - X, - H_LEN, - S_LEN, - M_PRIME_LEN, - DB_LEN, - L, - L2, - L21, - HALF, - HALF2, - HALF21, - K_LEN, - SK_LEN, - PK_LEN, - > +impl SignatureSigner for RsaPssShakeSigner<'_, K, X> +where + K: RsaSigningSize + RsaSize, + X: XOF + HashOneShot + HashAlgParams, { fn do_update(&mut self, msg_chunk: &[u8]) { self.hash.do_update(msg_chunk); } fn do_final(self) -> Result<[u8; K_LEN], SignatureError> { - // The encoding's first step, `Hash(M)`, completed here over the streamed chunks. - let mut m_hash = [0u8; H_LEN]; - self.hash.do_final_out(&mut m_hash); - sign_from_hash_with_salt::< - X, - H_LEN, - S_LEN, - M_PRIME_LEN, - DB_LEN, - L, - L2, - L21, - HALF, - HALF2, - HALF21, - K_LEN, - >(self.sk, &m_hash, &self.salt) + let mut m_hash = [0u8; MAX_HASH_LEN]; + self.hash.do_final_out(&mut m_hash[..X::OUTPUT_LEN]); + sign_from_hash_with_salt::( + self.sk, + &m_hash[..X::OUTPUT_LEN], + &self.salt[..X::OUTPUT_LEN], + ) } fn do_final_out(self, output: &mut [u8; K_LEN]) -> Result { @@ -487,228 +148,99 @@ impl< } } -impl< - X: XOF + HashOneShot, - const H_LEN: usize, - const S_LEN: usize, - const M_PRIME_LEN: usize, - const DB_LEN: usize, - const L: usize, - const L2: usize, - const L21: usize, - const HALF: usize, - const HALF2: usize, - const HALF21: usize, - const K_LEN: usize, - const SK_LEN: usize, - const PK_LEN: usize, -> AlgorithmInfo - for RsaPssShakeVerifier< - '_, - X, - H_LEN, - S_LEN, - M_PRIME_LEN, - DB_LEN, - L, - L2, - L21, - HALF, - HALF2, - HALF21, - K_LEN, - SK_LEN, - PK_LEN, - > -{ +impl AlgorithmInfo for RsaPssShakeVerifier<'_, K, X> { fn alg_name(&self) -> &'static str { - as Algorithm>::ALG_NAME + RSASSA_PSS_SHAKE::::ALG_NAME } fn max_security_strength(&self) -> SecurityStrength { - as Algorithm>::MAX_SECURITY_STRENGTH + RSASSA_PSS_SHAKE::::MAX_SECURITY_STRENGTH } } -impl< - X: XOF + HashOneShot, - const H_LEN: usize, - const S_LEN: usize, - const M_PRIME_LEN: usize, - const DB_LEN: usize, - const L: usize, - const L2: usize, - const L21: usize, - const HALF: usize, - const HALF2: usize, - const HALF21: usize, - const K_LEN: usize, - const SK_LEN: usize, - const PK_LEN: usize, -> SignatureVerifier - for RsaPssShakeVerifier< - '_, - X, - H_LEN, - S_LEN, - M_PRIME_LEN, - DB_LEN, - L, - L2, - L21, - HALF, - HALF2, - HALF21, - K_LEN, - SK_LEN, - PK_LEN, - > +impl SignatureVerifier for RsaPssShakeVerifier<'_, K, X> +where + K: RsaSize, + X: XOF + HashOneShot + HashAlgParams, { fn do_update(&mut self, msg_chunk: &[u8]) { self.hash.do_update(msg_chunk); } fn do_verify_final(self, sig: &[u8]) -> Result<(), SignatureError> { - // RFC 8017 §8.1.2 / §8.2.2 step 1, "Length checking: If the length of the signature S is - // not k octets, output "invalid signature" and stop", reported as the length error the - // shared suite expects for a signature of the wrong size. + // RFC 8017 §8.1.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 mut m_hash = [0u8; H_LEN]; - self.hash.do_final_out(&mut m_hash); - // 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, sig, - ) - .map_err(|_| SignatureError::SignatureVerificationFailed) + let mut m_hash = [0u8; MAX_HASH_LEN]; + self.hash.do_final_out(&mut m_hash[..X::OUTPUT_LEN]); + verify_from_hash::(self.pk, &m_hash[..X::OUTPUT_LEN], sig) + .map_err(|_| SignatureError::SignatureVerificationFailed) } } -/// RSASSA-PSS-SIGN (RFC 8017 §8.1.1) with the salt supplied directly, given the message's hash -/// `m_hash` (`X`'s `H_LEN`-byte output over the message) rather than the message -- mirroring -/// [`crate::rsassa_pss::sign_from_hash_with_salt`], and what [`RsaPssShakeSigner`]'s `do_final` -/// calls. -pub fn sign_from_hash_with_salt< - X: XOF + HashOneShot, - const H_LEN: usize, - const S_LEN: usize, - const M_PRIME_LEN: usize, - const DB_LEN: usize, - const L: usize, - const L2: usize, - const L21: usize, - const HALF: usize, - const HALF2: usize, - const HALF21: usize, - const K_LEN: usize, ->( - sk: &RsaPrivateKey, - m_hash: &[u8; H_LEN], - salt: &[u8; S_LEN], -) -> Result<[u8; K_LEN], SignatureError> { - let em = emsa_pss_encode_shake_from_hash::( - m_hash, salt, - ); - let m = limbs_from_be_bytes::(&em); - let s = rsasp1::(sk, &m)?; - Ok(be_bytes_from_limbs::(&s)) +/// RSASSA-PSS-SIGN (RFC 8017 §8.1.1) from the message hash (`X::OUTPUT_LEN` bytes) with the +/// salt given (the same length): the EMSA-PSS encoding, then RSASP1. The known-answer entry +/// point; [`sign_from_hash`] draws the salt. +/// +/// # Errors +/// [`SignatureError::DecodingError`] if the encoded message is not below `n`, which the +/// encoding's cleared top bit rules out. +pub fn sign_from_hash_with_salt( + sk: &RsaPrivateKey, + m_hash: &[u8], + salt: &[u8], +) -> Result<[u8; K_LEN], SignatureError> +where + K: RsaSigningSize + RsaSize, + X: XOF + HashOneShot + HashAlgParams, +{ + let em = emsa_pss_encode_shake_from_hash::(m_hash, salt); + let m = K::limbs_from_be_bytes(&em); + let s = rsasp1::(sk, &m)?; + Ok(K::be_bytes_from_limbs(&s)) } -/// RSASSA-PSS-SIGN (RFC 8017 §8.1.1) given the message's hash `m_hash`: draws a fresh -/// `S_LEN`-byte salt from `rng` (EMSA-PSS-ENCODE step 4; RFC 8702 §3.2.1 fixes `S_LEN` at 32 bytes -/// for `id-RSASSA-PSS-SHAKE128` and 64 for `id-RSASSA-PSS-SHAKE256`) and hands both to +/// RSASSA-PSS-SIGN (RFC 8017 §8.1.1) from the message hash, with a fresh salt of one hash +/// output drawn from `rng` (EMSA-PSS-ENCODE step 4). +/// +/// # Errors +/// [`SignatureError::RNGError`] if the RNG fails to deliver; otherwise as /// [`sign_from_hash_with_salt`]. -pub fn sign_from_hash< - X: XOF + HashOneShot, - const H_LEN: usize, - const S_LEN: usize, - const M_PRIME_LEN: usize, - const DB_LEN: usize, - const L: usize, - const L2: usize, - const L21: usize, - const HALF: usize, - const HALF2: usize, - const HALF21: usize, - const K_LEN: usize, ->( - sk: &RsaPrivateKey, - m_hash: &[u8; H_LEN], +pub fn sign_from_hash( + sk: &RsaPrivateKey, + m_hash: &[u8], rng: &mut dyn RNG, -) -> Result<[u8; K_LEN], SignatureError> { - let mut salt = [0u8; S_LEN]; - rng.next_bytes_out(&mut salt).map_err(SignatureError::RNGError)?; - sign_from_hash_with_salt::< - X, - H_LEN, - S_LEN, - M_PRIME_LEN, - DB_LEN, - L, - L2, - L21, - HALF, - HALF2, - HALF21, - K_LEN, - >(sk, m_hash, &salt) +) -> Result<[u8; K_LEN], SignatureError> +where + K: RsaSigningSize + RsaSize, + X: XOF + HashOneShot + HashAlgParams, +{ + let mut salt = [0u8; MAX_HASH_LEN]; + rng.next_bytes_out(&mut salt[..X::OUTPUT_LEN]).map_err(SignatureError::RNGError)?; + sign_from_hash_with_salt::(sk, m_hash, &salt[..X::OUTPUT_LEN]) } -/// RSASSA-PSS-VERIFY (RFC 8017 §8.1.2) given the message's hash `m_hash`, mirroring -/// [`crate::rsassa_pss::verify_from_hash`] but built on the SHAKE-native EMSA-PSS-VERIFY, which -/// recovers the salt from `EM` itself. -pub fn verify_from_hash< - X: XOF + HashOneShot, - const H_LEN: usize, - const S_LEN: usize, - const M_PRIME_LEN: usize, - const DB_LEN: usize, - const L: usize, - const L2: usize, - const L21: usize, - const K_LEN: usize, ->( - pk: &RsaPublicKey, - m_hash: &[u8; H_LEN], +/// RSASSA-PSS-VERIFY (RFC 8017 §8.1.2) from the message hash: RSAVP1, then the EMSA-PSS +/// verification against `m_hash`. +/// +/// # Errors +/// [`SignatureError::DecodingError`] for a signature representative not below `n` (step 2.b's +/// "invalid signature" from RSAVP1), [`SignatureError::SignatureVerificationFailed`] for an +/// encoding that does not verify. +pub fn verify_from_hash( + pk: &RsaPublicKey, + m_hash: &[u8], signature: &[u8; K_LEN], -) -> Result<(), SignatureError> { - let s = limbs_from_be_bytes::(signature); - let m = rsavp1::(pk, &s)?; - let em = be_bytes_from_limbs::(&m); - - if emsa_pss_verify_shake_from_hash::(m_hash, &em) { +) -> Result<(), SignatureError> +where + K: RsaSize, + X: XOF + HashOneShot + HashAlgParams, +{ + let s = K::limbs_from_be_bytes(signature); + let m = rsavp1::(pk, &s)?; + let em = K::be_bytes_from_limbs(&m); + if emsa_pss_verify_shake_from_hash::(m_hash, &em) { Ok(()) } else { Err(SignatureError::SignatureVerificationFailed) diff --git a/crypto/rsa/src/rsasve.rs b/crypto/rsa/src/rsasve.rs index df42ad25..fdd71f2f 100644 --- a/crypto/rsa/src/rsasve.rs +++ b/crypto/rsa/src/rsasve.rs @@ -1,7 +1,7 @@ //! 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 `()` -//! in each size module, naming [`RSASVE`] as the algorithm and handing out the workers +//! 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). //! @@ -32,10 +32,10 @@ //! * `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 `64 * L` bits long, i.e. its top bit is set. §6.2.1 item 1 gives the key an +//! * `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 `8 * L` bytes +//! 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. //! @@ -44,104 +44,82 @@ //! amounts to full public-key validation, which §6.4.2.2 notes "is not specified in this //! Recommendation". -use crate::codec::{be_bytes_from_limbs, limbs_from_be_bytes}; use crate::keys::{RsaPrivateKey, RsaPublicKey}; -use crate::rsa_core::{crt_exp, public_exp}; +use crate::size::{RsaSigningSize, RsaSize}; use bouncycastle_core::errors::{KEMError, RNGError, SignatureError}; use bouncycastle_core::hazmat::do_hazardous_operations; -use bouncycastle_core::kem_key::KEMAlgorithm; +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, RNG}; -use bouncycastle_ec::nat; -use bouncycastle_utils::secret::Secret; +use bouncycastle_core::traits::{ + Algorithm, KEMDecapsulator, KEMEncapsulator, KEMPrivateKey, KEMPublicKey, 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: "65,537 ≤ e < 2^256". +/// 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 `nLen`-byte draws RSASVE.GENERATE's step 2 makes before it gives up with -/// `GenericError`. §7.2.1.2 step 2.c just says "go to step 2a", with no limit. The limit exists so -/// that a broken RNG, e.g. one stuck on all-`0xFF` output, produces an error rather than a hang, the -/// same reason `crate::keygen` caps its candidate loops. `n`'s top bit is set (see the module docs' -/// `# Key validation`), so a working RNG's draw falls outside `(1, n - 1)` with probability below -/// one half, and 128 draws all fail with probability below `2^-128`. +/// 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; -/// Maps an error from the signature-typed key constructors and key generation this module wraps -/// into its [`KEMError`] equivalent. Every variant those can actually produce keeps its meaning. fn kem_error(e: SignatureError) -> KEMError { match e { - SignatureError::DecodingError(s) => KEMError::DecodingError(s), + 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"), } } -/// Whether `n` is exactly `64 * L` bits: see the module docs' `# Key validation`. -fn has_full_bit_length(n: &[u64; L]) -> bool { - n[L - 1] >> 63 == 1 +/// 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 } -/// `1 < x < n - 1`, the range SP 800-56B Rev. 2 requires of RSAEP's plaintext (§7.1.1 input 2), -/// RSADP's ciphertext (§7.1.2.3 step 1), and RSASVE.GENERATE's `z` (§7.2.1.2 step 2.c). -/// -/// Written as two borrow-outs combined with `&` rather than as a short-circuiting comparison. In -/// RSASVE.GENERATE `x` is the secret `z`, and it should not matter to the timing which half of the -/// test a rejected candidate failed. -fn in_open_range(x: &[u64; L], n: &[u64; L]) -> bool { +/// Whether `1 < x < n - 1` (§7.2.1.2 step 2's range, §7.2.1.3 step 1's check). +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[0] &= !1; - let mut one = [0u64; L]; - one[0] = 1; - // `x - (n - 1)` borrows exactly when `x < n - 1`; `1 - x` borrows exactly when `1 < x`. - let below_n_minus_1 = nat::sub(x, &n_minus_1).1; - let above_1 = nat::sub(&one, x).1; - (below_n_minus_1 & above_1) == 1 + 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 public key-establishment key: an [`RsaPublicKey`] with the extra checks listed in the -/// module docs' `# Key validation`, and a distinct type so that it cannot verify signatures (see -/// `# Key separation`). -/// -/// # Encoding -/// -/// `KEMPublicKey::encode`/`from_bytes` (implemented per size, e.g. for -/// `crate::rsa_2048::RSA2048KEMPublicKey`) use [`RsaPublicKey`]'s layout, `n || e`, unchanged. -/// Decoding applies this type's checks as well as [`RsaPublicKey`]'s. +/// An RSA key-establishment public key at the size `K`: [`RsaPublicKey`] under the KEM roles +/// and the `# Key validation` checks, encoded as it is. #[derive(Clone, Debug, PartialEq, Eq)] -pub struct RsaKEMPublicKey(pub(crate) RsaPublicKey); +pub struct RsaKEMPublicKey(pub(crate) RsaPublicKey); -impl RsaKEMPublicKey { +impl RsaKEMPublicKey { /// Builds a public key from its modulus and exponent. Returns /// `Err(`[`KEMError::DecodingError`]`)` in the cases [`RsaPublicKey::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: &[u64; L], e: u32) -> Result { + pub fn new(n: &K::Limbs, e: u32) -> Result { Self::from_rsa_key(RsaPublicKey::new(n, e).map_err(kem_error)?) } - /// Applies this type's own checks to an already-built [`RsaPublicKey`]. Crate-private, so there - /// is no direct signature-key-to-KEM-key conversion in the public API. Key material still gets - /// in through its raw components or encoding, which the two kinds of key share. - pub(crate) fn from_rsa_key(pk: RsaPublicKey) -> Result { + pub(crate) fn from_rsa_key(pk: RsaPublicKey) -> 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()) { + 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`. - pub fn n(&self) -> &[u64; L] { + /// The modulus `n`, as little-endian limbs. + pub fn n(&self) -> &K::Limbs { self.0.n() } @@ -151,201 +129,109 @@ impl RsaKEMPublicKey { } } -/// Defers to [`RsaPublicKey`]'s `Display`. Required by `KEMPublicKey`'s `Display` supertrait. -impl Display for RsaKEMPublicKey { +impl Display for RsaKEMPublicKey { fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { self.0.fmt(f) } } -/// An RSA private key-establishment key: an [`RsaPrivateKey`] (CRT form) with the modulus -/// bit-length check listed in the module docs' `# Key validation`, and a distinct type so that it -/// cannot sign (see `# Key separation`). -/// -/// # Encoding -/// -/// `KEMPrivateKey::encode`/`from_bytes` (implemented per size, e.g. for -/// `crate::rsa_2048::RSA2048KEMPrivateKey`) use [`RsaPrivateKey`]'s layout, -/// `p || q || dP || dQ || qInv`, unchanged. +/// An RSA key-establishment private key at the size `K`: [`RsaPrivateKey`] under the KEM roles +/// and the `# Key validation` checks, encoded as it is. #[derive(Clone, Debug, PartialEq, Eq)] -pub struct RsaKEMPrivateKey(pub(crate) RsaPrivateKey); +pub struct RsaKEMPrivateKey(pub(crate) RsaPrivateKey); -impl RsaKEMPrivateKey { +impl RsaKEMPrivateKey { /// Builds a private key from its CRT components. Returns /// `Err(`[`KEMError::DecodingError`]`)` in the cases [`RsaPrivateKey::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: &[u64; HALF], - q: &[u64; HALF], - d_p: &[u64; HALF], - d_q: &[u64; HALF], - q_inv: &[u64; HALF], + p: &K::HalfLimbs, + q: &K::HalfLimbs, + d_p: &K::HalfLimbs, + d_q: &K::HalfLimbs, + q_inv: &K::HalfLimbs, ) -> Result { Self::from_rsa_key( RsaPrivateKey::from_crt_components(p, q, d_p, d_q, q_inv).map_err(kem_error)?, ) } - /// As [`RsaKEMPublicKey::from_rsa_key`], for the private half. - pub(crate) fn from_rsa_key(sk: RsaPrivateKey) -> Result { - if !has_full_bit_length(sk.n()) { + pub(crate) fn from_rsa_key(sk: RsaPrivateKey) -> 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`. - pub fn n(&self) -> &[u64; L] { + /// 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 one modulus size: the [`KEMAlgorithm`] marker the key -/// roles name, carrying the metadata and no state. Each size module names its own instantiation -/// (e.g. `crate::rsa_2048::RSASVE`), along with that size's `keygen(rng)` as an inherent -/// associated function. -/// -/// `L`/`L2`/`L21`/`HALF`/`HALF2`/`HALF21` are the widths the rest of this crate threads through -/// `rsa_core` (see [`crate::modexp`]). `N_BYTES = 8 * L` is `nLen`, which is both the ciphertext -/// length and the shared-secret length. `SECURITY_BITS` is the modulus's SP 800-57 Part 1 -/// security strength, the same value that size's `keygen` demands of its RNG. Encapsulation -/// demands it too, and the shared secret is labelled with it. +/// 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< - const L: usize, - const L2: usize, - const L21: usize, - const HALF: usize, - const HALF2: usize, - const HALF21: usize, - const N_BYTES: usize, - const SECURITY_BITS: usize, -> { - _widths: PhantomData<[u64; L]>, +pub struct RSASVE { + _size: PhantomData, } -/// The algorithm name at one modulus size, from the limb count. -const fn alg_name(l: usize) -> &'static str { - match l { - 32 => "RSASVE-2048", - 48 => "RSASVE-3072", - 64 => "RSASVE-4096", - 128 => "RSASVE-8192", - _ => "RSASVE", - } +impl RSASVE { + const NAME: ConstStr<16> = ConstStr::concat(&["RSASVE-", K::BITS_NAME]); } -impl< - const L: usize, - const L2: usize, - const L21: usize, - const HALF: usize, - const HALF2: usize, - const HALF21: usize, - const N_BYTES: usize, - const SECURITY_BITS: usize, -> Algorithm for RSASVE -{ - const ALG_NAME: &'static str = alg_name(L); - const MAX_SECURITY_STRENGTH: SecurityStrength = SecurityStrength::from_bits(SECURITY_BITS); +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< - const L: usize, - const L2: usize, - const L21: usize, - const HALF: usize, - const HALF2: usize, - const HALF21: usize, - const N_BYTES: usize, - const SECURITY_BITS: usize, -> KEMAlgorithm for RSASVE -{ +impl Algorithm for RSASVE { + const ALG_NAME: &'static str = Self::NAME.as_str(); + const MAX_SECURITY_STRENGTH: SecurityStrength = K::STRENGTH; } -/// The encapsulator an [`RsaKEMPublicKey`] hands out through `EncapsulatingKey<()>`: it borrows -/// the key and draws `Z` from the RNG of each call. The widths are the size module's. -pub struct RsasveEncapsulator< - 'k, - const L: usize, - const L2: usize, - const L21: usize, - const N_BYTES: usize, - const SECURITY_BITS: usize, -> { - pk: &'k RsaKEMPublicKey, -} +impl KEMAlgorithm for RSASVE {} -impl< - 'k, - const L: usize, - const L2: usize, - const L21: usize, - const N_BYTES: usize, - const SECURITY_BITS: usize, -> RsasveEncapsulator<'k, L, L2, L21, N_BYTES, SECURITY_BITS> -{ - /// Borrows `pk`; the size modules' role impls call this. - pub(crate) fn new(pk: &'k RsaKEMPublicKey) -> Self { - Self { pk } - } +/// The worker [`EncapsulatingKey::create_encapsulator`] hands out: the public key, borrowed. +pub struct RsasveEncapsulator<'k, K: RsaSize> { + pk: &'k RsaKEMPublicKey, } -impl< - const L: usize, - const L2: usize, - const L21: usize, - const N_BYTES: usize, - const SECURITY_BITS: usize, -> Algorithm for RsasveEncapsulator<'_, L, L2, L21, N_BYTES, SECURITY_BITS> -{ - const ALG_NAME: &'static str = alg_name(L); - const MAX_SECURITY_STRENGTH: SecurityStrength = SecurityStrength::from_bits(SECURITY_BITS); +impl Algorithm for RsasveEncapsulator<'_, K> { + const ALG_NAME: &'static str = RSASVE::::ALG_NAME; + const MAX_SECURITY_STRENGTH: SecurityStrength = RSASVE::::MAX_SECURITY_STRENGTH; } -impl< - const L: usize, - const L2: usize, - const L21: usize, - const N_BYTES: usize, - const SECURITY_BITS: usize, -> KEMEncapsulator for RsasveEncapsulator<'_, L, L2, L21, N_BYTES, SECURITY_BITS> +impl KEMEncapsulator for RsasveEncapsulator<'_, K> +where + K: RsaSize, { - /// RSASVE.GENERATE((n, e)) (SP 800-56B Rev. 2 §7.2.1.2), drawing `Z` from `rng`: the - /// ciphertext `C` into `ct` and the secret value `Z` into `ss`, as a [`KeyMaterial`] of type - /// [`KeyType::CryptographicRandom`] at the modulus's security strength. - /// - /// Errors: `RNGError(SecurityStrengthInsufficientForAlgorithm)` if `rng` is weaker than the - /// modulus (§5.3: an RBG generating `Z` "shall be instantiated to support a security strength - /// that is equal to or greater than the security strength associated with the RSA modulus - /// length"), - /// `RNGError` if `rng` fails, and `GenericError` if [`MAX_GENERATE_ATTEMPTS`] draws all fall - /// outside `(1, n - 1)`, which a working RNG does not do (see that constant). Both buffers - /// are left zeroized on every error. - // `Z`, `C`: SP 800-56B's own names (see QUALITY_AND_STYLE.md's naming exception). + /// 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_BYTES], - ss: &mut KeyMaterial, + ct: &mut [u8; N], + ss: &mut KeyMaterial, ) -> Result { - debug_assert_eq!(N_BYTES, 8 * L, "RSASVE needs N_BYTES == 8 * L"); ct.fill(0); ss.zeroize(); - if rng.security_strength() < SecurityStrength::from_bits(SECURITY_BITS) { + if rng.security_strength() < K::STRENGTH { return Err(KEMError::RNGError(RNGError::SecurityStrengthInsufficientForAlgorithm)); } - - // Step 1: "nLen = len(n)/8, the byte length of the modulus n" -- N_BYTES, since - // `RsaKEMPublicKey` guarantees `n` is exactly `8 * N_BYTES` bits. - - // `Z` and `z` are held in `Secret` so that they are scrubbed on every exit, including - // the error ones: §7.2.1.2's closing paragraph requires this routine to "destroy any - // locally stored portions of Z and z". - let mut Z = Secret::<[u8; N_BYTES]>::new(); - let mut z = Secret::<[u64; L]>::new(); + let mut Z = Secret::<[u8; N]>::new(); + let mut z = Secret::::new(); let mut attempts = 0; loop { if attempts == MAX_GENERATE_ATTEMPTS { @@ -354,43 +240,33 @@ impl< )); } attempts += 1; - // Step 2.a: "Using the RBG ..., generate Z, a byte string of nLen bytes." rng.next_bytes_out(&mut *Z)?; - // Step 2.b: "z = BS2I(Z, nLen)." - *z = limbs_from_be_bytes::(&Z); - // Step 2.c: "If z does not satisfy 1 < z < (n – 1), then go to step 2a." - if in_open_range(&z, self.pk.n()) { + *z = K::limbs_from_be_bytes(&Z); + if in_open_range::(&z, self.pk.n()) { break; } } - - // Step 3.a: "c = RSAEP((n, e), z)". RSAEP's own step 1 range check (§7.1.1, "1 < m < - // (n – 1)") is the one step 2.c has just ensured, so it is not repeated: `public_exp` is - // RSAEP's step 2, `c = z^e mod n`. - let c = public_exp::(&self.pk.0, &z); - // Step 3.b: "C = I2BS(c, nLen)." - *ct = be_bytes_from_limbs::(&c); - - // Step 4: "Output the string Z as the secret value, and the ciphertext C." - if let Err(e) = secret_value_into::(&Z, ss) { + 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_BYTES) + Ok(N) } } -/// `Z` into `ss` as [`KeyType::CryptographicRandom`] at the modulus's strength, zeroizing `ss` -/// first and again if the label cannot be set. +/// `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_BYTES], - ss: &mut KeyMaterial, +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(SecurityStrength::from_bits(SECURITY_BITS)) + ss.set_security_strength(K::STRENGTH) }); if let Err(e) = result { ss.zeroize(); @@ -399,147 +275,114 @@ fn secret_value_into( Ok(()) } -/// The decapsulator an [`RsaKEMPrivateKey`] hands out through `DecapsulatingKey<()>`: it borrows -/// the key. The widths are the size module's. -pub struct RsasveDecapsulator< - 'k, - const L: usize, - const L2: usize, - const L21: usize, - const HALF: usize, - const HALF2: usize, - const HALF21: usize, - const N_BYTES: usize, - const SECURITY_BITS: usize, -> { - sk: &'k RsaKEMPrivateKey, -} - -impl< - 'k, - const L: usize, - const L2: usize, - const L21: usize, - const HALF: usize, - const HALF2: usize, - const HALF21: usize, - const N_BYTES: usize, - const SECURITY_BITS: usize, -> RsasveDecapsulator<'k, L, L2, L21, HALF, HALF2, HALF21, N_BYTES, SECURITY_BITS> -{ - /// Borrows `sk`; the size modules' role impls call this. - pub(crate) fn new(sk: &'k RsaKEMPrivateKey) -> Self { - Self { sk } - } +/// The worker [`DecapsulatingKey::create_decapsulator`] hands out: the private key, borrowed. +pub struct RsasveDecapsulator<'k, K: RsaSize> { + sk: &'k RsaKEMPrivateKey, } -impl< - const L: usize, - const L2: usize, - const L21: usize, - const HALF: usize, - const HALF2: usize, - const HALF21: usize, - const N_BYTES: usize, - const SECURITY_BITS: usize, -> Algorithm for RsasveDecapsulator<'_, L, L2, L21, HALF, HALF2, HALF21, N_BYTES, SECURITY_BITS> -{ - const ALG_NAME: &'static str = alg_name(L); - const MAX_SECURITY_STRENGTH: SecurityStrength = SecurityStrength::from_bits(SECURITY_BITS); +impl Algorithm for RsasveDecapsulator<'_, K> { + const ALG_NAME: &'static str = RSASVE::::ALG_NAME; + const MAX_SECURITY_STRENGTH: SecurityStrength = RSASVE::::MAX_SECURITY_STRENGTH; } -impl< - const L: usize, - const L2: usize, - const L21: usize, - const HALF: usize, - const HALF2: usize, - const HALF21: usize, - const N_BYTES: usize, - const SECURITY_BITS: usize, -> KEMDecapsulator - for RsasveDecapsulator<'_, L, L2, L21, HALF, HALF2, HALF21, N_BYTES, SECURITY_BITS> +impl KEMDecapsulator for RsasveDecapsulator<'_, K> +where + K: RsaSigningSize + RsaSize, { - /// RSASVE.RECOVER((n, d), C) (SP 800-56B Rev. 2 §7.2.1.3), with the private key in CRT form - /// (§7.1.2.3's RSADP): `Z` into `ss` as a [`KeyMaterial`] of type - /// [`KeyType::CryptographicRandom`] at the modulus's security strength, matching what the - /// encapsulator gave the other party. - /// - /// Errors: `DecapsulationFailed` if RSADP finds the ciphertext out of range (step 3.c), - /// which §7.2.1.3 calls "an indication of a decryption error"; step 2's length check is the - /// type's. A ciphertext that is in range but was never produced by an encapsulation is *not* - /// detected. RSASVE has no redundancy to check, so such a ciphertext just recovers a - /// different `Z` (see the crate docs' `# Security Considerations`). `ss` is left zeroized - /// on every error. + /// 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_BYTES], - ss: &mut KeyMaterial, - ) -> Result { - debug_assert_eq!(N_BYTES, 8 * L, "RSASVE needs N_BYTES == 8 * L"); + fn decaps_out(&self, ct: &[u8; N], ss: &mut KeyMaterial) -> Result { ss.zeroize(); - // Step 1: "nLen = len(n)/8" -- N_BYTES, as in `encaps_out`. - // Step 2: "If the length of the ciphertext C is not nLen bytes in length, output an - // indication of a decryption error" -- the array type. - - // Step 3.a: "c = BS2I(C)." - let c = limbs_from_be_bytes::(ct); - - // Step 3.b/3.c: "z = RSADP((n, d), c)", and "If RSADP indicates that the ciphertext is - // out of range, output an indication of a decryption error". This is RSADP's step 1 - // (§7.1.2.3, "If the ciphertext c does not satisfy 1 < c < (n – 1) ..."), checked here - // rather than inside a separate RSADP function, and `crt_exp` is its steps 2-5 (`mp = - // c^dP mod p`, `mq = c^dQ mod q`, `h = ((mp − mq) × qInv) mod p`, `m = mq + q × h`). - // `c` is the public ciphertext, so the range check need not be constant-time, although - // it is. - if !in_open_range(&c, self.sk.n()) { + let c = K::limbs_from_be_bytes(ct); + if !in_open_range::(&c, self.sk.n()) { return Err(KEMError::DecapsulationFailed); } - let mut z = Secret::<[u64; L]>::new(); - *z = crt_exp::(&self.sk.0, &c); + 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) + } +} - // Step 3.d: "Z = I2BS(z, nLen)." - let mut Z = Secret::<[u8; N_BYTES]>::new(); - *Z = be_bytes_from_limbs::(&z); +impl EncapsulatingKey<(), N, N> for RsaKEMPublicKey +where + K: RsaSize, +{ + type Algorithm = RSASVE; + type Encapsulator<'k> = RsasveEncapsulator<'k, K>; - // Step 4: "Output the string Z as the secret value (i.e., the shared secret)". - secret_value_into::(&Z, ss)?; - Ok(N_BYTES) + /// Cannot fail: RSASVE takes no parameters beyond the key. + fn create_encapsulator<'k>(&'k self, _params: ()) -> Result, KEMError> { + Ok(RsasveEncapsulator { pk: self }) } } -/// Wraps a size module's signature-typed `keygen` result as a KEM key pair, applying -/// the KEM key types' checks. These always pass for this crate's own keys, which have `e = 65537` -/// and an `n` of exactly `nlen` bits by construction (see [`crate::keygen`]). -pub(crate) fn keygen_from( - pair: Result<(RsaPublicKey, RsaPrivateKey), SignatureError>, -) -> Result<(RsaKEMPublicKey, RsaKEMPrivateKey), KEMError> { - let (pk, sk) = pair.map_err(kem_error)?; - Ok((RsaKEMPublicKey::from_rsa_key(pk)?, RsaKEMPrivateKey::from_rsa_key(sk)?)) +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 }) + } } -/// Decodes [`RsaPrivateKey`]'s raw layout into an [`RsaKEMPrivateKey`], for the per-size -/// `KEMPrivateKey::from_bytes` impls, which reject a wrong-length slice before calling this. -pub(crate) fn private_key_from_bytes< - const L: usize, - const HALF: usize, - const HALF_BYTES: usize, - const SK_LEN: usize, ->( - bytes: &[u8; SK_LEN], -) -> Result, KEMError> { - RsaKEMPrivateKey::from_rsa_key( - RsaPrivateKey::from_bytes_raw::(bytes).map_err(kem_error)?, - ) +impl KEMPrivateKey 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(|_| { + KEMError::DecodingError( + "an RSA private key is five components of half the modulus length", + ) + })?; + Self::from_rsa_key(RsaPrivateKey::from_bytes_raw(bytes).map_err(kem_error)?) + } } -/// Decodes [`RsaPublicKey`]'s raw layout into an [`RsaKEMPublicKey`], for the per-size -/// `KEMPublicKey::from_bytes` impls, which reject a wrong-length slice before calling this. -pub(crate) fn public_key_from_bytes( - bytes: &[u8; PK_LEN], -) -> Result, KEMError> { - RsaKEMPublicKey::from_rsa_key( - RsaPublicKey::from_bytes_raw::(bytes).map_err(kem_error)?, - ) +impl KEMPublicKey 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(|_| { + KEMError::DecodingError("an RSA public key is the modulus length plus four bytes") + })?; + Self::from_rsa_key(RsaPublicKey::from_bytes_raw(bytes).map_err(kem_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<(RsaPublicKey, RsaPrivateKey), 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..5f13d13c --- /dev/null +++ b/crypto/rsa/src/size.rs @@ -0,0 +1,601 @@ +//! 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::{RsaPrivateKey, RsaPublicKey, modulus_strength}; +use crate::rsa_core; +use crate::rsasve::{RsaKEMPrivateKey, RsaKEMPublicKey}; +use bouncycastle_core::errors::{KEMError, SignatureError}; +use bouncycastle_core::security_strength::SecurityStrength; +use bouncycastle_core::traits::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<(RsaPublicKey, RsaPrivateKey), 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: &RsaPrivateKey, m: &Self::Limbs) -> Self::Limbs; +} + +/// Implemented on a signing size marker: the signature key pair, so a caller starts from the +/// size (`RSA2048::generate_signature_key_pair(&mut rng)`). 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 { + /// The size's public key. + type PublicKey; + /// The size's private key. + type PrivateKey; + + /// FIPS 186-5 Appendix A.1.3 key pair generation from `rng`. + /// + /// # Errors + /// As [`RsaSigningSize::keygen`]. + fn generate_signature_key_pair( + rng: &mut dyn RNG, + ) -> Result<(Self::PublicKey, Self::PrivateKey), SignatureError>; +} + +impl SignatureKeyPair for K { + type PublicKey = RsaPublicKey; + type PrivateKey = RsaPrivateKey; + + fn generate_signature_key_pair( + rng: &mut dyn RNG, + ) -> Result<(RsaPublicKey, RsaPrivateKey), SignatureError> { + K::keygen(rng) + } +} + +/// 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<(RsaPublicKey, RsaPrivateKey), 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: &RsaPrivateKey, 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<(RsaPublicKey, RsaPrivateKey), 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: &RsaPrivateKey, 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<(RsaPublicKey, RsaPrivateKey), 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: &RsaPrivateKey, 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<(RsaPublicKey, RsaPrivateKey), 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: &RsaPrivateKey, 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/keys_tests.rs b/crypto/rsa/tests/keys_tests.rs index dbbd123e..d3b602d4 100644 --- a/crypto/rsa/tests/keys_tests.rs +++ b/crypto/rsa/tests/keys_tests.rs @@ -7,6 +7,9 @@ use bouncycastle_core::errors::SignatureError; use bouncycastle_core::traits::{SignaturePrivateKey, SignaturePublicKey}; use bouncycastle_rsa::keys::{RsaPrivateKey, RsaPublicKey}; +use bouncycastle_rsa::size::{RsaSigningSize, RsaSize}; +use bouncycastle_rsa::{RSA2048, RSA3072, RSA4096, RSA8192}; +use bouncycastle_utils::secret::ZeroizablePrimitive; const P: [u64; 16] = [ 0xfec673c1b07d4997, 0x98c9e3737faecc8b, 0x01369d6bebcfd19b, 0x8aadc1799d493a6e, @@ -51,24 +54,15 @@ const N: [u64; 32] = [ #[test] fn from_crt_components_accepts_a_genuine_key_and_derives_n() { - let sk = RsaPrivateKey::<32, 16>::from_crt_components(&P, &Q, &D_P, &D_Q, &Q_INV) + let sk = RsaPrivateKey::::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_mismatched_widths() { - // L = 31 != 2 * 16. - assert!(matches!( - RsaPrivateKey::<31, 16>::from_crt_components(&P, &Q, &D_P, &D_Q, &Q_INV), - Err(SignatureError::DecodingError(_)) - )); -} - #[test] fn from_crt_components_rejects_equal_primes() { assert!(matches!( - RsaPrivateKey::<32, 16>::from_crt_components(&P, &P, &D_P, &D_Q, &Q_INV), + RsaPrivateKey::::from_crt_components(&P, &P, &D_P, &D_Q, &Q_INV), Err(SignatureError::DecodingError(_)) )); } @@ -78,7 +72,7 @@ fn from_crt_components_rejects_even_prime() { let mut even_p = P; even_p[0] &= !1; assert!(matches!( - RsaPrivateKey::<32, 16>::from_crt_components(&even_p, &Q, &D_P, &D_Q, &Q_INV), + RsaPrivateKey::::from_crt_components(&even_p, &Q, &D_P, &D_Q, &Q_INV), Err(SignatureError::DecodingError(_)) )); } @@ -88,7 +82,7 @@ fn from_crt_components_rejects_even_q() { let mut even_q = Q; even_q[0] &= !1; assert!(matches!( - RsaPrivateKey::<32, 16>::from_crt_components(&P, &even_q, &D_P, &D_Q, &Q_INV), + RsaPrivateKey::::from_crt_components(&P, &even_q, &D_P, &D_Q, &Q_INV), Err(SignatureError::DecodingError(_)) )); } @@ -96,7 +90,7 @@ fn from_crt_components_rejects_even_q() { #[test] fn from_crt_components_rejects_dp_out_of_range() { assert!(matches!( - RsaPrivateKey::<32, 16>::from_crt_components(&P, &Q, &P, &D_Q, &Q_INV), + RsaPrivateKey::::from_crt_components(&P, &Q, &P, &D_Q, &Q_INV), Err(SignatureError::DecodingError(_)) )); } @@ -104,40 +98,46 @@ fn from_crt_components_rejects_dp_out_of_range() { #[test] fn from_crt_components_rejects_qinv_out_of_range() { assert!(matches!( - RsaPrivateKey::<32, 16>::from_crt_components(&P, &Q, &D_P, &D_Q, &P), + RsaPrivateKey::::from_crt_components(&P, &Q, &D_P, &D_Q, &P), Err(SignatureError::DecodingError(_)) )); } #[test] fn public_key_accepts_e_65537() { - let pk = RsaPublicKey::<32>::new(&N, 0x00010001).expect("e = 65537 is valid"); + let pk = RsaPublicKey::::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!(RsaPublicKey::<32>::new(&N, 65536), Err(SignatureError::DecodingError(_)))); + assert!(matches!( + RsaPublicKey::::new(&N, 65536), + Err(SignatureError::DecodingError(_)) + )); } #[test] fn public_key_rejects_exponent_below_three() { - assert!(matches!(RsaPublicKey::<32>::new(&N, 1), Err(SignatureError::DecodingError(_)))); + assert!(matches!(RsaPublicKey::::new(&N, 1), Err(SignatureError::DecodingError(_)))); } #[test] fn public_key_rejects_even_modulus() { let mut even_n = N; even_n[0] &= !1; - assert!(matches!(RsaPublicKey::<32>::new(&even_n, 3), Err(SignatureError::DecodingError(_)))); + assert!(matches!( + RsaPublicKey::::new(&even_n, 3), + Err(SignatureError::DecodingError(_)) + )); } #[test] fn public_key_encode_round_trips() { - let pk = RsaPublicKey::<32>::new(&N, 0x10001).unwrap(); + let pk = RsaPublicKey::::new(&N, 0x10001).unwrap(); let bytes: [u8; 260] = pk.encode(); - let decoded = RsaPublicKey::<32>::from_bytes(&bytes).expect("must decode"); + let decoded = RsaPublicKey::::from_bytes(&bytes).expect("must decode"); assert_eq!(decoded, pk); } @@ -145,7 +145,7 @@ fn public_key_encode_round_trips() { /// 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 = RsaPublicKey::<32>::new(&N, 0x10001).unwrap(); + let pk = RsaPublicKey::::new(&N, 0x10001).unwrap(); let bytes = pk.encode(); assert_eq!(bytes[..8], N[31].to_be_bytes()); assert_eq!(bytes[248..256], N[0].to_be_bytes()); @@ -158,27 +158,27 @@ fn public_key_encode_layout_is_n_then_e_big_endian() { #[test] fn public_key_from_bytes_rejects_even_modulus() { - let pk = RsaPublicKey::<32>::new(&N, 0x10001).unwrap(); + let pk = RsaPublicKey::::new(&N, 0x10001).unwrap(); let mut bytes: [u8; 260] = pk.encode(); bytes[255] &= !1; // clear n's low bit (last byte, big-endian) assert!(matches!( - RsaPublicKey::<32>::from_bytes(&bytes), + RsaPublicKey::::from_bytes(&bytes), Err(SignatureError::DecodingError(_)) )); } #[test] fn public_key_from_bytes_rejects_wrong_lengths() { - let pk = RsaPublicKey::<32>::new(&N, 0x10001).unwrap(); + let pk = RsaPublicKey::::new(&N, 0x10001).unwrap(); let bytes = pk.encode(); assert!(matches!( - RsaPublicKey::<32>::from_bytes(&bytes[..259]), + RsaPublicKey::::from_bytes(&bytes[..259]), Err(SignatureError::DecodingError(_)) )); let mut too_long = bytes.to_vec(); too_long.push(0); assert!(matches!( - RsaPublicKey::<32>::from_bytes(&too_long), + RsaPublicKey::::from_bytes(&too_long), Err(SignatureError::DecodingError(_)) )); } @@ -187,24 +187,24 @@ fn public_key_from_bytes_rejects_wrong_lengths() { /// 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 = RsaPublicKey::<32>::new(&N, 0x10001).unwrap(); + let pk = RsaPublicKey::::new(&N, 0x10001).unwrap(); let shown = format!("{pk}"); let n_hex: String = pk.encode()[..256].iter().map(|b| format!("{b:02x}")).collect(); - assert_eq!(shown, format!("RsaPublicKey<32> {{ n: {n_hex}, e: 10001 }}")); + assert_eq!(shown, format!("RsaPublicKey {{ n: {n_hex}, e: 10001 }}")); } #[test] fn private_key_encode_round_trips() { - let sk = RsaPrivateKey::<32, 16>::from_crt_components(&P, &Q, &D_P, &D_Q, &Q_INV).unwrap(); + let sk = RsaPrivateKey::::from_crt_components(&P, &Q, &D_P, &D_Q, &Q_INV).unwrap(); let bytes: [u8; 640] = sk.encode(); - let decoded = RsaPrivateKey::<32, 16>::from_bytes(&bytes).expect("must decode"); + let decoded = RsaPrivateKey::::from_bytes(&bytes).expect("must decode"); assert_eq!(decoded, sk); } /// `SignaturePrivateKey`'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 = RsaPrivateKey::<32, 16>::from_crt_components(&P, &Q, &D_P, &D_Q, &Q_INV).unwrap(); + let sk = RsaPrivateKey::::from_crt_components(&P, &Q, &D_P, &D_Q, &Q_INV).unwrap(); let bytes = sk.encode(); for (i, field) in [P, Q, D_P, D_Q, Q_INV].iter().enumerate() { let start = 128 * i; @@ -219,29 +219,62 @@ fn private_key_encode_layout_is_five_big_endian_fields() { #[test] fn private_key_from_bytes_rejects_equal_primes() { - let sk = RsaPrivateKey::<32, 16>::from_crt_components(&P, &Q, &D_P, &D_Q, &Q_INV).unwrap(); + let sk = RsaPrivateKey::::from_crt_components(&P, &Q, &D_P, &D_Q, &Q_INV).unwrap(); 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::<32, 16>::from_bytes(&bytes), + RsaPrivateKey::::from_bytes(&bytes), Err(SignatureError::DecodingError(_)) )); } #[test] fn private_key_from_bytes_rejects_wrong_lengths() { - let sk = RsaPrivateKey::<32, 16>::from_crt_components(&P, &Q, &D_P, &D_Q, &Q_INV).unwrap(); + let sk = RsaPrivateKey::::from_crt_components(&P, &Q, &D_P, &D_Q, &Q_INV).unwrap(); let bytes = sk.encode(); assert!(matches!( - RsaPrivateKey::<32, 16>::from_bytes(&bytes[..639]), + RsaPrivateKey::::from_bytes(&bytes[..639]), Err(SignatureError::DecodingError(_)) )); let mut too_long = bytes.to_vec(); too_long.push(0); assert!(matches!( - RsaPrivateKey::<32, 16>::from_bytes(&too_long), + RsaPrivateKey::::from_bytes(&too_long), + Err(SignatureError::DecodingError(_)) + )); +} + +/// 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!(RsaPrivateKey::::from_crt_components(&p, &q, &small, &small, &small).is_ok()); + assert!(matches!( + RsaPrivateKey::::from_crt_components(&p, &q, &p, &small, &small), + Err(SignatureError::DecodingError(_)) + )); + assert!(matches!( + RsaPrivateKey::::from_crt_components(&p, &q, &small, &q, &small), Err(SignatureError::DecodingError(_)) )); + assert!(matches!( + RsaPrivateKey::::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::(); } diff --git a/crypto/rsa/tests/rsa_1024_tests.rs b/crypto/rsa/tests/rsa_1024_tests.rs index e6737d2e..cc9f5a2d 100644 --- a/crypto/rsa/tests/rsa_1024_tests.rs +++ b/crypto/rsa/tests/rsa_1024_tests.rs @@ -174,3 +174,15 @@ fn public_key_trait_encoding_round_trips_and_rejects_wrong_lengths() { Err(SignatureError::DecodingError(_)) )); } + +/// 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!( + VerifyingKey::::verify(pk, 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 index d17c08a3..17c53d48 100644 --- a/crypto/rsa/tests/rsa_1536_tests.rs +++ b/crypto/rsa/tests/rsa_1536_tests.rs @@ -178,3 +178,15 @@ fn public_key_trait_encoding_round_trips_and_rejects_wrong_lengths() { Err(SignatureError::DecodingError(_)) )); } + +/// 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!( + VerifyingKey::::verify(pk, msg, None, &[0xffu8; 192]), + Err(SignatureError::SignatureVerificationFailed) + ) + }); +} diff --git a/crypto/rsa/tests/rsa_2048_pkcs1_v1_5_tests.rs b/crypto/rsa/tests/rsa_2048_pkcs1_v1_5_tests.rs index 2f53e653..2d11b026 100644 --- a/crypto/rsa/tests/rsa_2048_pkcs1_v1_5_tests.rs +++ b/crypto/rsa/tests/rsa_2048_pkcs1_v1_5_tests.rs @@ -38,6 +38,7 @@ use bouncycastle_core_test_framework::signature::{ TestFrameworkSignature, TestFrameworkSignatureKeys, }; use bouncycastle_hex::decode as hex_decode; +use bouncycastle_rsa::RSA2048; use bouncycastle_rsa::rsa_2048::{ PK_LEN, RSA2048PrivateKey, RSA2048PublicKey, RSASSA_PKCS1_v1_5_SHA256, SIG_LEN, SK_LEN, }; @@ -299,9 +300,7 @@ fn trait_verify_reports_out_of_range_representative_as_invalid_signature() { let mut digest = [0u8; 32]; SHA256::hash_out(b"msg", &mut digest); assert!(matches!( - rsassa_pkcs1_v1_5::verify_from_hash::( - &pk, &digest, &too_big - ), + rsassa_pkcs1_v1_5::verify_from_hash::(&pk, &digest, &too_big), Err(SignatureError::DecodingError(_)) )); assert!(matches!( diff --git a/crypto/rsa/tests/rsa_2048_pss_shake128_tests.rs b/crypto/rsa/tests/rsa_2048_pss_shake128_tests.rs index 4fd50320..2a28f536 100644 --- a/crypto/rsa/tests/rsa_2048_pss_shake128_tests.rs +++ b/crypto/rsa/tests/rsa_2048_pss_shake128_tests.rs @@ -12,6 +12,7 @@ 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::rsa_2048::{ RSA2048PrivateKey, RSA2048PublicKey, RSASSA_PSS_SHAKE128, SIG_LEN, }; @@ -266,21 +267,9 @@ fn set_salt_fixes_the_salt_on_the_streaming_path() { let sig = signer.do_final().unwrap(); let mut digest = [0u8; 32]; SHAKE128::hash_out(msg, &mut digest); - let expected = rsassa_pss_shake::sign_from_hash_with_salt::< - SHAKE128, - 32, - 32, - 72, - 223, - 32, - 64, - 65, - 16, - 32, - 33, - 256, - >(&sk, &digest, &salt) - .unwrap(); + let expected = + rsassa_pss_shake::sign_from_hash_with_salt::(&sk, &digest, &salt) + .unwrap(); assert_eq!(sig, expected); VerifyingKey::::verify(&pk, msg, None, &sig).unwrap(); diff --git a/crypto/rsa/tests/rsa_2048_pss_tests.rs b/crypto/rsa/tests/rsa_2048_pss_tests.rs index fc314fef..09b4da92 100644 --- a/crypto/rsa/tests/rsa_2048_pss_tests.rs +++ b/crypto/rsa/tests/rsa_2048_pss_tests.rs @@ -17,6 +17,7 @@ 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::rsa_2048::{RSA2048PrivateKey, RSA2048PublicKey, RSASSA_PSS_SHA256, SIG_LEN}; use bouncycastle_rsa::rsassa_pss; use bouncycastle_sha2::SHA256; @@ -266,22 +267,8 @@ fn set_salt_fixes_the_salt_on_the_streaming_path() { let sig = signer.do_final().unwrap(); let mut digest = [0u8; 32]; SHA256::hash_out(msg, &mut digest); - let expected = rsassa_pss::sign_from_hash_with_salt::< - SHA256, - 32, - 36, - 32, - 72, - 223, - 32, - 64, - 65, - 16, - 32, - 33, - 256, - >(&sk, &digest, &salt) - .unwrap(); + let expected = + rsassa_pss::sign_from_hash_with_salt::(&sk, &digest, &salt).unwrap(); assert_eq!(sig, expected); VerifyingKey::::verify(&pk, msg, None, &sig).unwrap(); diff --git a/crypto/rsa/tests/rsassa_worker_tests.rs b/crypto/rsa/tests/rsassa_worker_tests.rs new file mode 100644 index 00000000..6cc67293 --- /dev/null +++ b/crypto/rsa/tests/rsassa_worker_tests.rs @@ -0,0 +1,108 @@ +//! 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::{RsaPrivateKey, RsaPublicKey}; +use bouncycastle_rsa::rsassa_pkcs1_v1_5::RSASSA_PKCS1_v1_5; +use bouncycastle_rsa::rsassa_pss::RSASSA_PSS; +use bouncycastle_rsa::rsassa_pss_shake::RSASSA_PSS_SHAKE; +use bouncycastle_rsa::{rsassa_pss, rsassa_pss_shake}; +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() -> (RsaPublicKey, RsaPrivateKey) { + let sk = RsaPrivateKey::::from_crt_components(&P, &Q, &D_P, &D_Q, &Q_INV).unwrap(); + let pk = RsaPublicKey::::new(sk.n(), 0x10001).unwrap(); + (pk, sk) +} + +#[test] +fn workers_name_their_algorithm() { + let (pk, sk) = key_pair(); + let mut rng = DefaultRNG::default(); + + let signer = DeterministicSigningKey::, 256>::create_signer_deterministic(&sk, None).unwrap(); + assert_eq!(signer.alg_name(), "RSASSA-PKCS1-v1_5-SHA256"); + let verifier = + VerifyingKey::, 256>::create_verifier(&pk, None) + .unwrap(); + assert_eq!(verifier.alg_name(), "RSASSA-PKCS1-v1_5-SHA256"); + + let signer = + SigningKey::, 256>::create_signer(&sk, &mut rng, None).unwrap(); + assert_eq!(signer.alg_name(), "RSASSA-PSS-SHA256"); + let verifier = + VerifyingKey::, 256>::create_verifier(&pk, None).unwrap(); + assert_eq!(verifier.alg_name(), "RSASSA-PSS-SHA256"); + + let signer = + SigningKey::, 256>::create_signer(&sk, &mut rng, None) + .unwrap(); + assert_eq!(signer.alg_name(), "RSASSA-PSS-SHAKE128"); + let verifier = + VerifyingKey::, 256>::create_verifier(&pk, 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_pss::sign_from_hash::(&sk, &digest, &mut rng).unwrap(); + let b = rsassa_pss::sign_from_hash::(&sk, &digest, &mut rng).unwrap(); + assert_ne!(a, b); + rsassa_pss::verify_from_hash::(&pk, &digest, &a).unwrap(); + rsassa_pss::verify_from_hash::(&pk, &digest, &b).unwrap(); + assert!(rsassa_pss::verify_from_hash::(&pk, &[0u8; 32], &a).is_err()); + + let mut digest = [0u8; 32]; + SHAKE128::hash_out(b"the message", &mut digest); + let a = + rsassa_pss_shake::sign_from_hash::(&sk, &digest, &mut rng).unwrap(); + let b = + rsassa_pss_shake::sign_from_hash::(&sk, &digest, &mut rng).unwrap(); + assert_ne!(a, b); + rsassa_pss_shake::verify_from_hash::(&pk, &digest, &a).unwrap(); + rsassa_pss_shake::verify_from_hash::(&pk, &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 index 3b3d5332..c8babc0d 100644 --- a/crypto/rsa/tests/rsasve_tests.rs +++ b/crypto/rsa/tests/rsasve_tests.rs @@ -87,13 +87,13 @@ fn rng_emitting( } macro_rules! rsasve_suite { - ($module:ident, $size:ident, $bits:literal, $L:literal, $HALF:literal, $strength:expr, $weaker:expr) => { + ($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<$L>; - type SK = bouncycastle_rsa::rsasve::RsaKEMPrivateKey<$L, $HALF>; + 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)) @@ -101,18 +101,18 @@ macro_rules! rsasve_suite { fn sk_from(v: &Value, p: &str, q: &str, dp: &str, dq: &str, qinv: &str) -> SK { SK::from_crt_components( - &limbs::<$HALF>(v[p].as_str().unwrap()), - &limbs::<$HALF>(v[q].as_str().unwrap()), - &limbs::<$HALF>(v[dp].as_str().unwrap()), - &limbs::<$HALF>(v[dq].as_str().unwrap()), - &limbs::<$HALF>(v[qinv].as_str().unwrap()), + &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::<$L>(v["n"].as_str().unwrap()), 65537)?; + let pk = PK::new(&limbs(v["n"].as_str().unwrap()), 65537)?; let sk = sk_from(&v, "p", "q", "dP", "dQ", "qInv"); Ok((pk, sk)) } @@ -156,7 +156,11 @@ macro_rules! rsasve_suite { assert_eq!(pk.n(), sk.n()); assert_eq!(pk.e(), 65537); // `Display` is the wrapped signature key type's, unchanged. - let inner = bouncycastle_rsa::keys::RsaPublicKey::<$L>::new(pk.n(), 65537).unwrap(); + let inner = bouncycastle_rsa::keys::RsaPublicKey::::new( + pk.n(), + 65537, + ) + .unwrap(); assert_eq!(format!("{pk}"), format!("{inner}")); } @@ -287,7 +291,7 @@ macro_rules! rsasve_suite { #[test] fn public_key_validation() { let v = openssl_vectors(); - let n = limbs::<$L>(v["n"].as_str().unwrap()); + 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()); @@ -301,7 +305,8 @@ macro_rules! rsasve_suite { 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; - short_n[$L - 1] &= !(1 << 63); + 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(); @@ -319,21 +324,21 @@ macro_rules! rsasve_suite { // RsaPrivateKey's own checks come through as DecodingError: p == q. assert!(matches!( SK::from_crt_components( - &limbs::<$HALF>(v["p"].as_str().unwrap()), - &limbs::<$HALF>(v["p"].as_str().unwrap()), - &limbs::<$HALF>(v["dP"].as_str().unwrap()), - &limbs::<$HALF>(v["dP"].as_str().unwrap()), - &limbs::<$HALF>(v["qInv"].as_str().unwrap()), + &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; $HALF]; + let mut p = [0u64; $bits / 128]; p[0] = 3; - let mut q = [0u64; $HALF]; + let mut q = [0u64; $bits / 128]; q[0] = 5; - let mut small = [0u64; $HALF]; + let mut small = [0u64; $bits / 128]; small[0] = 1; assert!(matches!( SK::from_crt_components(&p, &q, &small, &small, &small), @@ -341,7 +346,7 @@ macro_rules! rsasve_suite { )); let (_, sk) = openssl_keypair().unwrap(); let mut bytes = sk.encode(); - bytes[..8 * $HALF].fill(0); // p = 0, which is even + bytes[..$bits / 16].fill(0); // p = 0, which is even assert!(matches!(SK::from_bytes(&bytes), Err(KEMError::DecodingError(_)))); } } @@ -351,36 +356,32 @@ macro_rules! rsasve_suite { rsasve_suite!( rsa_2048_rsasve, rsa_2048, + RSA2048, 2048, - 32, - 16, SecurityStrength::_112bit, SecurityStrength::None ); rsasve_suite!( rsa_3072_rsasve, rsa_3072, + RSA3072, 3072, - 48, - 24, SecurityStrength::_128bit, SecurityStrength::_112bit ); rsasve_suite!( rsa_4096_rsasve, rsa_4096, + RSA4096, 4096, - 64, - 32, SecurityStrength::_128bit, SecurityStrength::_112bit ); rsasve_suite!( rsa_8192_rsasve, rsa_8192, + RSA8192, 8192, - 128, - 64, SecurityStrength::_192bit, SecurityStrength::_128bit ); @@ -491,11 +492,11 @@ fn acvp_kas_ifc_ssc_kas2_3072() { /// `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, $bits:literal, $L:literal, $HALF:literal) => { + ($name:ident, $size:ident, $marker:ident, $bits:literal) => { #[test] fn $name() { use bouncycastle_rsa::$size::CT_LEN; - type SK = bouncycastle_rsa::rsasve::RsaKEMPrivateKey<$L, $HALF>; + type SK = bouncycastle_rsa::rsasve::RsaKEMPrivateKey; let d = get_test_data("acvp/RSA-DecryptionPrimitive-Sp800-56Br2.json"); let group = d["testGroups"] .as_array() @@ -539,9 +540,9 @@ macro_rules! acvp_rsadp { }; } -acvp_rsadp!(acvp_rsadp_crt_2048, rsa_2048, 2048, 32, 16); -acvp_rsadp!(acvp_rsadp_crt_3072, rsa_3072, 3072, 48, 24); -acvp_rsadp!(acvp_rsadp_crt_4096, rsa_4096, 4096, 64, 32); +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. From 010cf1acb6171950b0df5b84f0a063779d199f4b Mon Sep 17 00:00:00 2001 From: David Hook Date: Fri, 13 Nov 2026 10:57:54 +1100 Subject: [PATCH 34/55] Merging fix/rsa-scheme-keys, which makes an RSA key a key for one scheme and hash: a key served every scheme, so sk.sign(..) was ambiguous and every call spelled SigningKey::, 256>::sign(&sk, ..), and nothing stopped one key pair signing under two schemes, which SP 800-57 Part 1 Rev. 5 asks a key pair not to do. The key types now carry their algorithm, as the ECDSA keys carry their curve and hash: what RsaPublicKey and RsaPrivateKey were is keys::RsaPublicComponents and RsaPrivateComponents, the material with its validation and raw encoding and no role, and RsaPublicKey and RsaPrivateKey wrap them for the algorithm A their type names, so that sk.sign(&mut rng, msg, None), sk.sign_deterministic(msg, None) and pk.verify(msg, None, &sig) resolve from the key, a PSS key has no sign_deterministic and a PKCS#1 v1.5 key no sign; the components turn into a key for a scheme through key::() / into_key::(), the one deliberate step by which the same material serves two schemes, and the bytes carry no scheme, so a key file is decoded under the key type it is for. The roles are written once, in the new rsassa module, over three traits the markers implement: RsaSignatureAlgorithm (the size, the hash and the scheme's EMSA verification), RsaDeterministicSignatureAlgorithm (PKCS#1 v1.5, an encoding of the hash alone) and RsaRandomizedSignatureAlgorithm (PSS, an encoding of the hash and a salt), split by what the signer draws because two blanket role impls distinguished only by a bound on A overlap under coherence; three workers, RsaSigner with set_salt, RsaDeterministicSigner and RsaVerifier, replace the nine per-scheme ones, the scheme modules keep only their markers, and the pre-hash entry points are rsassa::sign_from_hash, sign_from_hash_with_salt, sign_from_hash_deterministic and verify_from_hash over . The signing-size markers generate a pair for one algorithm, RSA2048::generate_pkcs1_v1_5_signature_key_pair::(&mut rng) and generate_pss_signature_key_pair::, the hash spelled and never defaulted as on the ECDSA markers, and the plain generate_signature_key_pair goes; RsaSigningSize::keygen returns the components. The size modules lose RSA2048PublicKey, RSA2048PrivateKey and keygen, a key having no meaning without a scheme, and keep the scheme aliases and lengths; the key-establishment keys wrap the components as before, with their own Display. The CLI's generic rsa_pss_cmd, rsa_pkcs1_cmd and do_verify are over the algorithm alone and each size's command passes the marker's generator for the pairing it dispatches, subcommands, flags and outputs unchanged; the stack harness names its keys with their scheme. Tests: every suite builds the components once and types a key per pairing, the encoding tests under one scheme since the bytes are the same under any, and the rsa CLI tests type the documented key with the scheme each case checks. Verified: the rsa suite (the 4096 and 8192 keygens still #[ignore]d), the doctests, the cli suite, the all-targets build, nightly rustfmt, clippy adding nothing on the changed lines, rustdoc with warnings denied on the crate apart from modexp.rs's pre-existing private-item links. Mutants on apollo, scoped to keys.rs, rsassa.rs, the three scheme files, size.rs and rsasve.rs against the signature and RSASVE suites at 2048 and the verify-only sizes: 505 (162 caught, 330 unviable, 2 timeouts, both rsasve's encaps_out attempt counter made to loop, and 11 missed: the typed keys' e accessor, Debug and PartialEq, which the next squash's keys test closes; rsasve's kem_error arms, covered by the keygen test the scoped run skips; and size.rs's check_lengths const assertion and is_less at the two verify-only sizes, as before). Assisted-by: Claude:claude-mythos-5-1 --- cli/src/rsa_cmd.rs | 605 +++++++++++------- cli/tests/rsa_cli_tests.rs | 50 +- crypto/rsa/benches/rsa_1024_benches.rs | 32 +- crypto/rsa/benches/rsa_1536_benches.rs | 43 +- crypto/rsa/benches/rsa_2048_benches.rs | 185 ++---- crypto/rsa/benches/rsa_3072_benches.rs | 185 ++---- crypto/rsa/benches/rsa_4096_benches.rs | 181 ++---- crypto/rsa/benches/rsa_8192_benches.rs | 160 ++--- crypto/rsa/src/keygen.rs | 12 +- crypto/rsa/src/keys.rs | 295 +++++++-- crypto/rsa/src/lib.rs | 107 ++-- crypto/rsa/src/rsa_1024.rs | 3 - crypto/rsa/src/rsa_1536.rs | 3 - crypto/rsa/src/rsa_2048.rs | 20 +- crypto/rsa/src/rsa_3072.rs | 20 +- crypto/rsa/src/rsa_4096.rs | 20 +- crypto/rsa/src/rsa_8192.rs | 20 +- crypto/rsa/src/rsa_core.rs | 24 +- crypto/rsa/src/rsassa.rs | 347 ++++++++++ crypto/rsa/src/rsassa_pkcs1_v1_5.rs | 200 +----- crypto/rsa/src/rsassa_pss.rs | 236 +------ crypto/rsa/src/rsassa_pss_shake.rs | 234 +------ crypto/rsa/src/rsasve.rs | 44 +- crypto/rsa/src/size.rs | 109 +++- crypto/rsa/tests/keygen_tests.rs | 99 +-- crypto/rsa/tests/keys_tests.rs | 89 ++- crypto/rsa/tests/rsa_1024_tests.rs | 35 +- crypto/rsa/tests/rsa_1536_tests.rs | 38 +- ...rsa_2048_pkcs1_v1_5_sha384_sha512_tests.rs | 69 +- crypto/rsa/tests/rsa_2048_pkcs1_v1_5_tests.rs | 78 ++- .../tests/rsa_2048_pss_sha384_sha512_tests.rs | 119 ++-- .../rsa/tests/rsa_2048_pss_shake128_tests.rs | 103 ++- crypto/rsa/tests/rsa_2048_pss_tests.rs | 95 +-- .../rsa/tests/rsa_3072_pss_shake128_tests.rs | 55 +- crypto/rsa/tests/rsa_3072_tests.rs | 162 +++-- .../rsa/tests/rsa_4096_pss_shake256_tests.rs | 62 +- crypto/rsa/tests/rsa_4096_tests.rs | 199 +++--- crypto/rsa/tests/rsa_8192_tests.rs | 198 +++--- crypto/rsa/tests/rsassa_worker_tests.rs | 109 +++- crypto/rsa/tests/rsasve_tests.rs | 12 +- mem_usage_benches/src/bench_rsa_mem_usage.rs | 138 ++-- 41 files changed, 2365 insertions(+), 2430 deletions(-) create mode 100644 crypto/rsa/src/rsassa.rs diff --git a/cli/src/rsa_cmd.rs b/cli/src/rsa_cmd.rs index f4dfb981..999fc4c8 100644 --- a/cli/src/rsa_cmd.rs +++ b/cli/src/rsa_cmd.rs @@ -9,15 +9,18 @@ //! 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) that the key role traits are -//! implemented over, 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. `ctx` (accepted by the traits for +//! 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, `bouncycastle_rsa::rsa_*::keygen`) writes the private key +//! `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 @@ -38,14 +41,21 @@ use crate::helpers::{ }; use bouncycastle::core::errors::SignatureError; use bouncycastle::core::key_material::KeyMaterialTrait; -use bouncycastle::core::signature_key::{ - DeterministicSigningKey, SignatureAlgorithm, SigningKey, VerifyingKey, -}; +use bouncycastle::core::signature_key::{DeterministicSigningKey, SigningKey, VerifyingKey}; use bouncycastle::core::traits::{ RNG, SignaturePrivateKey, SignaturePublicKey, SignatureSigner, SignatureVerifier, }; use bouncycastle::rng::HashDRBG_SHA512; -use bouncycastle::rsa::{rsa_1024, rsa_1536, rsa_2048, rsa_3072, rsa_4096, rsa_8192}; +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; @@ -150,17 +160,14 @@ fn parse_pk, const PK_LEN: usize>( /// impl. Shared by [`rsa_sign_verify_cmd`]'s `Verify` arm, 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< - A: SignatureAlgorithm, - PK: SignaturePublicKey + VerifyingKey, - const PK_LEN: usize, - const SIG_LEN: usize, ->( +fn do_verify( pkfile: &Option, sigfile: &Option, alg_name: &str, -) { - let pk = parse_pk::(&require_file(pkfile, "pkfile"), alg_name); +) where + RsaPublicKey: SignaturePublicKey + 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 @@ -176,20 +183,21 @@ fn do_verify< } } +/// 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< - PK: SignaturePublicKey, - SK: SignaturePrivateKey, - const PK_LEN: usize, - const SK_LEN: usize, ->( - keygen: fn(&mut dyn RNG) -> Result<(PK, SK), SignatureError>, +fn rsa_keygen_cmd( + keygen: Keygen, pkfile: &Option, output_hex: bool, alg_name: &str, -) { +) where + RsaPublicKey: SignaturePublicKey, + RsaPrivateKey: SignaturePrivateKey, +{ let Some(pkfile) = pkfile else { eprintln!( "Error: {alg_name} keygen needs --pkfile to receive the public key (an RSA \ @@ -209,28 +217,31 @@ fn rsa_keygen_cmd< /// an OS-seeded DRBG through [`SigningKey::create_signer`]. #[allow(clippy::too_many_arguments)] fn rsa_pss_cmd< - A: SignatureAlgorithm, - PK: SignaturePublicKey + VerifyingKey, - SK: SignaturePrivateKey + SigningKey, + A: RsaRandomizedSignatureAlgorithm, const PK_LEN: usize, const SK_LEN: usize, const SIG_LEN: usize, >( action: &RSAAction, - keygen: fn(&mut dyn RNG) -> Result<(PK, SK), SignatureError>, + keygen: Keygen, skfile: &Option, pkfile: &Option, sigfile: &Option, output_hex: bool, alg_name: &str, -) { +) where + RsaPublicKey: SignaturePublicKey + VerifyingKey, + RsaPrivateKey: SignaturePrivateKey + SigningKey, +{ match action { RSAAction::Keygen => { - rsa_keygen_cmd::(keygen, pkfile, output_hex, alg_name) + rsa_keygen_cmd::(keygen, pkfile, output_hex, alg_name) } RSAAction::Sign => { - let sk = - parse_sk::(require_secret(skfile, "skfile").ref_to_bytes(), alg_name); + 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(), @@ -244,7 +255,7 @@ fn rsa_pss_cmd< }); write_bytes_or_hex(&sig, output_hex); } - RSAAction::Verify => do_verify::(pkfile, sigfile, alg_name), + RSAAction::Verify => do_verify::(pkfile, sigfile, alg_name), } } @@ -252,28 +263,31 @@ fn rsa_pss_cmd< /// through [`DeterministicSigningKey::create_signer_deterministic`]. #[allow(clippy::too_many_arguments)] fn rsa_pkcs1_cmd< - A: SignatureAlgorithm, - PK: SignaturePublicKey + VerifyingKey, - SK: SignaturePrivateKey + DeterministicSigningKey, + A: RsaDeterministicSignatureAlgorithm, const PK_LEN: usize, const SK_LEN: usize, const SIG_LEN: usize, >( action: &RSAAction, - keygen: fn(&mut dyn RNG) -> Result<(PK, SK), SignatureError>, + keygen: Keygen, skfile: &Option, pkfile: &Option, sigfile: &Option, output_hex: bool, alg_name: &str, -) { +) where + RsaPublicKey: SignaturePublicKey + VerifyingKey, + RsaPrivateKey: SignaturePrivateKey + DeterministicSigningKey, +{ match action { RSAAction::Keygen => { - rsa_keygen_cmd::(keygen, pkfile, output_hex, alg_name) + rsa_keygen_cmd::(keygen, pkfile, output_hex, alg_name) } RSAAction::Sign => { - let sk = - parse_sk::(require_secret(skfile, "skfile").ref_to_bytes(), alg_name); + 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(); @@ -284,7 +298,7 @@ fn rsa_pkcs1_cmd< }); write_bytes_or_hex(&sig, output_hex); } - RSAAction::Verify => do_verify::(pkfile, sigfile, alg_name), + RSAAction::Verify => do_verify::(pkfile, sigfile, alg_name), } } @@ -294,19 +308,17 @@ pub(crate) fn rsa_1024_cmd( pkfile: &Option, sigfile: &Option, ) { - use rsa_1024::{ - PK_LEN, RSA1024PublicKey, RSASSA_PKCS1_v1_5_SHA256, RSASSA_PKCS1_v1_5_SHA384, SIG_LEN, - }; + 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::( + do_verify::( pkfile, sigfile, "RSA-1024/PKCS#1v1.5/SHA-256", ) } (RSAScheme::Pkcs1v15, RSAHash::Sha384) => { - do_verify::( + do_verify::( pkfile, sigfile, "RSA-1024/PKCS#1v1.5/SHA-384", @@ -316,7 +328,6 @@ pub(crate) fn rsa_1024_cmd( } } -/// RSA-1536: verification only (see module docs). No PSS group exists in Wycheproof at this size. pub(crate) fn rsa_1536_cmd( scheme: &RSAScheme, hash: &RSAHash, @@ -324,26 +335,26 @@ pub(crate) fn rsa_1536_cmd( sigfile: &Option, ) { use rsa_1536::{ - PK_LEN, RSA1536PublicKey, RSASSA_PKCS1_v1_5_SHA256, RSASSA_PKCS1_v1_5_SHA384, - RSASSA_PKCS1_v1_5_SHA512, SIG_LEN, + 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::( + do_verify::( pkfile, sigfile, "RSA-1536/PKCS#1v1.5/SHA-256", ) } (RSAScheme::Pkcs1v15, RSAHash::Sha384) => { - do_verify::( + do_verify::( pkfile, sigfile, "RSA-1536/PKCS#1v1.5/SHA-384", ) } (RSAScheme::Pkcs1v15, RSAHash::Sha512) => { - do_verify::( + do_verify::( pkfile, sigfile, "RSA-1536/PKCS#1v1.5/SHA-512", @@ -353,8 +364,7 @@ pub(crate) fn rsa_1536_cmd( } } -/// RSA-2048: sign and verify. `--hash shake128` is the only SHAKE choice wired up at this size -/// (RFC 8702 §5 pairs SHAKE128 with 2048/3072-bit RSA, SHAKE256 with 4096-bit or larger). +/// 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, @@ -366,55 +376,93 @@ pub(crate) fn rsa_2048_cmd( output_hex: bool, ) { use rsa_2048::{ - PK_LEN, RSA2048PrivateKey as SK, RSA2048PublicKey as PK, 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, + 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, }; - let args = (skfile, pkfile, sigfile, output_hex); - let run = |name: &str, - f: fn( - &RSAAction, - fn(&mut dyn RNG) -> Result<(PK, SK), SignatureError>, - &Option, - &Option, - &Option, - bool, - &str, - )| { f(action, rsa_2048::keygen, args.0, args.1, args.2, args.3, name) }; match (scheme, hash) { - (RSAScheme::Pkcs1v15, RSAHash::Sha256) => run( - "RSA-2048/PKCS#1v1.5/SHA-256", - rsa_pkcs1_cmd::, - ), - (RSAScheme::Pkcs1v15, RSAHash::Sha384) => run( - "RSA-2048/PKCS#1v1.5/SHA-384", - rsa_pkcs1_cmd::, - ), - (RSAScheme::Pkcs1v15, RSAHash::Sha512) => run( - "RSA-2048/PKCS#1v1.5/SHA-512", - rsa_pkcs1_cmd::, - ), - (RSAScheme::Pss, RSAHash::Sha256) => run( - "RSA-2048/PSS/SHA-256", - rsa_pss_cmd::, - ), - (RSAScheme::Pss, RSAHash::Sha384) => run( - "RSA-2048/PSS/SHA-384", - rsa_pss_cmd::, - ), - (RSAScheme::Pss, RSAHash::Sha512) => run( - "RSA-2048/PSS/SHA-512", - rsa_pss_cmd::, - ), - (RSAScheme::Pss, RSAHash::Shake128) => run( - "RSA-2048/PSS-SHAKE128", - rsa_pss_cmd::, - ), + (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_shake_signature_key_pair::, + skfile, + pkfile, + sigfile, + output_hex, + "RSA-2048/PSS-SHAKE128", + ) + } (scheme, hash) => unsupported(scheme, hash, "RSA-2048"), } } -/// RSA-3072: sign and verify. See [`rsa_2048_cmd`] for the SHAKE128 pairing rationale. +/// 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, @@ -426,56 +474,93 @@ pub(crate) fn rsa_3072_cmd( output_hex: bool, ) { use rsa_3072::{ - PK_LEN, RSA3072PrivateKey as SK, RSA3072PublicKey as PK, 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, + 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, }; - let args = (skfile, pkfile, sigfile, output_hex); - let run = |name: &str, - f: fn( - &RSAAction, - fn(&mut dyn RNG) -> Result<(PK, SK), SignatureError>, - &Option, - &Option, - &Option, - bool, - &str, - )| { f(action, rsa_3072::keygen, args.0, args.1, args.2, args.3, name) }; match (scheme, hash) { - (RSAScheme::Pkcs1v15, RSAHash::Sha256) => run( - "RSA-3072/PKCS#1v1.5/SHA-256", - rsa_pkcs1_cmd::, - ), - (RSAScheme::Pkcs1v15, RSAHash::Sha384) => run( - "RSA-3072/PKCS#1v1.5/SHA-384", - rsa_pkcs1_cmd::, - ), - (RSAScheme::Pkcs1v15, RSAHash::Sha512) => run( - "RSA-3072/PKCS#1v1.5/SHA-512", - rsa_pkcs1_cmd::, - ), - (RSAScheme::Pss, RSAHash::Sha256) => run( - "RSA-3072/PSS/SHA-256", - rsa_pss_cmd::, - ), - (RSAScheme::Pss, RSAHash::Sha384) => run( - "RSA-3072/PSS/SHA-384", - rsa_pss_cmd::, - ), - (RSAScheme::Pss, RSAHash::Sha512) => run( - "RSA-3072/PSS/SHA-512", - rsa_pss_cmd::, - ), - (RSAScheme::Pss, RSAHash::Shake128) => run( - "RSA-3072/PSS-SHAKE128", - rsa_pss_cmd::, - ), + (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_shake_signature_key_pair::, + skfile, + pkfile, + sigfile, + output_hex, + "RSA-3072/PSS-SHAKE128", + ) + } (scheme, hash) => unsupported(scheme, hash, "RSA-3072"), } } -/// RSA-4096: sign and verify. `--hash shake256` (not shake128) is wired up at this size -- see -/// [`rsa_2048_cmd`] for the pairing rationale. +/// 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, @@ -487,57 +572,93 @@ pub(crate) fn rsa_4096_cmd( output_hex: bool, ) { use rsa_4096::{ - PK_LEN, RSA4096PrivateKey as SK, RSA4096PublicKey as PK, 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, + 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, }; - let args = (skfile, pkfile, sigfile, output_hex); - let run = |name: &str, - f: fn( - &RSAAction, - fn(&mut dyn RNG) -> Result<(PK, SK), SignatureError>, - &Option, - &Option, - &Option, - bool, - &str, - )| { f(action, rsa_4096::keygen, args.0, args.1, args.2, args.3, name) }; match (scheme, hash) { - (RSAScheme::Pkcs1v15, RSAHash::Sha256) => run( - "RSA-4096/PKCS#1v1.5/SHA-256", - rsa_pkcs1_cmd::, - ), - (RSAScheme::Pkcs1v15, RSAHash::Sha384) => run( - "RSA-4096/PKCS#1v1.5/SHA-384", - rsa_pkcs1_cmd::, - ), - (RSAScheme::Pkcs1v15, RSAHash::Sha512) => run( - "RSA-4096/PKCS#1v1.5/SHA-512", - rsa_pkcs1_cmd::, - ), - (RSAScheme::Pss, RSAHash::Sha256) => run( - "RSA-4096/PSS/SHA-256", - rsa_pss_cmd::, - ), - (RSAScheme::Pss, RSAHash::Sha384) => run( - "RSA-4096/PSS/SHA-384", - rsa_pss_cmd::, - ), - (RSAScheme::Pss, RSAHash::Sha512) => run( - "RSA-4096/PSS/SHA-512", - rsa_pss_cmd::, - ), - (RSAScheme::Pss, RSAHash::Shake256) => run( - "RSA-4096/PSS-SHAKE256", - rsa_pss_cmd::, - ), + (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_shake_signature_key_pair::, + skfile, + pkfile, + sigfile, + output_hex, + "RSA-4096/PSS-SHAKE256", + ) + } (scheme, hash) => unsupported(scheme, hash, "RSA-4096"), } } -/// RSA-8192: sign and verify. No PSS-SHAKE variant is wired up at this size: no Wycheproof -/// vectors exist for it, and RFC 8702 §5 does not name a pairing beyond "4096-bit or larger" for -/// SHAKE256 -- 4096 already covers that recommendation. +/// 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, @@ -549,46 +670,76 @@ pub(crate) fn rsa_8192_cmd( output_hex: bool, ) { use rsa_8192::{ - PK_LEN, RSA8192PrivateKey as SK, RSA8192PublicKey as PK, 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, + 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, }; - let args = (skfile, pkfile, sigfile, output_hex); - let run = |name: &str, - f: fn( - &RSAAction, - fn(&mut dyn RNG) -> Result<(PK, SK), SignatureError>, - &Option, - &Option, - &Option, - bool, - &str, - )| { f(action, rsa_8192::keygen, args.0, args.1, args.2, args.3, name) }; match (scheme, hash) { - (RSAScheme::Pkcs1v15, RSAHash::Sha256) => run( - "RSA-8192/PKCS#1v1.5/SHA-256", - rsa_pkcs1_cmd::, - ), - (RSAScheme::Pkcs1v15, RSAHash::Sha384) => run( - "RSA-8192/PKCS#1v1.5/SHA-384", - rsa_pkcs1_cmd::, - ), - (RSAScheme::Pkcs1v15, RSAHash::Sha512) => run( - "RSA-8192/PKCS#1v1.5/SHA-512", - rsa_pkcs1_cmd::, - ), - (RSAScheme::Pss, RSAHash::Sha256) => run( - "RSA-8192/PSS/SHA-256", - rsa_pss_cmd::, - ), - (RSAScheme::Pss, RSAHash::Sha384) => run( - "RSA-8192/PSS/SHA-384", - rsa_pss_cmd::, - ), - (RSAScheme::Pss, RSAHash::Sha512) => run( - "RSA-8192/PSS/SHA-512", - rsa_pss_cmd::, - ), + (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/tests/rsa_cli_tests.rs b/cli/tests/rsa_cli_tests.rs index 1e0bd8cf..3d7d7cd4 100644 --- a/cli/tests/rsa_cli_tests.rs +++ b/cli/tests/rsa_cli_tests.rs @@ -8,14 +8,16 @@ //! `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::{ - DeterministicSigningKey, SignatureAlgorithm, VerifyingKey, -}; +use bouncycastle::core::signature_key::{DeterministicSigningKey, VerifyingKey}; use bouncycastle::core::traits::{SignaturePrivateKey, SignaturePublicKey}; +use bouncycastle::rsa::RSA2048; +use bouncycastle::rsa::keys::{ + RsaPrivateComponents, RsaPrivateKey, RsaPublicComponents, RsaPublicKey, +}; use bouncycastle::rsa::rsa_2048::{ - RSA2048PrivateKey, RSA2048PublicKey, RSASSA_PKCS1_v1_5_SHA256, RSASSA_PSS_SHA256, - RSASSA_PSS_SHAKE128, SIG_LEN, + 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}; @@ -159,12 +161,20 @@ fn temp_file(tag: &str, contents: &[u8]) -> String { path.to_string_lossy().into_owned() } -fn sk_2048() -> RSA2048PrivateKey { - RSA2048PrivateKey::from_bytes(&unhex(SK_2048_HEX)).expect("the documented key decodes") +/// 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() -> RSA2048PublicKey { - RSA2048PublicKey::from_bytes(&unhex(PK_2048_HEX)).expect("the documented key decodes") +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`). @@ -209,12 +219,8 @@ fn rsa_1024_verifies_a_wycheproof_signature_and_rejects_another_message() { 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 = DeterministicSigningKey::::sign_deterministic( - &sk_2048(), - &msg, - None, - ) - .unwrap(); + 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); @@ -235,17 +241,13 @@ fn rsa_2048_pkcs1v15_signature_matches_the_library_and_verifies() { /// 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]) -where - RSA2048PublicKey: VerifyingKey, -{ - let pk = pk_2048(); +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] { - VerifyingKey::::verify(&pk, msg, None, sig) - .unwrap_or_else(|e| panic!("PSS/{hash}: library rejected {e:?}")); + 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)); } @@ -336,7 +338,7 @@ fn rsa_2048_keygen_then_sign_and_verify() { 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 = RSA2048PublicKey::from_bytes(&unhex(pk_hex.trim())).unwrap(); + 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. @@ -356,7 +358,7 @@ fn rsa_2048_keygen_then_sign_and_verify() { &msg, ); assert!(String::from_utf8_lossy(&out).contains("Signature is valid.")); - VerifyingKey::::verify(&pk, &msg, None, &sig).unwrap(); + 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/crypto/rsa/benches/rsa_1024_benches.rs b/crypto/rsa/benches/rsa_1024_benches.rs index 82a393d0..8f7f5bc4 100644 --- a/crypto/rsa/benches/rsa_1024_benches.rs +++ b/crypto/rsa/benches/rsa_1024_benches.rs @@ -8,9 +8,9 @@ use criterion::{Criterion, criterion_group, criterion_main}; use std::hint::black_box; use bouncycastle_hex::decode as hex_decode; -use bouncycastle_rsa::rsa_1024::{ - RSA1024PublicKey, RSASSA_PKCS1_v1_5_SHA256, RSASSA_PKCS1_v1_5_SHA384, -}; +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] = [ @@ -19,7 +19,7 @@ fn bench_rsa_1024(c: &mut Criterion) { 0xb909dd0f4c6014f2, 0x9c8a5810b6d05990, 0x40760d1f23fe9250, 0x90adb011a919575a, 0x45e48572113cab28, 0xcb9ca9ec12000fc8, 0x91b4fcaf62a14595, 0xac9048a7a4f560af, ]; - let pk_sha256 = RSA1024PublicKey::new(&n_sha256, 0x10001).unwrap(); + let pk_sha256 = RsaPublicComponents::::new(&n_sha256, 0x10001).unwrap(); let msg_sha256 = hex_decode("0000000000000000000000000000000000000000").unwrap(); let sig_sha256: [u8; 128] = hex_decode( "41339884a9b3940e8488d666bb158063c6a2a2717cae7f564834a876fcbf7098ecf3acbfabf37d38a8e6127b1e313744f1f896e165efdaea0b2e7673867842b9e94db0868ed9a92bcdcb370a4e20ff275c82595e4400a8b9e9f12482f014846b48216f321266ae6ae6338dbcdc41b711e483e6e3e728772e7f9f5ef95c30196b", @@ -34,7 +34,7 @@ fn bench_rsa_1024(c: &mut Criterion) { 0xe60ee26a7b7cfccb, 0xaf86df2283c8e327, 0x7dea6692a1713516, 0xe94e94385dffc5e2, 0x8cf0173a0a309a1e, 0x3ea5161e5450d16a, 0xba51135f78844d9a, 0xa1d3912e65d994e0, ]; - let pk_sha384 = RSA1024PublicKey::new(&n_sha384, 0x10001).unwrap(); + let pk_sha384 = RsaPublicComponents::::new(&n_sha384, 0x10001).unwrap(); let msg_sha384 = hex_decode("0000000000000000000000000000000000000000").unwrap(); let sig_sha384: [u8; 128] = hex_decode( "74b9a7b9548a281c5a258520c879e0e64d8a28812a7b6461c6e418e0502b61008a8e535a5b55fb64529a6a6df2f60ef33c1844b27f81532be2bc2992d0eb5e524112da90bf40adefcf206469639ff3895a9826674ee1acbdd623842ab0a9a36d48da13ba17c4ee069254da2ea418d5a8f135e2a414c0654a266d538621917545", @@ -46,24 +46,18 @@ fn bench_rsa_1024(c: &mut Criterion) { let mut group = c.benchmark_group("rsa_1024"); group.bench_function("pkcs1v15_verify_sha256", |b| { b.iter(|| { - VerifyingKey::::verify( - black_box(&pk_sha256), - black_box(&msg_sha256), - None, - black_box(&sig_sha256), - ) - .unwrap() + pk_sha256 + .key::() + .verify(black_box(&msg_sha256), None, black_box(&sig_sha256)) + .unwrap() }) }); group.bench_function("pkcs1v15_verify_sha384", |b| { b.iter(|| { - VerifyingKey::::verify( - black_box(&pk_sha384), - black_box(&msg_sha384), - None, - black_box(&sig_sha384), - ) - .unwrap() + pk_sha384 + .key::() + .verify(black_box(&msg_sha384), None, black_box(&sig_sha384)) + .unwrap() }) }); group.finish(); diff --git a/crypto/rsa/benches/rsa_1536_benches.rs b/crypto/rsa/benches/rsa_1536_benches.rs index ac56c3ed..67045598 100644 --- a/crypto/rsa/benches/rsa_1536_benches.rs +++ b/crypto/rsa/benches/rsa_1536_benches.rs @@ -8,8 +8,10 @@ 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::{ - RSA1536PublicKey, RSASSA_PKCS1_v1_5_SHA256, RSASSA_PKCS1_v1_5_SHA384, RSASSA_PKCS1_v1_5_SHA512, + RSASSA_PKCS1_v1_5_SHA256, RSASSA_PKCS1_v1_5_SHA384, RSASSA_PKCS1_v1_5_SHA512, }; fn bench_rsa_1536(c: &mut Criterion) { @@ -21,7 +23,7 @@ fn bench_rsa_1536(c: &mut Criterion) { 0x5e2c811a56b5d946, 0x6c9fc8200b205487, 0x7b401487a9c85917, 0x41744b5872ccebc8, 0x86eb04d51f21ac52, 0xe029a743f0649ae5, 0x6cf4930cf2615140, 0xeb477c90d46bd189, ]; - let pk_sha256 = RSA1536PublicKey::new(&n_sha256, 0x10001).unwrap(); + let pk_sha256 = RsaPublicComponents::::new(&n_sha256, 0x10001).unwrap(); let msg = hex_decode("0000000000000000000000000000000000000000").unwrap(); let sig_sha256: [u8; 192] = hex_decode( "8d2611d4c79f6b2087ae8bc76610905c361b9fe0a6629388197b4293f9e14ecbeb377206e4c1db35cdc0ab163dc5c51e8a7370a059e9ee8014d18ef0937f7936879d7825c792180a4f10a0d46e0a954f093d703b82bd076dcec0b8a66fc3be9bdf79ce4550c453015dc1c7397ec1bfceed040a4d777915546b9cbcf1eeb13eb71ac49c235e69cb07c315d529442f4863d61b7d5caa5ce07820edf649a9342211a26f8280dab9c5dd11af0752168326f8e8d5e834ddba3bce063f011eccc8f46d", @@ -38,7 +40,7 @@ fn bench_rsa_1536(c: &mut Criterion) { 0xd7841125d38dd9f4, 0xb0ed9964c7b125da, 0x06d573f19163ae2a, 0xa7716c797d15afe5, 0xcf19e47fadf98cfd, 0xdc9306f2f3646bbc, 0x9c3c1865cf6beaf5, 0xd1060fe7c6d185f0, ]; - let pk_sha384 = RSA1536PublicKey::new(&n_sha384, 0x10001).unwrap(); + let pk_sha384 = RsaPublicComponents::::new(&n_sha384, 0x10001).unwrap(); let sig_sha384: [u8; 192] = hex_decode( "58c4c42da5eee1b757b31e3362a95d75180c0fee472c431527ff5500fe0b5c1d59968d79e6e41650f013a6b3e37c5a1d79233b818ef76c4ed469a09607becdc58987e6a548610de14ff06899ef284778dd5329a27b85072e8ffd46b63a5e8f7602ddb9fc5a07224c49818fc8057581ea36da033f2b936f0761186c7fd82b474e87d47aa1b7ec610642d3bcb16c59bb70ac68b1f081a9c9248f069474d6ed9b29c669fc40a979cdfc2053e1a3c0cf40efa29c01785323995f1d8f3850c32bdf92", ) @@ -54,7 +56,7 @@ fn bench_rsa_1536(c: &mut Criterion) { 0xfe887a4a1fae6ca8, 0xa96a2bedc3e72738, 0xe2ad09578c749863, 0xffb63f097ed7b5c5, 0xcea5ba02d99f0807, 0x1cb9a9b7b769d6df, 0xfd4c711aef054e29, 0xd1f33c4d0c3b127c, ]; - let pk_sha512 = RSA1536PublicKey::new(&n_sha512, 0x10001).unwrap(); + let pk_sha512 = RsaPublicComponents::::new(&n_sha512, 0x10001).unwrap(); let sig_sha512: [u8; 192] = hex_decode( "5259fe9566e1bd81952a805384b1657374f33550ee0895b57b7a0869a831270d3b3b2db8e295a4eb98d8eb036183b3d228ad22b8e493c7eb0f9ab00eeab2e086f10f8018a8daaff4858ae745a4d70881a166963c64403216422e18974aa456d8229ef2e43002e0390166630c7fabd14efaa974a9521a72a69e0b446971db077ce80f6dd95cf797b6ed276873bbf6b1ba6a79df8c917c2a3fbbc0e5347b0bb99eec6ad0b6bdb7bc9d3e0a7f6b7b623f2aa9dba1e940676ec5629d39778286f261", ) @@ -65,35 +67,26 @@ fn bench_rsa_1536(c: &mut Criterion) { let mut group = c.benchmark_group("rsa_1536"); group.bench_function("pkcs1v15_verify_sha256", |b| { b.iter(|| { - VerifyingKey::::verify( - black_box(&pk_sha256), - black_box(&msg), - None, - black_box(&sig_sha256), - ) - .unwrap() + pk_sha256 + .key::() + .verify(black_box(&msg), None, black_box(&sig_sha256)) + .unwrap() }) }); group.bench_function("pkcs1v15_verify_sha384", |b| { b.iter(|| { - VerifyingKey::::verify( - black_box(&pk_sha384), - black_box(&msg), - None, - black_box(&sig_sha384), - ) - .unwrap() + pk_sha384 + .key::() + .verify(black_box(&msg), None, black_box(&sig_sha384)) + .unwrap() }) }); group.bench_function("pkcs1v15_verify_sha512", |b| { b.iter(|| { - VerifyingKey::::verify( - black_box(&pk_sha512), - black_box(&msg), - None, - black_box(&sig_sha512), - ) - .unwrap() + pk_sha512 + .key::() + .verify(black_box(&msg), None, black_box(&sig_sha512)) + .unwrap() }) }); group.finish(); diff --git a/crypto/rsa/benches/rsa_2048_benches.rs b/crypto/rsa/benches/rsa_2048_benches.rs index 78d90df0..e2a43d40 100644 --- a/crypto/rsa/benches/rsa_2048_benches.rs +++ b/crypto/rsa/benches/rsa_2048_benches.rs @@ -9,21 +9,22 @@ use bouncycastle_core::signature_key::{DeterministicSigningKey, SigningKey, Veri use bouncycastle_core::traits::{ KEMPrivateKey, KEMPublicKey, SignaturePrivateKey, SignaturePublicKey, }; +use bouncycastle_rsa::RSA2048; use bouncycastle_rsa::rsa_2048::{RSA2048KEMPrivateKey, RSA2048KEMPublicKey}; +use bouncycastle_rsa::size::RsaSigningSize; use criterion::{Criterion, criterion_group, criterion_main}; use std::hint::black_box; use bouncycastle_rng::DefaultRNG; -use bouncycastle_rsa::rsa_2048::keygen; +use bouncycastle_rsa::keys::{RsaPrivateComponents, RsaPublicComponents}; use bouncycastle_rsa::rsa_2048::{ - RSA2048PrivateKey, RSA2048PublicKey, 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, + 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() -> RSA2048PrivateKey { +fn genuine_key() -> RsaPrivateComponents { let p: [u64; 16] = [ 0x0ea36cfb3a5b18f1, 0x48a6e65332119129, 0x110ad9e7b48a1c93, 0x569156b90113e2e9, 0xe79813a575cfad9c, 0x69d659d143ec6f17, 0xe81e6bab5ddaa783, 0xbff1c5b80a69f788, @@ -54,209 +55,143 @@ fn genuine_key() -> RSA2048PrivateKey { 0xe923e1097c0c562f, 0xc968b48a91c38b5b, 0x933e85179c0320b0, 0x7993d0445f758d51, 0x9bfc042ee0924b1b, 0x41f956d90fa8a793, 0xee7a87b6483a66ee, 0x2640fbfbcfefb163, ]; - RSA2048PrivateKey::from_crt_components(&p, &q, &d_p, &d_q, &q_inv) + 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 = RSA2048PublicKey::new(sk.n(), 0x10001).unwrap(); + let pk = RsaPublicComponents::::new(sk.n(), 0x10001).unwrap(); let mut rng = DefaultRNG::default(); - let sig_pkcs1_256 = - DeterministicSigningKey::::sign_deterministic( - &sk, MSG, None, - ) - .unwrap(); - let sig_pkcs1_384 = - DeterministicSigningKey::::sign_deterministic( - &sk, MSG, None, - ) - .unwrap(); - let sig_pkcs1_512 = - DeterministicSigningKey::::sign_deterministic( - &sk, MSG, None, - ) - .unwrap(); - let sig_pss_256 = SigningKey::::sign(&sk, &mut rng, MSG, None).unwrap(); - let sig_pss_384 = SigningKey::::sign(&sk, &mut rng, MSG, None).unwrap(); - let sig_pss_512 = SigningKey::::sign(&sk, &mut rng, MSG, None).unwrap(); - let sig_pss_shake128 = - SigningKey::::sign(&sk, &mut rng, MSG, None).unwrap(); + 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( - DeterministicSigningKey::::sign_deterministic( - black_box(&sk), - black_box(MSG), - None, - ) - .unwrap(), + sk.key::() + .sign_deterministic(black_box(MSG), None) + .unwrap(), ) }) }); group.bench_function("pkcs1v15_verify_sha256", |b| { b.iter(|| { - VerifyingKey::::verify( - black_box(&pk), - black_box(MSG), - None, - black_box(&sig_pkcs1_256), - ) - .unwrap() + pk.key::() + .verify(black_box(MSG), None, black_box(&sig_pkcs1_256)) + .unwrap() }) }); group.bench_function("pkcs1v15_sign_sha384", |b| { b.iter(|| { black_box( - DeterministicSigningKey::::sign_deterministic( - black_box(&sk), - black_box(MSG), - None, - ) - .unwrap(), + sk.key::() + .sign_deterministic(black_box(MSG), None) + .unwrap(), ) }) }); group.bench_function("pkcs1v15_verify_sha384", |b| { b.iter(|| { - VerifyingKey::::verify( - black_box(&pk), - black_box(MSG), - None, - black_box(&sig_pkcs1_384), - ) - .unwrap() + pk.key::() + .verify(black_box(MSG), None, black_box(&sig_pkcs1_384)) + .unwrap() }) }); group.bench_function("pkcs1v15_sign_sha512", |b| { b.iter(|| { black_box( - DeterministicSigningKey::::sign_deterministic( - black_box(&sk), - black_box(MSG), - None, - ) - .unwrap(), + sk.key::() + .sign_deterministic(black_box(MSG), None) + .unwrap(), ) }) }); group.bench_function("pkcs1v15_verify_sha512", |b| { b.iter(|| { - VerifyingKey::::verify( - black_box(&pk), - black_box(MSG), - None, - black_box(&sig_pkcs1_512), - ) - .unwrap() + pk.key::() + .verify(black_box(MSG), None, black_box(&sig_pkcs1_512)) + .unwrap() }) }); group.bench_function("pss_sign_sha256", |b| { b.iter(|| { black_box( - SigningKey::::sign( - black_box(&sk), - &mut DefaultRNG::default(), - black_box(MSG), - None, - ) - .unwrap(), + sk.key::() + .sign(&mut DefaultRNG::default(), black_box(MSG), None) + .unwrap(), ) }) }); group.bench_function("pss_verify_sha256", |b| { b.iter(|| { - VerifyingKey::::verify( - black_box(&pk), - black_box(MSG), - None, - black_box(&sig_pss_256), - ) - .unwrap() + pk.key::() + .verify(black_box(MSG), None, black_box(&sig_pss_256)) + .unwrap() }) }); group.bench_function("pss_sign_sha384", |b| { b.iter(|| { black_box( - SigningKey::::sign( - black_box(&sk), - &mut DefaultRNG::default(), - black_box(MSG), - None, - ) - .unwrap(), + sk.key::() + .sign(&mut DefaultRNG::default(), black_box(MSG), None) + .unwrap(), ) }) }); group.bench_function("pss_verify_sha384", |b| { b.iter(|| { - VerifyingKey::::verify( - black_box(&pk), - black_box(MSG), - None, - black_box(&sig_pss_384), - ) - .unwrap() + pk.key::() + .verify(black_box(MSG), None, black_box(&sig_pss_384)) + .unwrap() }) }); group.bench_function("pss_sign_sha512", |b| { b.iter(|| { black_box( - SigningKey::::sign( - black_box(&sk), - &mut DefaultRNG::default(), - black_box(MSG), - None, - ) - .unwrap(), + sk.key::() + .sign(&mut DefaultRNG::default(), black_box(MSG), None) + .unwrap(), ) }) }); group.bench_function("pss_verify_sha512", |b| { b.iter(|| { - VerifyingKey::::verify( - black_box(&pk), - black_box(MSG), - None, - black_box(&sig_pss_512), - ) - .unwrap() + pk.key::() + .verify(black_box(MSG), None, black_box(&sig_pss_512)) + .unwrap() }) }); group.bench_function("pss_sign_shake128", |b| { b.iter(|| { black_box( - SigningKey::::sign( - black_box(&sk), - &mut DefaultRNG::default(), - black_box(MSG), - None, - ) - .unwrap(), + sk.key::() + .sign(&mut DefaultRNG::default(), black_box(MSG), None) + .unwrap(), ) }) }); group.bench_function("pss_verify_shake128", |b| { b.iter(|| { - VerifyingKey::::verify( - black_box(&pk), - black_box(MSG), - None, - black_box(&sig_pss_shake128), - ) - .unwrap() + 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.encode()).unwrap(); - let kem_pk = RSA2048KEMPublicKey::from_bytes(&pk.encode()).unwrap(); + 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())) @@ -272,7 +207,7 @@ fn bench_rsa_2048(c: &mut Criterion) { 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(keygen(&mut DefaultRNG::default()).unwrap())) + b.iter(|| black_box(RSA2048::keygen(&mut DefaultRNG::default()).unwrap())) }); keygen_group.finish(); } diff --git a/crypto/rsa/benches/rsa_3072_benches.rs b/crypto/rsa/benches/rsa_3072_benches.rs index 3ea62f7f..a4cd287a 100644 --- a/crypto/rsa/benches/rsa_3072_benches.rs +++ b/crypto/rsa/benches/rsa_3072_benches.rs @@ -7,21 +7,22 @@ use bouncycastle_core::signature_key::{DeterministicSigningKey, SigningKey, Veri use bouncycastle_core::traits::{ KEMPrivateKey, KEMPublicKey, SignaturePrivateKey, SignaturePublicKey, }; +use bouncycastle_rsa::RSA3072; use bouncycastle_rsa::rsa_3072::{RSA3072KEMPrivateKey, RSA3072KEMPublicKey}; +use bouncycastle_rsa::size::RsaSigningSize; use criterion::{Criterion, criterion_group, criterion_main}; use std::hint::black_box; use bouncycastle_rng::DefaultRNG; -use bouncycastle_rsa::rsa_3072::keygen; +use bouncycastle_rsa::keys::{RsaPrivateComponents, RsaPublicComponents}; use bouncycastle_rsa::rsa_3072::{ - RSA3072PrivateKey, RSA3072PublicKey, 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, + 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() -> RSA3072PrivateKey { +fn genuine_key() -> RsaPrivateComponents { let p: [u64; 24] = [ 0xb26d973345bc4c5f, 0x23251a1d29962ca9, 0x554fc3f23d6c9046, 0x89ffe73b1401e9b8, 0xe0b448b454670aca, 0xa73ea5c2413d1da2, 0xe9539bc7a8d3b351, 0x357984fc116af9cb, @@ -62,209 +63,143 @@ fn genuine_key() -> RSA3072PrivateKey { 0xfe6c3600d9b8e9a9, 0x744fac4daabf5488, 0xfbee6ec24b75fbf0, 0x8be552c8be44f139, 0xfb0da96bd423759d, 0xb3443d93e7e8ca62, 0x36fe01b950885ecd, 0x214a1f73130e48b3, ]; - RSA3072PrivateKey::from_crt_components(&p, &q, &d_p, &d_q, &q_inv) + 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 = RSA3072PublicKey::new(sk.n(), 0x10001).unwrap(); + let pk = RsaPublicComponents::::new(sk.n(), 0x10001).unwrap(); let mut rng = DefaultRNG::default(); - let sig_pkcs1_256 = - DeterministicSigningKey::::sign_deterministic( - &sk, MSG, None, - ) - .unwrap(); - let sig_pkcs1_384 = - DeterministicSigningKey::::sign_deterministic( - &sk, MSG, None, - ) - .unwrap(); - let sig_pkcs1_512 = - DeterministicSigningKey::::sign_deterministic( - &sk, MSG, None, - ) - .unwrap(); - let sig_pss_256 = SigningKey::::sign(&sk, &mut rng, MSG, None).unwrap(); - let sig_pss_384 = SigningKey::::sign(&sk, &mut rng, MSG, None).unwrap(); - let sig_pss_512 = SigningKey::::sign(&sk, &mut rng, MSG, None).unwrap(); - let sig_pss_shake128 = - SigningKey::::sign(&sk, &mut rng, MSG, None).unwrap(); + 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( - DeterministicSigningKey::::sign_deterministic( - black_box(&sk), - black_box(MSG), - None, - ) - .unwrap(), + sk.key::() + .sign_deterministic(black_box(MSG), None) + .unwrap(), ) }) }); group.bench_function("pkcs1v15_verify_sha256", |b| { b.iter(|| { - VerifyingKey::::verify( - black_box(&pk), - black_box(MSG), - None, - black_box(&sig_pkcs1_256), - ) - .unwrap() + pk.key::() + .verify(black_box(MSG), None, black_box(&sig_pkcs1_256)) + .unwrap() }) }); group.bench_function("pkcs1v15_sign_sha384", |b| { b.iter(|| { black_box( - DeterministicSigningKey::::sign_deterministic( - black_box(&sk), - black_box(MSG), - None, - ) - .unwrap(), + sk.key::() + .sign_deterministic(black_box(MSG), None) + .unwrap(), ) }) }); group.bench_function("pkcs1v15_verify_sha384", |b| { b.iter(|| { - VerifyingKey::::verify( - black_box(&pk), - black_box(MSG), - None, - black_box(&sig_pkcs1_384), - ) - .unwrap() + pk.key::() + .verify(black_box(MSG), None, black_box(&sig_pkcs1_384)) + .unwrap() }) }); group.bench_function("pkcs1v15_sign_sha512", |b| { b.iter(|| { black_box( - DeterministicSigningKey::::sign_deterministic( - black_box(&sk), - black_box(MSG), - None, - ) - .unwrap(), + sk.key::() + .sign_deterministic(black_box(MSG), None) + .unwrap(), ) }) }); group.bench_function("pkcs1v15_verify_sha512", |b| { b.iter(|| { - VerifyingKey::::verify( - black_box(&pk), - black_box(MSG), - None, - black_box(&sig_pkcs1_512), - ) - .unwrap() + pk.key::() + .verify(black_box(MSG), None, black_box(&sig_pkcs1_512)) + .unwrap() }) }); group.bench_function("pss_sign_sha256", |b| { b.iter(|| { black_box( - SigningKey::::sign( - black_box(&sk), - &mut DefaultRNG::default(), - black_box(MSG), - None, - ) - .unwrap(), + sk.key::() + .sign(&mut DefaultRNG::default(), black_box(MSG), None) + .unwrap(), ) }) }); group.bench_function("pss_verify_sha256", |b| { b.iter(|| { - VerifyingKey::::verify( - black_box(&pk), - black_box(MSG), - None, - black_box(&sig_pss_256), - ) - .unwrap() + pk.key::() + .verify(black_box(MSG), None, black_box(&sig_pss_256)) + .unwrap() }) }); group.bench_function("pss_sign_sha384", |b| { b.iter(|| { black_box( - SigningKey::::sign( - black_box(&sk), - &mut DefaultRNG::default(), - black_box(MSG), - None, - ) - .unwrap(), + sk.key::() + .sign(&mut DefaultRNG::default(), black_box(MSG), None) + .unwrap(), ) }) }); group.bench_function("pss_verify_sha384", |b| { b.iter(|| { - VerifyingKey::::verify( - black_box(&pk), - black_box(MSG), - None, - black_box(&sig_pss_384), - ) - .unwrap() + pk.key::() + .verify(black_box(MSG), None, black_box(&sig_pss_384)) + .unwrap() }) }); group.bench_function("pss_sign_sha512", |b| { b.iter(|| { black_box( - SigningKey::::sign( - black_box(&sk), - &mut DefaultRNG::default(), - black_box(MSG), - None, - ) - .unwrap(), + sk.key::() + .sign(&mut DefaultRNG::default(), black_box(MSG), None) + .unwrap(), ) }) }); group.bench_function("pss_verify_sha512", |b| { b.iter(|| { - VerifyingKey::::verify( - black_box(&pk), - black_box(MSG), - None, - black_box(&sig_pss_512), - ) - .unwrap() + pk.key::() + .verify(black_box(MSG), None, black_box(&sig_pss_512)) + .unwrap() }) }); group.bench_function("pss_sign_shake128", |b| { b.iter(|| { black_box( - SigningKey::::sign( - black_box(&sk), - &mut DefaultRNG::default(), - black_box(MSG), - None, - ) - .unwrap(), + sk.key::() + .sign(&mut DefaultRNG::default(), black_box(MSG), None) + .unwrap(), ) }) }); group.bench_function("pss_verify_shake128", |b| { b.iter(|| { - VerifyingKey::::verify( - black_box(&pk), - black_box(MSG), - None, - black_box(&sig_pss_shake128), - ) - .unwrap() + 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.encode()).unwrap(); - let kem_pk = RSA3072KEMPublicKey::from_bytes(&pk.encode()).unwrap(); + 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())) @@ -280,7 +215,7 @@ fn bench_rsa_3072(c: &mut Criterion) { 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(keygen(&mut DefaultRNG::default()).unwrap())) + b.iter(|| black_box(RSA3072::keygen(&mut DefaultRNG::default()).unwrap())) }); keygen_group.finish(); } diff --git a/crypto/rsa/benches/rsa_4096_benches.rs b/crypto/rsa/benches/rsa_4096_benches.rs index a2345451..9dee0714 100644 --- a/crypto/rsa/benches/rsa_4096_benches.rs +++ b/crypto/rsa/benches/rsa_4096_benches.rs @@ -8,20 +8,21 @@ use bouncycastle_core::signature_key::{DeterministicSigningKey, SigningKey, Veri use bouncycastle_core::traits::{ KEMPrivateKey, KEMPublicKey, SignaturePrivateKey, SignaturePublicKey, }; +use bouncycastle_rsa::RSA4096; use bouncycastle_rsa::rsa_4096::{RSA4096KEMPrivateKey, RSA4096KEMPublicKey}; 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::{ - RSA4096PrivateKey, RSA4096PublicKey, 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, + 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() -> RSA4096PrivateKey { +fn genuine_key() -> RsaPrivateComponents { let p: [u64; 32] = [ 0x5141acd4afd4771f, 0x5857742b7e4032dc, 0xb7a9b97fe5371396, 0x4b1783c5bc91a6dc, 0xaf5d0c912d97b728, 0xeb265a7f28b88976, 0x5e993302aa72f11d, 0xc007ad09d76ae22a, @@ -72,209 +73,143 @@ fn genuine_key() -> RSA4096PrivateKey { 0x748d7b5d94cacd4d, 0xcf634f3a07cea4b7, 0x8dbcca51f4da4379, 0x80774236a54ec9dc, 0x6a1ef00ee582d3d1, 0xdecfb14ca1e80c8e, 0xc78af5f6c807cc99, 0x484ad86e79415ea3, ]; - RSA4096PrivateKey::from_crt_components(&p, &q, &d_p, &d_q, &q_inv) + 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 = RSA4096PublicKey::new(sk.n(), 0x10001).unwrap(); + let pk = RsaPublicComponents::::new(sk.n(), 0x10001).unwrap(); let mut rng = DefaultRNG::default(); - let sig_pkcs1_256 = - DeterministicSigningKey::::sign_deterministic( - &sk, MSG, None, - ) - .unwrap(); - let sig_pkcs1_384 = - DeterministicSigningKey::::sign_deterministic( - &sk, MSG, None, - ) - .unwrap(); - let sig_pkcs1_512 = - DeterministicSigningKey::::sign_deterministic( - &sk, MSG, None, - ) - .unwrap(); - let sig_pss_256 = SigningKey::::sign(&sk, &mut rng, MSG, None).unwrap(); - let sig_pss_384 = SigningKey::::sign(&sk, &mut rng, MSG, None).unwrap(); - let sig_pss_512 = SigningKey::::sign(&sk, &mut rng, MSG, None).unwrap(); - let sig_pss_shake256 = - SigningKey::::sign(&sk, &mut rng, MSG, None).unwrap(); + 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( - DeterministicSigningKey::::sign_deterministic( - black_box(&sk), - black_box(MSG), - None, - ) - .unwrap(), + sk.key::() + .sign_deterministic(black_box(MSG), None) + .unwrap(), ) }) }); group.bench_function("pkcs1v15_verify_sha256", |b| { b.iter(|| { - VerifyingKey::::verify( - black_box(&pk), - black_box(MSG), - None, - black_box(&sig_pkcs1_256), - ) - .unwrap() + pk.key::() + .verify(black_box(MSG), None, black_box(&sig_pkcs1_256)) + .unwrap() }) }); group.bench_function("pkcs1v15_sign_sha384", |b| { b.iter(|| { black_box( - DeterministicSigningKey::::sign_deterministic( - black_box(&sk), - black_box(MSG), - None, - ) - .unwrap(), + sk.key::() + .sign_deterministic(black_box(MSG), None) + .unwrap(), ) }) }); group.bench_function("pkcs1v15_verify_sha384", |b| { b.iter(|| { - VerifyingKey::::verify( - black_box(&pk), - black_box(MSG), - None, - black_box(&sig_pkcs1_384), - ) - .unwrap() + pk.key::() + .verify(black_box(MSG), None, black_box(&sig_pkcs1_384)) + .unwrap() }) }); group.bench_function("pkcs1v15_sign_sha512", |b| { b.iter(|| { black_box( - DeterministicSigningKey::::sign_deterministic( - black_box(&sk), - black_box(MSG), - None, - ) - .unwrap(), + sk.key::() + .sign_deterministic(black_box(MSG), None) + .unwrap(), ) }) }); group.bench_function("pkcs1v15_verify_sha512", |b| { b.iter(|| { - VerifyingKey::::verify( - black_box(&pk), - black_box(MSG), - None, - black_box(&sig_pkcs1_512), - ) - .unwrap() + pk.key::() + .verify(black_box(MSG), None, black_box(&sig_pkcs1_512)) + .unwrap() }) }); group.bench_function("pss_sign_sha256", |b| { b.iter(|| { black_box( - SigningKey::::sign( - black_box(&sk), - &mut DefaultRNG::default(), - black_box(MSG), - None, - ) - .unwrap(), + sk.key::() + .sign(&mut DefaultRNG::default(), black_box(MSG), None) + .unwrap(), ) }) }); group.bench_function("pss_verify_sha256", |b| { b.iter(|| { - VerifyingKey::::verify( - black_box(&pk), - black_box(MSG), - None, - black_box(&sig_pss_256), - ) - .unwrap() + pk.key::() + .verify(black_box(MSG), None, black_box(&sig_pss_256)) + .unwrap() }) }); group.bench_function("pss_sign_sha384", |b| { b.iter(|| { black_box( - SigningKey::::sign( - black_box(&sk), - &mut DefaultRNG::default(), - black_box(MSG), - None, - ) - .unwrap(), + sk.key::() + .sign(&mut DefaultRNG::default(), black_box(MSG), None) + .unwrap(), ) }) }); group.bench_function("pss_verify_sha384", |b| { b.iter(|| { - VerifyingKey::::verify( - black_box(&pk), - black_box(MSG), - None, - black_box(&sig_pss_384), - ) - .unwrap() + pk.key::() + .verify(black_box(MSG), None, black_box(&sig_pss_384)) + .unwrap() }) }); group.bench_function("pss_sign_sha512", |b| { b.iter(|| { black_box( - SigningKey::::sign( - black_box(&sk), - &mut DefaultRNG::default(), - black_box(MSG), - None, - ) - .unwrap(), + sk.key::() + .sign(&mut DefaultRNG::default(), black_box(MSG), None) + .unwrap(), ) }) }); group.bench_function("pss_verify_sha512", |b| { b.iter(|| { - VerifyingKey::::verify( - black_box(&pk), - black_box(MSG), - None, - black_box(&sig_pss_512), - ) - .unwrap() + pk.key::() + .verify(black_box(MSG), None, black_box(&sig_pss_512)) + .unwrap() }) }); group.bench_function("pss_sign_shake256", |b| { b.iter(|| { black_box( - SigningKey::::sign( - black_box(&sk), - &mut DefaultRNG::default(), - black_box(MSG), - None, - ) - .unwrap(), + sk.key::() + .sign(&mut DefaultRNG::default(), black_box(MSG), None) + .unwrap(), ) }) }); group.bench_function("pss_verify_shake256", |b| { b.iter(|| { - VerifyingKey::::verify( - black_box(&pk), - black_box(MSG), - None, - black_box(&sig_pss_shake256), - ) - .unwrap() + 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.encode()).unwrap(); - let kem_pk = RSA4096KEMPublicKey::from_bytes(&pk.encode()).unwrap(); + 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())) diff --git a/crypto/rsa/benches/rsa_8192_benches.rs b/crypto/rsa/benches/rsa_8192_benches.rs index e42cf3db..ae02edc0 100644 --- a/crypto/rsa/benches/rsa_8192_benches.rs +++ b/crypto/rsa/benches/rsa_8192_benches.rs @@ -8,19 +8,21 @@ use bouncycastle_core::signature_key::{DeterministicSigningKey, SigningKey, Veri use bouncycastle_core::traits::{ KEMPrivateKey, KEMPublicKey, SignaturePrivateKey, SignaturePublicKey, }; +use bouncycastle_rsa::RSA8192; use bouncycastle_rsa::rsa_8192::{RSA8192KEMPrivateKey, RSA8192KEMPublicKey}; 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::{ - RSA8192PrivateKey, RSA8192PublicKey, 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_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() -> RSA8192PrivateKey { +fn genuine_key() -> RsaPrivateComponents { let p: [u64; 64] = [ 0xa9a87892c469b1e5, 0x038c3f4efcb198ac, 0xed4f14df1b8a1e1f, 0xef2330d78ee73020, 0xd3093ddaf276904c, 0x94a438d69aeaff23, 0x48dbb3d700ad58ed, 0xbbd763b5346ff916, @@ -111,186 +113,126 @@ fn genuine_key() -> RSA8192PrivateKey { 0xd1aac2fe108f98c0, 0x1e799537a42b3060, 0xdbcce6fc287e449b, 0x1985969e5afbc524, 0x61ba61f820f83597, 0x65c8523f0767bccc, 0xde04e1644a214f9a, 0x9748f8d853be7131, ]; - RSA8192PrivateKey::from_crt_components(&p, &q, &d_p, &d_q, &q_inv) + 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 = RSA8192PublicKey::new(sk.n(), 0x10001).unwrap(); + let pk = RsaPublicComponents::::new(sk.n(), 0x10001).unwrap(); let mut rng = DefaultRNG::default(); - let sig_pkcs1_256 = - DeterministicSigningKey::::sign_deterministic( - &sk, MSG, None, - ) - .unwrap(); - let sig_pkcs1_384 = - DeterministicSigningKey::::sign_deterministic( - &sk, MSG, None, - ) - .unwrap(); - let sig_pkcs1_512 = - DeterministicSigningKey::::sign_deterministic( - &sk, MSG, None, - ) - .unwrap(); - let sig_pss_256 = - SigningKey::::sign(&sk, &mut rng, MSG, None).unwrap(); - let sig_pss_384 = - SigningKey::::sign(&sk, &mut rng, MSG, None).unwrap(); - let sig_pss_512 = - SigningKey::::sign(&sk, &mut rng, MSG, None).unwrap(); + 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( - DeterministicSigningKey::::sign_deterministic( - black_box(&sk), - black_box(MSG), - None, - ) - .unwrap(), + sk.key::() + .sign_deterministic(black_box(MSG), None) + .unwrap(), ) }) }); group.bench_function("pkcs1v15_verify_sha256", |b| { b.iter(|| { - VerifyingKey::::verify( - black_box(&pk), - black_box(MSG), - None, - black_box(&sig_pkcs1_256), - ) - .unwrap() + pk.key::() + .verify(black_box(MSG), None, black_box(&sig_pkcs1_256)) + .unwrap() }) }); group.bench_function("pkcs1v15_sign_sha384", |b| { b.iter(|| { black_box( - DeterministicSigningKey::::sign_deterministic( - black_box(&sk), - black_box(MSG), - None, - ) - .unwrap(), + sk.key::() + .sign_deterministic(black_box(MSG), None) + .unwrap(), ) }) }); group.bench_function("pkcs1v15_verify_sha384", |b| { b.iter(|| { - VerifyingKey::::verify( - black_box(&pk), - black_box(MSG), - None, - black_box(&sig_pkcs1_384), - ) - .unwrap() + pk.key::() + .verify(black_box(MSG), None, black_box(&sig_pkcs1_384)) + .unwrap() }) }); group.bench_function("pkcs1v15_sign_sha512", |b| { b.iter(|| { black_box( - DeterministicSigningKey::::sign_deterministic( - black_box(&sk), - black_box(MSG), - None, - ) - .unwrap(), + sk.key::() + .sign_deterministic(black_box(MSG), None) + .unwrap(), ) }) }); group.bench_function("pkcs1v15_verify_sha512", |b| { b.iter(|| { - VerifyingKey::::verify( - black_box(&pk), - black_box(MSG), - None, - black_box(&sig_pkcs1_512), - ) - .unwrap() + pk.key::() + .verify(black_box(MSG), None, black_box(&sig_pkcs1_512)) + .unwrap() }) }); group.bench_function("pss_sign_sha256", |b| { b.iter(|| { black_box( - SigningKey::::sign( - black_box(&sk), - &mut DefaultRNG::default(), - black_box(MSG), - None, - ) - .unwrap(), + sk.key::() + .sign(&mut DefaultRNG::default(), black_box(MSG), None) + .unwrap(), ) }) }); group.bench_function("pss_verify_sha256", |b| { b.iter(|| { - VerifyingKey::::verify( - black_box(&pk), - black_box(MSG), - None, - black_box(&sig_pss_256), - ) - .unwrap() + pk.key::() + .verify(black_box(MSG), None, black_box(&sig_pss_256)) + .unwrap() }) }); group.bench_function("pss_sign_sha384", |b| { b.iter(|| { black_box( - SigningKey::::sign( - black_box(&sk), - &mut DefaultRNG::default(), - black_box(MSG), - None, - ) - .unwrap(), + sk.key::() + .sign(&mut DefaultRNG::default(), black_box(MSG), None) + .unwrap(), ) }) }); group.bench_function("pss_verify_sha384", |b| { b.iter(|| { - VerifyingKey::::verify( - black_box(&pk), - black_box(MSG), - None, - black_box(&sig_pss_384), - ) - .unwrap() + pk.key::() + .verify(black_box(MSG), None, black_box(&sig_pss_384)) + .unwrap() }) }); group.bench_function("pss_sign_sha512", |b| { b.iter(|| { black_box( - SigningKey::::sign( - black_box(&sk), - &mut DefaultRNG::default(), - black_box(MSG), - None, - ) - .unwrap(), + sk.key::() + .sign(&mut DefaultRNG::default(), black_box(MSG), None) + .unwrap(), ) }) }); group.bench_function("pss_verify_sha512", |b| { b.iter(|| { - VerifyingKey::::verify( - black_box(&pk), - black_box(MSG), - None, - black_box(&sig_pss_512), - ) - .unwrap() + 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.encode()).unwrap(); - let kem_pk = RSA8192KEMPublicKey::from_bytes(&pk.encode()).unwrap(); + 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())) diff --git a/crypto/rsa/src/keygen.rs b/crypto/rsa/src/keygen.rs index 80135672..b4e3a437 100644 --- a/crypto/rsa/src/keygen.rs +++ b/crypto/rsa/src/keygen.rs @@ -7,7 +7,7 @@ //! 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 -//! (`crate::rsa_2048::keygen` and siblings): `nlen` is fixed by the width, `e` by +//! (`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. //! @@ -24,7 +24,7 @@ //! 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::{RsaPrivateKey, RsaPublicKey}; +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}; @@ -500,7 +500,7 @@ fn primes_too_close(p: &[u64; N], q: &[u64; N]) -> bool { /// 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 `crate::rsa_2048::keygen` for the RSA-2048 values. +/// 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 @@ -516,7 +516,7 @@ pub fn keygen_from_rng Result<(RsaPublicKey, RsaPrivateKey), SignatureError> +) -> Result<(RsaPublicComponents, RsaPrivateComponents), SignatureError> where K: RsaSigningSize + RsaSize, { @@ -589,8 +589,8 @@ where zeroize_in_place(&mut p_minus_2); } - let sk = RsaPrivateKey::::from_crt_components(&p, &q, &d_p, &d_q, &q_inv)?; - let pk = RsaPublicKey::::new(sk.n(), PUBLIC_EXPONENT)?; + 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)); } } diff --git a/crypto/rsa/src/keys.rs b/crypto/rsa/src/keys.rs index 0e690546..296316c1 100644 --- a/crypto/rsa/src/keys.rs +++ b/crypto/rsa/src/keys.rs @@ -1,43 +1,52 @@ -//! RSA key types: [`RsaPublicKey`] (RFC 8017 §3.1's `(n, e)`) and [`RsaPrivateKey`] (§3.2's -//! "second representation", the CRT quintuple `p`, `q`, `dP`, `dQ`, `qInv`), generic over the -//! modulus size [`RsaSize`]. +//! 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. //! -//! Keys come either from [`crate::keygen`] (FIPS 186-5 Appendix A.1.3, through -//! [`RsaSigningSize::keygen`]) or from externally supplied -//! key material (loaded from CAVP/wycheproof test vectors, or a key produced by another -//! implementation) through [`RsaPrivateKey::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. +//! 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 key types implement `bouncycastle_core`'s `SignaturePublicKey` / `SignaturePrivateKey`, -//! the private key only at a [`RsaSigningSize`], with the byte -//! layouts described on each type below. +//! The keys implement `bouncycastle_core`'s `SignaturePublicKey` / `SignaturePrivateKey`, 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::SignatureError; use bouncycastle_core::security_strength::SecurityStrength; use bouncycastle_core::traits::{SignaturePrivateKey, SignaturePublicKey}; use bouncycastle_utils::secret::{Secret, ZeroizablePrimitive}; use core::fmt; -use core::fmt::{Display, Formatter}; +use core::fmt::{Debug, Display, Formatter}; +use core::marker::PhantomData; -/// An RSA public key: RFC 8017 §3.1's `(n, e)`, at the size `K`. +/// 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 /// -/// `SignaturePublicKey::encode`/`from_bytes` use the raw layout `n || e`: `n` as `K::K_LEN` +/// The keys' `SignaturePublicKey::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. +/// Decoding validates `(n, e)` the same way [`Self::new`] does; the scheme is not encoded. #[derive(Clone, Debug, PartialEq, Eq)] -pub struct RsaPublicKey { +pub struct RsaPublicComponents { n: K::Limbs, e: u32, } -impl RsaPublicKey { +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). @@ -63,6 +72,16 @@ impl RsaPublicKey { 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; @@ -82,42 +101,9 @@ impl RsaPublicKey { } } -impl SignaturePublicKey for RsaPublicKey -where - K: RsaSize, -{ - fn encode(&self) -> [u8; PK_LEN] { - self.encode_raw() - } - - fn encode_out(&self, out: &mut [u8; PK_LEN]) -> usize { - *out = self.encode_raw(); - PK_LEN - } - - fn from_bytes(bytes: &[u8]) -> Result { - let bytes: &[u8; PK_LEN] = bytes.try_into().map_err(|_| { - SignatureError::DecodingError("an RSA public key is the modulus length plus four bytes") - })?; - Self::from_bytes_raw(bytes) - } -} - -/// `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 -/// `SignaturePublicKey`'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: ", K::NAME)?; - for limb in self.n.as_ref().iter().rev() { - write!(f, "{limb:016x}")?; - } - write!(f, ", e: {:x} }}", self.e) - } -} - -/// An RSA private key 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`). +/// 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 @@ -131,13 +117,13 @@ impl Display for RsaPublicKey { /// /// # Encoding /// -/// `SignaturePrivateKey::encode`/`from_bytes`, at a signing size, use the raw layout +/// The keys' `SignaturePrivateKey::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 RsaPrivateKey { +pub struct RsaPrivateComponents { p: Secret, q: Secret, d_p: Secret, @@ -149,7 +135,7 @@ pub struct RsaPrivateKey { // 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 RsaPrivateKey { +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 @@ -200,12 +186,22 @@ impl RsaPrivateKey { } } -impl RsaPrivateKey { +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 } @@ -227,7 +223,7 @@ impl RsaPrivateKey { } } -impl RsaPrivateKey { +impl RsaPrivateComponents { /// The `# Encoding` layout. pub(crate) fn encode_raw(&self) -> K::PrivateKeyEncoded { let half = K::K_LEN / 2; @@ -258,16 +254,185 @@ impl RsaPrivateKey { } } -impl SignaturePrivateKey for RsaPrivateKey +/// 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 SignaturePublicKey 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(|_| { + SignatureError::DecodingError("an RSA public key is the modulus length plus four bytes") + })?; + Ok(Self::from_components(RsaPublicComponents::from_bytes_raw(bytes)?)) + } +} + +/// `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 `SignaturePublicKey`'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 SignaturePrivateKey for RsaPrivateKey where - K: RsaSigningSize + RsaSize, + A: RsaSignatureAlgorithm, + A::Size: RsaSigningSize + RsaSize, { fn encode(&self) -> [u8; SK_LEN] { - self.encode_raw() + self.components.encode_raw() } fn encode_out(&self, out: &mut [u8; SK_LEN]) -> usize { - *out = self.encode_raw(); + *out = self.components.encode_raw(); SK_LEN } @@ -277,7 +442,7 @@ where "an RSA private key is five components of half the modulus length", ) })?; - Self::from_bytes_raw(bytes) + Ok(Self::from_components(RsaPrivateComponents::from_bytes_raw(bytes)?)) } } diff --git a/crypto/rsa/src/lib.rs b/crypto/rsa/src/lib.rs index 391756b6..3fea1ebf 100644 --- a/crypto/rsa/src/lib.rs +++ b/crypto/rsa/src/lib.rs @@ -19,28 +19,34 @@ //! 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) and //! [`RSASSA_PSS_SHAKE`](rsassa_pss_shake::RSASSA_PSS_SHAKE), named by scheme and hash -//! (`RSASSA-PSS-SHA256`) at the lesser of the modulus's and the hash's strength, and the keys -//! are [`RsaPublicKey`](keys::RsaPublicKey) and [`RsaPrivateKey`](keys::RsaPrivateKey). -//! The key role traits of [`bouncycastle_core::signature_key`] are implemented over every -//! pairing: the private key signs through -//! [`SigningKey`](bouncycastle_core::signature_key::SigningKey) for RSASSA-PSS (a fresh salt from -//! the caller's RNG per signer) and +//! (`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 the public key verifies through -//! [`VerifyingKey`](bouncycastle_core::signature_key::VerifyingKey); one-shot or streaming, the -//! same API shape as this workspace's ECDSA, SM2 and ML-DSA crates. One key type serves every -//! scheme and hash, so a call names the algorithm: `SigningKey::, -//! 256>::sign(&sk, &mut rng, msg, None)`. The key types implement +//! 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 //! [`SignaturePrivateKey`](bouncycastle_core::traits::SignaturePrivateKey)/[`SignaturePublicKey`](bouncycastle_core::traits::SignaturePublicKey), -//! and a signing size generates a pair through [`RsaSigningSize::keygen`](size::RsaSigningSize::keygen) -//! or [`size::SignatureKeyPair`] (`RSA2048::generate_signature_key_pair(&mut rng)`, FIPS 186-5 -//! Appendix A.1.3, in [`keygen`]). The `rsassa_*` modules also expose `*_from_hash` entry -//! points that take the message hash rather than the message, for a caller that already holds -//! the digest. +//! 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`, `RSA2048PrivateKey` is -//! `RsaPrivateKey`, `SIG_LEN` is `RSA2048::K_LEN`), for code that works at one size. +//! (`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. @@ -61,87 +67,95 @@ //! //! 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: +//! uses every signature scheme. The key names its scheme, so the calls name nothing: //! //! ``` //! use bouncycastle_core::signature_key::{DeterministicSigningKey, SigningKey, VerifyingKey}; //! use bouncycastle_core::traits::{SignaturePrivateKey, SignaturePublicKey, SignatureSigner, SignatureVerifier}; //! use bouncycastle_rng::HashDRBG_SHA512; -//! use bouncycastle_rsa::rsa_2048::{RSASSA_PKCS1_v1_5_SHA256, RSASSA_PSS_SHA256, RSA2048PrivateKey, RSA2048PublicKey, SIG_LEN}; +//! 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 `bouncycastle_rsa::rsa_2048::keygen(&mut rng)?` instead -- a few seconds of -//! # // Miller-Rabin in a debug build, so this example uses a fixed one. +//! # // 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 = RSA2048PrivateKey::from_crt_components(&P, &Q, &D_P, &D_Q, &Q_INV)?; -//! let pk = RSA2048PublicKey::new(sk.n(), 0x10001)?; +//! 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 = DeterministicSigningKey::::sign_deterministic(&sk, b"the message to sign", None)?; -//! VerifyingKey::::verify(&pk, b"the message to sign", None, &signature)?; +//! 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 = DeterministicSigningKey::::create_signer_deterministic(&sk, None)?; +//! 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 = VerifyingKey::::create_verifier(&pk, None)?; +//! 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!(VerifyingKey::::verify(&pk, b"the message to sign", None, &signature[1..]).is_err()); -//! assert!(VerifyingKey::::verify(&pk, b"a different message", None, &signature).is_err()); -//! -//! // RSASSA-PSS draws its salt from the RNG handed to the signer, so two signatures differ. -//! let sig_a = SigningKey::::sign(&sk, &mut rng, b"the message to sign", None)?; -//! let sig_b = SigningKey::::sign(&sk, &mut rng, b"the message to sign", None)?; +//! 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); -//! VerifyingKey::::verify(&pk, b"the message to sign", None, &sig_a)?; -//! VerifyingKey::::verify(&pk, b"the message to sign", None, &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 = SigningKey::::create_signer(&sk, &mut rng, None)?; +//! 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 = SigningKey::::create_signer(&sk, &mut rng, None)?; +//! 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); -//! VerifyingKey::::verify(&pk, b"the message to sign", None, &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). -//! let pk_again = RSA2048PublicKey::from_bytes(&pk.encode())?; +//! // 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 = RSA2048PrivateKey::from_bytes(&sk.encode())?; +//! 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` for signatures produced +//! 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::VerifyingKey; -//! use bouncycastle_rsa::rsa_1024::{RSASSA_PKCS1_v1_5_SHA256, RSA1024PublicKey, SIG_LEN}; +//! 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 = RSA1024PublicKey::new(&N, 0x10001)?; -//! VerifyingKey::::verify(&pk, &msg, None, &sig)?; +//! let pk = RsaPublicKey::::new(&N, 0x10001)?; +//! pk.verify(&msg, None, &sig)?; //! # Ok::<(), bouncycastle_core::errors::SignatureError>(()) //! ``` //! @@ -359,6 +373,7 @@ pub mod rsa_3072; pub mod rsa_4096; pub mod rsa_8192; mod rsa_core; +pub mod rsassa; pub mod rsassa_pkcs1_v1_5; pub mod rsassa_pss; pub mod rsassa_pss_shake; diff --git a/crypto/rsa/src/rsa_1024.rs b/crypto/rsa/src/rsa_1024.rs index 9a7d2516..8d76162c 100644 --- a/crypto/rsa/src/rsa_1024.rs +++ b/crypto/rsa/src/rsa_1024.rs @@ -2,14 +2,11 @@ //! 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::keys::RsaPublicKey; use crate::rsassa_pkcs1_v1_5::RSASSA_PKCS1_v1_5; pub use crate::size::RSA1024; use crate::size::RsaSize; use bouncycastle_sha2::{SHA256, SHA384}; -/// An RSA-1024 public key. -pub type RSA1024PublicKey = RsaPublicKey; /// 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. diff --git a/crypto/rsa/src/rsa_1536.rs b/crypto/rsa/src/rsa_1536.rs index 41b79fe2..1a09572b 100644 --- a/crypto/rsa/src/rsa_1536.rs +++ b/crypto/rsa/src/rsa_1536.rs @@ -2,14 +2,11 @@ //! 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::keys::RsaPublicKey; 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}; -/// An RSA-1536 public key. -pub type RSA1536PublicKey = RsaPublicKey; /// 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. diff --git a/crypto/rsa/src/rsa_2048.rs b/crypto/rsa/src/rsa_2048.rs index 51b59040..5200506c 100644 --- a/crypto/rsa/src/rsa_2048.rs +++ b/crypto/rsa/src/rsa_2048.rs @@ -1,40 +1,26 @@ //! RSA-2048: the generic types at this size, as aliases over the marker [`RSA2048`]: -//! the key types, `keygen`, every (scheme, hash) pairing offered at this size, and RSASVE. +//! 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::keys::{RsaPrivateKey, RsaPublicKey}; use crate::rsassa_pkcs1_v1_5::RSASSA_PKCS1_v1_5; use crate::rsassa_pss::RSASSA_PSS; use crate::rsassa_pss_shake::RSASSA_PSS_SHAKE; use crate::rsasve::{RsaKEMPrivateKey, RsaKEMPublicKey}; pub use crate::size::RSA2048; -use crate::size::{RsaSigningSize, RsaSize}; -use bouncycastle_core::errors::SignatureError; -use bouncycastle_core::traits::RNG; +use crate::size::RsaSize; use bouncycastle_sha2::{SHA256, SHA384, SHA512}; use bouncycastle_sha3::SHAKE128; -/// An RSA-2048 public key. -pub type RSA2048PublicKey = RsaPublicKey; /// 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; -/// An RSA-2048 private key. -pub type RSA2048PrivateKey = RsaPrivateKey; /// Encoded length of an RSA-2048 private key: `p || q || dP || dQ || qInv`. pub const SK_LEN: usize = RSA2048::SK_LEN; -/// FIPS 186-5 Appendix A.1.3 key generation at RSA-2048: [`RsaSigningSize::keygen`]. -/// -/// # Errors -/// As [`RsaSigningSize::keygen`]. -pub fn keygen(rng: &mut dyn RNG) -> Result<(RSA2048PublicKey, RSA2048PrivateKey), SignatureError> { - RSA2048::keygen(rng) -} - /// 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; diff --git a/crypto/rsa/src/rsa_3072.rs b/crypto/rsa/src/rsa_3072.rs index 2c31476b..9343efb9 100644 --- a/crypto/rsa/src/rsa_3072.rs +++ b/crypto/rsa/src/rsa_3072.rs @@ -1,40 +1,26 @@ //! RSA-3072: the generic types at this size, as aliases over the marker [`RSA3072`]: -//! the key types, `keygen`, every (scheme, hash) pairing offered at this size, and RSASVE. +//! 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::keys::{RsaPrivateKey, RsaPublicKey}; use crate::rsassa_pkcs1_v1_5::RSASSA_PKCS1_v1_5; use crate::rsassa_pss::RSASSA_PSS; use crate::rsassa_pss_shake::RSASSA_PSS_SHAKE; use crate::rsasve::{RsaKEMPrivateKey, RsaKEMPublicKey}; pub use crate::size::RSA3072; -use crate::size::{RsaSigningSize, RsaSize}; -use bouncycastle_core::errors::SignatureError; -use bouncycastle_core::traits::RNG; +use crate::size::RsaSize; use bouncycastle_sha2::{SHA256, SHA384, SHA512}; use bouncycastle_sha3::SHAKE128; -/// An RSA-3072 public key. -pub type RSA3072PublicKey = RsaPublicKey; /// 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; -/// An RSA-3072 private key. -pub type RSA3072PrivateKey = RsaPrivateKey; /// Encoded length of an RSA-3072 private key: `p || q || dP || dQ || qInv`. pub const SK_LEN: usize = RSA3072::SK_LEN; -/// FIPS 186-5 Appendix A.1.3 key generation at RSA-3072: [`RsaSigningSize::keygen`]. -/// -/// # Errors -/// As [`RsaSigningSize::keygen`]. -pub fn keygen(rng: &mut dyn RNG) -> Result<(RSA3072PublicKey, RSA3072PrivateKey), SignatureError> { - RSA3072::keygen(rng) -} - /// 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; diff --git a/crypto/rsa/src/rsa_4096.rs b/crypto/rsa/src/rsa_4096.rs index daa91d76..56338175 100644 --- a/crypto/rsa/src/rsa_4096.rs +++ b/crypto/rsa/src/rsa_4096.rs @@ -1,40 +1,26 @@ //! RSA-4096: the generic types at this size, as aliases over the marker [`RSA4096`]: -//! the key types, `keygen`, every (scheme, hash) pairing offered at this size, and RSASVE. +//! 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::keys::{RsaPrivateKey, RsaPublicKey}; use crate::rsassa_pkcs1_v1_5::RSASSA_PKCS1_v1_5; use crate::rsassa_pss::RSASSA_PSS; use crate::rsassa_pss_shake::RSASSA_PSS_SHAKE; use crate::rsasve::{RsaKEMPrivateKey, RsaKEMPublicKey}; pub use crate::size::RSA4096; -use crate::size::{RsaSigningSize, RsaSize}; -use bouncycastle_core::errors::SignatureError; -use bouncycastle_core::traits::RNG; +use crate::size::RsaSize; use bouncycastle_sha2::{SHA256, SHA384, SHA512}; use bouncycastle_sha3::SHAKE256; -/// An RSA-4096 public key. -pub type RSA4096PublicKey = RsaPublicKey; /// 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; -/// An RSA-4096 private key. -pub type RSA4096PrivateKey = RsaPrivateKey; /// Encoded length of an RSA-4096 private key: `p || q || dP || dQ || qInv`. pub const SK_LEN: usize = RSA4096::SK_LEN; -/// FIPS 186-5 Appendix A.1.3 key generation at RSA-4096: [`RsaSigningSize::keygen`]. -/// -/// # Errors -/// As [`RsaSigningSize::keygen`]. -pub fn keygen(rng: &mut dyn RNG) -> Result<(RSA4096PublicKey, RSA4096PrivateKey), SignatureError> { - RSA4096::keygen(rng) -} - /// 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; diff --git a/crypto/rsa/src/rsa_8192.rs b/crypto/rsa/src/rsa_8192.rs index 2c280771..cced1dc7 100644 --- a/crypto/rsa/src/rsa_8192.rs +++ b/crypto/rsa/src/rsa_8192.rs @@ -1,38 +1,24 @@ //! RSA-8192: the generic types at this size, as aliases over the marker [`RSA8192`]: -//! the key types, `keygen`, every (scheme, hash) pairing offered at this size, and RSASVE. +//! 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::keys::{RsaPrivateKey, RsaPublicKey}; 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::{RsaSigningSize, RsaSize}; -use bouncycastle_core::errors::SignatureError; -use bouncycastle_core::traits::RNG; +use crate::size::RsaSize; use bouncycastle_sha2::{SHA256, SHA384, SHA512}; -/// An RSA-8192 public key. -pub type RSA8192PublicKey = RsaPublicKey; /// 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; -/// An RSA-8192 private key. -pub type RSA8192PrivateKey = RsaPrivateKey; /// Encoded length of an RSA-8192 private key: `p || q || dP || dQ || qInv`. pub const SK_LEN: usize = RSA8192::SK_LEN; -/// FIPS 186-5 Appendix A.1.3 key generation at RSA-8192: [`RsaSigningSize::keygen`]. -/// -/// # Errors -/// As [`RsaSigningSize::keygen`]. -pub fn keygen(rng: &mut dyn RNG) -> Result<(RSA8192PublicKey, RSA8192PrivateKey), SignatureError> { - RSA8192::keygen(rng) -} - /// 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; diff --git a/crypto/rsa/src/rsa_core.rs b/crypto/rsa/src/rsa_core.rs index 0a3437f8..ed98c12d 100644 --- a/crypto/rsa/src/rsa_core.rs +++ b/crypto/rsa/src/rsa_core.rs @@ -7,10 +7,10 @@ //! 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::RsaPrivateKey`] has no representation for +//! `(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::{RsaPrivateKey, RsaPublicKey}; +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; @@ -24,7 +24,7 @@ use bouncycastle_utils::secret::{Secret, zeroize_in_place}; /// 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: &RsaPublicKey, + pk: &RsaPublicComponents, s: &K::Limbs, ) -> Result { // RFC 8017 §5.2.2 step 1: the representative must be in [0, n - 1]. @@ -42,14 +42,14 @@ pub(crate) fn public_exp( x: &[u64; L], ) -> [u64; L] { let ctx = MontgomeryContext::::new(n) - .expect("RsaPublicKey::new already validated n is odd and nonzero"); + .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: &RsaPrivateKey, + sk: &RsaPrivateComponents, m: &K::Limbs, ) -> Result { // RFC 8017 §5.2.1 step 1: the representative must be in [0, n - 1]. @@ -79,17 +79,17 @@ pub(crate) fn crt_exp< ) -> [u64; L] { let mut ctx_p = Secret::>::new(); *ctx_p = MontgomeryContext::::new(p) - .expect("RsaPrivateKey::from_crt_components already validated p is odd and nonzero"); + .expect("RsaPrivateComponents::from_crt_components already validated p is odd and nonzero"); let mut ctx_q = Secret::>::new(); *ctx_q = MontgomeryContext::::new(q) - .expect("RsaPrivateKey::from_crt_components already validated q is odd and nonzero"); + .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 RsaPrivateKey's docs). + // 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); @@ -125,7 +125,7 @@ mod tests { use crate::size::RSA2048; - fn keypair() -> RsaPrivateKey { + fn keypair() -> RsaPrivateComponents { let p: [u64; 16] = [ 0xfec673c1b07d4997, 0x98c9e3737faecc8b, 0x01369d6bebcfd19b, 0x8aadc1799d493a6e, 0x958ca74fe2a455a1, 0x686e62c9e375661d, 0xbf73814b7bf6fe14, 0x791ffe2d364719e4, @@ -156,12 +156,12 @@ mod tests { 0x6ea50741414ce321, 0x7df35889e34d4f38, 0x859106459f51850b, 0xd59e422a92f4a7a2, 0x0c1e16e70fcbe362, 0xcf95cadb6a1f450d, 0x106a4e948e405012, 0x95a3415bfb9b5ff6, ]; - RsaPrivateKey::from_crt_components(&p, &q, &d_p, &d_q, &q_inv) + RsaPrivateComponents::from_crt_components(&p, &q, &d_p, &d_q, &q_inv) .expect("genuine CRT components must be accepted") } - fn public_key(sk: &RsaPrivateKey) -> RsaPublicKey { - RsaPublicKey::new(sk.n(), 0x00010001).expect("e = 65537 is valid") + fn public_key(sk: &RsaPrivateComponents) -> RsaPublicComponents { + RsaPublicComponents::new(sk.n(), 0x00010001).expect("e = 65537 is valid") } #[test] diff --git a/crypto/rsa/src/rsassa.rs b/crypto/rsa/src/rsassa.rs new file mode 100644 index 00000000..25167e4c --- /dev/null +++ b/crypto/rsa/src/rsassa.rs @@ -0,0 +1,347 @@ +//! 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), +//! [`RSASSA_PSS_SHAKE`](crate::rsassa_pss_shake::RSASSA_PSS_SHAKE)) 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::{ + DeterministicSigningKey, SignatureAlgorithm, SigningKey, VerifyingKey, +}; +use bouncycastle_core::traits::{ + AlgorithmInfo, 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, with MGF1 or a native +/// XOF mask. Its keys sign through [`SigningKey`], the salt (one hash output, RFC 8017 §9.1 +/// note 4's "typical" choice) drawn from the RNG when the signer is made. +pub trait RsaRandomizedSignatureAlgorithm: RsaSignatureAlgorithm { + /// EMSA-PSS-ENCODE of the message hash with `salt`. + 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`, one hash output long (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::Hash::OUTPUT_LEN, "the PSS salt is one hash output long") }; + 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> { + let mut salt = [0u8; MAX_HASH_LEN]; + rng.next_bytes_out(&mut salt[..A::Hash::OUTPUT_LEN]).map_err(SignatureError::RNGError)?; + Ok(RsaSigner { sk: self, hash: A::Hash::default(), salt }) + } +} + +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 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 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 do_final(self) -> Result<[u8; K_LEN], SignatureError> { + let h_len = A::Hash::OUTPUT_LEN; + let mut m_hash = [0u8; MAX_HASH_LEN]; + self.hash.do_final_out(&mut m_hash[..h_len]); + sign_from_hash_with_salt::(self.sk, &m_hash[..h_len], &self.salt[..h_len]) + } + + fn do_final_out(self, output: &mut [u8; K_LEN]) -> Result { + output.fill(0); + *output = self.do_final()?; + 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 do_final(self) -> Result<[u8; K_LEN], SignatureError> { + let h_len = A::Hash::OUTPUT_LEN; + let mut m_hash = [0u8; MAX_HASH_LEN]; + self.hash.do_final_out(&mut m_hash[..h_len]); + sign_from_hash_deterministic::(self.sk, &m_hash[..h_len]) + } + + fn do_final_out(self, output: &mut [u8; K_LEN]) -> Result { + output.fill(0); + *output = self.do_final()?; + 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 do_verify_final(self, 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.do_final_out(&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, +{ + let h_len = A::Hash::OUTPUT_LEN; + let mut salt = [0u8; MAX_HASH_LEN]; + rng.next_bytes_out(&mut salt[..h_len]).map_err(SignatureError::RNGError)?; + sign_from_hash_with_salt::(sk, m_hash, &salt[..h_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 {} + impl Sealed for crate::rsassa_pss_shake::RSASSA_PSS_SHAKE {} +} diff --git a/crypto/rsa/src/rsassa_pkcs1_v1_5.rs b/crypto/rsa/src/rsassa_pkcs1_v1_5.rs index 604f38b8..7955509a 100644 --- a/crypto/rsa/src/rsassa_pkcs1_v1_5.rs +++ b/crypto/rsa/src/rsassa_pkcs1_v1_5.rs @@ -1,34 +1,27 @@ -//! RSASSA-PKCS1-v1_5 (RFC 8017 §8.2): sign and verify, built on `rsa_core`'s RSASP1/RSAVP1 and -//! `emsa_pkcs1_v1_5`'s deterministic encoding, once over the modulus size `K` ([`RsaSize`]) -//! and the hash `H`. [`RSASSA_PKCS1_v1_5`] is the algorithm marker the key role traits -//! ([`DeterministicSigningKey`], [`VerifyingKey`]) are implemented over -- one-shot and -//! streaming, with a `&[u8]`-typed signature on the verify side -- on top of -//! [`sign_from_hash`]/[`verify_from_hash`], which take the message hash rather than the message -//! and are the pre-hash entry points for a caller that has already computed it. +//! 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::keys::{RsaPrivateKey, RsaPublicKey}; -use crate::mgf1::MAX_HASH_LEN; -use crate::rsa_core::{rsasp1, rsavp1}; -use crate::size::{RsaSigningSize, RsaSize, min_strength}; -use bouncycastle_core::errors::SignatureError; +use crate::rsassa::{RsaDeterministicSignatureAlgorithm, RsaSignatureAlgorithm}; +use crate::size::{RsaSize, min_strength}; use bouncycastle_core::security_strength::SecurityStrength; -use bouncycastle_core::signature_key::{DeterministicSigningKey, SignatureAlgorithm, VerifyingKey}; -use bouncycastle_core::traits::{ - Algorithm, AlgorithmInfo, AlgorithmOID, HashAlgParams, HashOneShot, SignatureSigner, - SignatureVerifier, -}; +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`] signs through [`DeterministicSigningKey`] at a signing size: PKCS#1 v1.5 +/// [`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`] verifies through [`VerifyingKey`] at any size. One key type serves every +/// [`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: -/// `DeterministicSigningKey::::sign_deterministic(&sk, ..)`. +/// 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 { @@ -47,168 +40,21 @@ impl Algorithm for RSASSA_PKCS1_v1_5 { impl SignatureAlgorithm for RSASSA_PKCS1_v1_5 {} -/// The signer [`DeterministicSigningKey::create_signer_deterministic`] hands out: the key, -/// borrowed, and the running hash. -pub struct RsaPkcs1v15Signer<'k, K: RsaSize, H> { - sk: &'k RsaPrivateKey, - hash: H, -} - -/// The verifier [`VerifyingKey::create_verifier`] hands out: the key, borrowed, and the running -/// hash. -pub struct RsaPkcs1v15Verifier<'k, K: RsaSize, H> { - pk: &'k RsaPublicKey, - hash: H, -} - -impl DeterministicSigningKey, K_LEN> - for RsaPrivateKey -where - // 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. - K: RsaSigningSize + RsaSize, - H: HashOneShot + HashAlgParams + AlgorithmOID, +impl RsaSignatureAlgorithm + for RSASSA_PKCS1_v1_5 { - type Signer<'k> - = RsaPkcs1v15Signer<'k, K, H> - where - Self: 'k; + type Size = K; + type Hash = H; - fn create_signer_deterministic<'k>( - &'k self, - _ctx: Option<&[u8]>, - ) -> Result, SignatureError> { - Ok(RsaPkcs1v15Signer { sk: self, hash: H::default() }) + fn emsa_verify(m_hash: &[u8], em: &[u8; K_LEN]) -> bool { + emsa_pkcs1_v1_5_verify_from_hash::(m_hash, em) } } -impl VerifyingKey, K_LEN> for RsaPublicKey -where - K: RsaSize, - H: HashOneShot + HashAlgParams + AlgorithmOID, +impl RsaDeterministicSignatureAlgorithm + for RSASSA_PKCS1_v1_5 { - type Verifier<'k> - = RsaPkcs1v15Verifier<'k, K, H> - where - Self: 'k; - - fn create_verifier<'k>( - &'k self, - _ctx: Option<&[u8]>, - ) -> Result, SignatureError> { - Ok(RsaPkcs1v15Verifier { pk: self, hash: H::default() }) - } -} - -impl AlgorithmInfo for RsaPkcs1v15Signer<'_, K, H> { - fn alg_name(&self) -> &'static str { - RSASSA_PKCS1_v1_5::::ALG_NAME - } - - fn max_security_strength(&self) -> SecurityStrength { - RSASSA_PKCS1_v1_5::::MAX_SECURITY_STRENGTH - } -} - -impl SignatureSigner for RsaPkcs1v15Signer<'_, K, H> -where - K: RsaSigningSize + RsaSize, - H: HashOneShot + HashAlgParams + AlgorithmOID, -{ - fn do_update(&mut self, msg_chunk: &[u8]) { - self.hash.do_update(msg_chunk); - } - - fn do_final(self) -> Result<[u8; K_LEN], SignatureError> { - let mut m_hash = [0u8; MAX_HASH_LEN]; - self.hash.do_final_out(&mut m_hash[..H::OUTPUT_LEN]); - sign_from_hash::(self.sk, &m_hash[..H::OUTPUT_LEN]) - } - - fn do_final_out(self, output: &mut [u8; K_LEN]) -> Result { - output.fill(0); - *output = self.do_final()?; - Ok(K_LEN) - } -} - -impl AlgorithmInfo for RsaPkcs1v15Verifier<'_, K, H> { - fn alg_name(&self) -> &'static str { - RSASSA_PKCS1_v1_5::::ALG_NAME - } - - fn max_security_strength(&self) -> SecurityStrength { - RSASSA_PKCS1_v1_5::::MAX_SECURITY_STRENGTH - } -} - -impl SignatureVerifier for RsaPkcs1v15Verifier<'_, K, H> -where - K: RsaSize, - H: HashOneShot + HashAlgParams + AlgorithmOID, -{ - fn do_update(&mut self, msg_chunk: &[u8]) { - self.hash.do_update(msg_chunk); - } - - fn do_verify_final(self, sig: &[u8]) -> Result<(), SignatureError> { - // RFC 8017 §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 mut m_hash = [0u8; MAX_HASH_LEN]; - self.hash.do_final_out(&mut m_hash[..H::OUTPUT_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::OUTPUT_LEN], sig) - .map_err(|_| SignatureError::SignatureVerificationFailed) - } -} - -/// RSASSA-PKCS1-V1_5-SIGN (RFC 8017 §8.2.1) from the message hash (`H::OUTPUT_LEN` bytes): the -/// EMSA-PKCS1-v1_5 encoding of `digest`, then RSASP1. -/// -/// # Errors -/// [`SignatureError::DecodingError`] if the encoded message is not below `n`, which no modulus -/// with its top bit set allows. -pub fn sign_from_hash( - sk: &RsaPrivateKey, - digest: &[u8], -) -> Result<[u8; K_LEN], SignatureError> -where - K: RsaSigningSize + RsaSize, - H: HashAlgParams + AlgorithmOID, -{ - let em = emsa_pkcs1_v1_5_encode_from_hash::(digest); - let m = K::limbs_from_be_bytes(&em); - let s = rsasp1::(sk, &m)?; - Ok(K::be_bytes_from_limbs(&s)) -} - -/// RSASSA-PKCS1-V1_5-VERIFY (RFC 8017 §8.2.2) from the message hash: RSAVP1, then the EMSA -/// decoding compared against `digest`. -/// -/// # Errors -/// [`SignatureError::DecodingError`] for a signature representative not below `n` (step 2.b's -/// "invalid signature" from RSAVP1), [`SignatureError::SignatureVerificationFailed`] for an -/// encoding that does not match. -pub fn verify_from_hash( - pk: &RsaPublicKey, - digest: &[u8], - signature: &[u8; K_LEN], -) -> Result<(), SignatureError> -where - K: RsaSize, - H: AlgorithmOID, -{ - let s = K::limbs_from_be_bytes(signature); - let m = rsavp1::(pk, &s)?; - let em_prime = K::be_bytes_from_limbs(&m); - - if emsa_pkcs1_v1_5_verify_from_hash::(digest, &em_prime) { - Ok(()) - } else { - Err(SignatureError::SignatureVerificationFailed) + 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 index 533af1e1..50d559ba 100644 --- a/crypto/rsa/src/rsassa_pss.rs +++ b/crypto/rsa/src/rsassa_pss.rs @@ -1,32 +1,27 @@ -//! RSASSA-PSS (RFC 8017 §8.1): sign and verify, built on `rsa_core`'s RSASP1/RSAVP1 and -//! `emsa_pss`'s probabilistic encoding, once over the modulus size `K` ([`RsaSize`]) and the -//! hash `H` (also MGF1's hash). [`RSASSA_PSS`] is the algorithm marker the key role -//! traits are implemented over, on top of the `*_from_hash` functions, which take the message -//! hash rather than the message; the salt, one hash output long (RFC 8017 §9.1 note 4's -//! "typical" choice), comes from the RNG handed to [`SigningKey::create_signer`], and -//! [`RsaPssSigner::set_salt`] replaces it for a known answer. +//! RSASSA-PSS (RFC 8017 §8.1) over the modulus size `K` ([`RsaSize`]) and the hash `H` (also +//! MGF1's hash): [`RSASSA_PSS`] is the algorithm marker a key names, named +//! `RSASSA-PSS-` at the lesser of the size's and the hash's strength, and its +//! [`RsaRandomizedSignatureAlgorithm`] impl is `emsa_pss`'s probabilistic encoding, the salt one +//! hash output long (RFC 8017 §9.1 note 4's "typical" choice); the keys, the workers (with +//! `set_salt` for a known answer) and the `*_from_hash` entry points are [`crate::rsassa`]'s, +//! once over every algorithm. use crate::emsa_pss::{emsa_pss_encode_from_hash, emsa_pss_verify_from_hash}; -use crate::keys::{RsaPrivateKey, RsaPublicKey}; -use crate::mgf1::MAX_HASH_LEN; -use crate::rsa_core::{rsasp1, rsavp1}; -use crate::size::{RsaSigningSize, RsaSize, min_strength}; -use bouncycastle_core::errors::SignatureError; +use crate::rsassa::{RsaRandomizedSignatureAlgorithm, RsaSignatureAlgorithm}; +use crate::size::{RsaSize, min_strength}; use bouncycastle_core::security_strength::SecurityStrength; -use bouncycastle_core::signature_key::{SignatureAlgorithm, SigningKey, VerifyingKey}; -use bouncycastle_core::traits::{ - Algorithm, AlgorithmInfo, HashAlgParams, HashOneShot, RNG, SignatureSigner, SignatureVerifier, -}; +use bouncycastle_core::signature_key::SignatureAlgorithm; +use bouncycastle_core::traits::{Algorithm, HashAlgParams, HashOneShot}; use bouncycastle_utils::const_str::ConstStr; use core::marker::PhantomData; /// RSASSA-PSS (RFC 8017 §8.1) over the hash `H`, with MGF1 over `H`, at the modulus size `K`: the algorithm marker the key role traits are implemented /// over, named `RSASSA-PSS-` (`RSASSA-PSS-SHA256`), at the lesser of the size's and the hash's -/// strength. [`RsaPrivateKey`] signs through [`SigningKey`] at a signing size: a fresh salt, one +/// strength. [`RsaPrivateKey`](crate::keys::RsaPrivateKey) signs through [`SigningKey`](bouncycastle_core::signature_key::SigningKey) at a signing size: a fresh salt, one /// hash output long, from the caller's RNG per signer (EMSA-PSS-ENCODE step 4), so two -/// signatures of one message differ. [`RsaPublicKey`] verifies through [`VerifyingKey`] at any +/// signatures of one message differ. [`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: -/// `SigningKey::::sign(&sk, ..)`. `ctx` is accepted and +/// a key over it signs through `SigningKey`, `sk.sign(&mut rng, msg, None)`. `ctx` is accepted and /// ignored, since RSA has no context string. #[allow(non_camel_case_types)] pub struct RSASSA_PSS { @@ -45,204 +40,19 @@ impl Algorithm for RSASSA_PSS { impl SignatureAlgorithm for RSASSA_PSS {} -/// The signer [`SigningKey::create_signer`] hands out: the key, borrowed, the running hash and -/// the salt (the first `H::OUTPUT_LEN` bytes of the buffer). -pub struct RsaPssSigner<'k, K: RsaSize, H> { - sk: &'k RsaPrivateKey, - hash: H, - salt: [u8; MAX_HASH_LEN], -} - -impl RsaPssSigner<'_, K, H> { - /// Replaces the salt drawn when the signer was created, for a known-answer test; `N` must be - /// the hash's output length, which is checked when the call is compiled. - pub fn set_salt(&mut self, salt: [u8; N]) { - const { assert!(N == H::OUTPUT_LEN, "the PSS salt is one hash output long") }; - self.salt[..N].copy_from_slice(&salt); - } -} - -/// The verifier [`VerifyingKey::create_verifier`] hands out: the key, borrowed, and the running -/// hash. -pub struct RsaPssVerifier<'k, K: RsaSize, H> { - pk: &'k RsaPublicKey, - hash: H, -} - -impl SigningKey, K_LEN> for RsaPrivateKey -where - // 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. - K: RsaSigningSize + RsaSize, - H: HashOneShot + HashAlgParams, -{ - type Signer<'k> - = RsaPssSigner<'k, K, H> - where - Self: 'k; - - fn create_signer<'k>( - &'k self, - rng: &mut dyn RNG, - _ctx: Option<&[u8]>, - ) -> Result, SignatureError> { - // EMSA-PSS-ENCODE step 4's salt, drawn when the signer is created, as ECDSA draws `k`. - let mut salt = [0u8; MAX_HASH_LEN]; - rng.next_bytes_out(&mut salt[..H::OUTPUT_LEN]).map_err(SignatureError::RNGError)?; - Ok(RsaPssSigner { sk: self, hash: H::default(), salt }) - } -} +impl RsaSignatureAlgorithm for RSASSA_PSS { + type Size = K; + type Hash = H; -impl VerifyingKey, K_LEN> for RsaPublicKey -where - K: RsaSize, - H: HashOneShot + HashAlgParams, -{ - type Verifier<'k> - = RsaPssVerifier<'k, K, H> - where - Self: 'k; - - fn create_verifier<'k>( - &'k self, - _ctx: Option<&[u8]>, - ) -> Result, SignatureError> { - Ok(RsaPssVerifier { pk: self, hash: H::default() }) - } -} - -impl AlgorithmInfo for RsaPssSigner<'_, K, H> { - fn alg_name(&self) -> &'static str { - RSASSA_PSS::::ALG_NAME - } - - fn max_security_strength(&self) -> SecurityStrength { - RSASSA_PSS::::MAX_SECURITY_STRENGTH - } -} - -impl SignatureSigner for RsaPssSigner<'_, K, H> -where - K: RsaSigningSize + RsaSize, - H: HashOneShot + HashAlgParams, -{ - fn do_update(&mut self, msg_chunk: &[u8]) { - self.hash.do_update(msg_chunk); + fn emsa_verify(m_hash: &[u8], em: &[u8; K_LEN]) -> bool { + emsa_pss_verify_from_hash::(m_hash, em) } - - fn do_final(self) -> Result<[u8; K_LEN], SignatureError> { - let mut m_hash = [0u8; MAX_HASH_LEN]; - self.hash.do_final_out(&mut m_hash[..H::OUTPUT_LEN]); - sign_from_hash_with_salt::( - self.sk, - &m_hash[..H::OUTPUT_LEN], - &self.salt[..H::OUTPUT_LEN], - ) - } - - fn do_final_out(self, output: &mut [u8; K_LEN]) -> Result { - output.fill(0); - *output = self.do_final()?; - Ok(K_LEN) - } -} - -impl AlgorithmInfo for RsaPssVerifier<'_, K, H> { - fn alg_name(&self) -> &'static str { - RSASSA_PSS::::ALG_NAME - } - - fn max_security_strength(&self) -> SecurityStrength { - RSASSA_PSS::::MAX_SECURITY_STRENGTH - } -} - -impl SignatureVerifier for RsaPssVerifier<'_, K, H> -where - K: RsaSize, - H: HashOneShot + HashAlgParams, -{ - fn do_update(&mut self, msg_chunk: &[u8]) { - self.hash.do_update(msg_chunk); - } - - fn do_verify_final(self, sig: &[u8]) -> Result<(), SignatureError> { - // RFC 8017 §8.1.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 mut m_hash = [0u8; MAX_HASH_LEN]; - self.hash.do_final_out(&mut m_hash[..H::OUTPUT_LEN]); - verify_from_hash::(self.pk, &m_hash[..H::OUTPUT_LEN], sig) - .map_err(|_| SignatureError::SignatureVerificationFailed) - } -} - -/// RSASSA-PSS-SIGN (RFC 8017 §8.1.1) from the message hash (`H::OUTPUT_LEN` bytes) with the -/// salt given (the same length): the EMSA-PSS encoding, then RSASP1. The known-answer entry -/// point; [`sign_from_hash`] draws the salt. -/// -/// # Errors -/// [`SignatureError::DecodingError`] if the encoded message is not below `n`, which the -/// encoding's cleared top bit rules out. -pub fn sign_from_hash_with_salt( - sk: &RsaPrivateKey, - m_hash: &[u8], - salt: &[u8], -) -> Result<[u8; K_LEN], SignatureError> -where - K: RsaSigningSize + RsaSize, - H: HashOneShot + HashAlgParams, -{ - let em = emsa_pss_encode_from_hash::(m_hash, salt); - let m = K::limbs_from_be_bytes(&em); - let s = rsasp1::(sk, &m)?; - Ok(K::be_bytes_from_limbs(&s)) -} - -/// RSASSA-PSS-SIGN (RFC 8017 §8.1.1) from the message hash, with a fresh salt of one hash -/// output drawn from `rng` (EMSA-PSS-ENCODE step 4). -/// -/// # Errors -/// [`SignatureError::RNGError`] if the RNG fails to deliver; otherwise 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 - K: RsaSigningSize + RsaSize, - H: HashOneShot + HashAlgParams, -{ - let mut salt = [0u8; MAX_HASH_LEN]; - rng.next_bytes_out(&mut salt[..H::OUTPUT_LEN]).map_err(SignatureError::RNGError)?; - sign_from_hash_with_salt::(sk, m_hash, &salt[..H::OUTPUT_LEN]) } -/// RSASSA-PSS-VERIFY (RFC 8017 §8.1.2) from the message hash: RSAVP1, then the EMSA-PSS -/// verification against `m_hash`. -/// -/// # Errors -/// [`SignatureError::DecodingError`] for a signature representative not below `n` (step 2.b's -/// "invalid signature" from RSAVP1), [`SignatureError::SignatureVerificationFailed`] for an -/// encoding that does not verify. -pub fn verify_from_hash( - pk: &RsaPublicKey, - m_hash: &[u8], - signature: &[u8; K_LEN], -) -> Result<(), SignatureError> -where - K: RsaSize, - H: HashOneShot + HashAlgParams, +impl RsaRandomizedSignatureAlgorithm + for RSASSA_PSS { - let s = K::limbs_from_be_bytes(signature); - let m = rsavp1::(pk, &s)?; - let em = K::be_bytes_from_limbs(&m); - if emsa_pss_verify_from_hash::(m_hash, &em) { - Ok(()) - } else { - Err(SignatureError::SignatureVerificationFailed) + fn emsa_encode(m_hash: &[u8], salt: &[u8]) -> [u8; K_LEN] { + emsa_pss_encode_from_hash::(m_hash, salt) } } diff --git a/crypto/rsa/src/rsassa_pss_shake.rs b/crypto/rsa/src/rsassa_pss_shake.rs index 4ad8432c..84ee4c15 100644 --- a/crypto/rsa/src/rsassa_pss_shake.rs +++ b/crypto/rsa/src/rsassa_pss_shake.rs @@ -1,32 +1,27 @@ //! RSASSA-PSS with SHAKE128 or SHAKE256 as both the hash and the (native, non-MGF1) mask -//! generation function -- `id-RSASSA-PSS-SHAKE128`/`id-RSASSA-PSS-SHAKE256` (RFC 8702 §3.2.1). -//! Otherwise identical to [`crate::rsassa_pss`] (RFC 8017 §8.1): same RSASP1/RSAVP1 -//! orchestration, same fresh-salt-per-signature approach, just built on `emsa_pss_shake` in -//! place of `emsa_pss` -- and the same [`RSASSA_PSS_SHAKE`] marker over `*_from_hash` -//! functions, with `X: XOF` in place of `H: Hash`. +//! generation function, `id-RSASSA-PSS-SHAKE128` / `id-RSASSA-PSS-SHAKE256` (RFC 8702 §3.2.1), +//! over the modulus size `K` ([`RsaSize`]) and the XOF `X`: [`RSASSA_PSS_SHAKE`] is the +//! algorithm marker a key names, named `RSASSA-PSS-`, and its +//! [`RsaRandomizedSignatureAlgorithm`] impl is `emsa_pss_shake`'s encoding in place of +//! [`crate::rsassa_pss`]'s; the keys, the workers and the `*_from_hash` entry points are +//! [`crate::rsassa`]'s, once over every algorithm. use crate::emsa_pss_shake::{emsa_pss_encode_shake_from_hash, emsa_pss_verify_shake_from_hash}; -use crate::keys::{RsaPrivateKey, RsaPublicKey}; -use crate::mgf1::MAX_HASH_LEN; -use crate::rsa_core::{rsasp1, rsavp1}; -use crate::size::{RsaSigningSize, RsaSize, min_strength}; -use bouncycastle_core::errors::SignatureError; +use crate::rsassa::{RsaRandomizedSignatureAlgorithm, RsaSignatureAlgorithm}; +use crate::size::{RsaSize, min_strength}; use bouncycastle_core::security_strength::SecurityStrength; -use bouncycastle_core::signature_key::{SignatureAlgorithm, SigningKey, VerifyingKey}; -use bouncycastle_core::traits::{ - Algorithm, AlgorithmInfo, HashAlgParams, HashOneShot, RNG, SignatureSigner, SignatureVerifier, - XOF, -}; +use bouncycastle_core::signature_key::SignatureAlgorithm; +use bouncycastle_core::traits::{Algorithm, HashAlgParams, HashOneShot, XOF}; use bouncycastle_utils::const_str::ConstStr; use core::marker::PhantomData; /// RSASSA-PSS with a SHAKE XOF `X` as both hash and mask (RFC 8702 §3.2.1), at the modulus size `K`: the algorithm marker the key role traits are implemented /// over, named `RSASSA-PSS-` (`RSASSA-PSS-SHAKE128`), at the lesser of the size's and the hash's -/// strength. [`RsaPrivateKey`] signs through [`SigningKey`] at a signing size: a fresh salt, one +/// strength. [`RsaPrivateKey`](crate::keys::RsaPrivateKey) signs through [`SigningKey`](bouncycastle_core::signature_key::SigningKey) at a signing size: a fresh salt, one /// hash output long, from the caller's RNG per signer (EMSA-PSS-ENCODE step 4), so two -/// signatures of one message differ. [`RsaPublicKey`] verifies through [`VerifyingKey`] at any +/// signatures of one message differ. [`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: -/// `SigningKey::::sign(&sk, ..)`. `ctx` is accepted and +/// a key over it signs through `SigningKey`, `sk.sign(&mut rng, msg, None)`. `ctx` is accepted and /// ignored, since RSA has no context string. #[allow(non_camel_case_types)] pub struct RSASSA_PSS_SHAKE { @@ -45,204 +40,21 @@ impl Algorithm for RSASSA_PSS_SHAKE { impl SignatureAlgorithm for RSASSA_PSS_SHAKE {} -/// The signer [`SigningKey::create_signer`] hands out: the key, borrowed, the running hash and -/// the salt (the first `X::OUTPUT_LEN` bytes of the buffer). -pub struct RsaPssShakeSigner<'k, K: RsaSize, X> { - sk: &'k RsaPrivateKey, - hash: X, - salt: [u8; MAX_HASH_LEN], -} - -impl RsaPssShakeSigner<'_, K, X> { - /// Replaces the salt drawn when the signer was created, for a known-answer test; `N` must be - /// the hash's output length, which is checked when the call is compiled. - pub fn set_salt(&mut self, salt: [u8; N]) { - const { assert!(N == X::OUTPUT_LEN, "the PSS salt is one hash output long") }; - self.salt[..N].copy_from_slice(&salt); - } -} - -/// The verifier [`VerifyingKey::create_verifier`] hands out: the key, borrowed, and the running -/// hash. -pub struct RsaPssShakeVerifier<'k, K: RsaSize, X> { - pk: &'k RsaPublicKey, - hash: X, -} - -impl SigningKey, K_LEN> for RsaPrivateKey -where - // 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. - K: RsaSigningSize + RsaSize, - X: XOF + HashOneShot + HashAlgParams, -{ - type Signer<'k> - = RsaPssShakeSigner<'k, K, X> - where - Self: 'k; - - fn create_signer<'k>( - &'k self, - rng: &mut dyn RNG, - _ctx: Option<&[u8]>, - ) -> Result, SignatureError> { - // EMSA-PSS-ENCODE step 4's salt, drawn when the signer is created, as ECDSA draws `k`. - let mut salt = [0u8; MAX_HASH_LEN]; - rng.next_bytes_out(&mut salt[..X::OUTPUT_LEN]).map_err(SignatureError::RNGError)?; - Ok(RsaPssShakeSigner { sk: self, hash: X::default(), salt }) - } -} - -impl VerifyingKey, K_LEN> for RsaPublicKey -where - K: RsaSize, - X: XOF + HashOneShot + HashAlgParams, -{ - type Verifier<'k> - = RsaPssShakeVerifier<'k, K, X> - where - Self: 'k; - - fn create_verifier<'k>( - &'k self, - _ctx: Option<&[u8]>, - ) -> Result, SignatureError> { - Ok(RsaPssShakeVerifier { pk: self, hash: X::default() }) - } -} - -impl AlgorithmInfo for RsaPssShakeSigner<'_, K, X> { - fn alg_name(&self) -> &'static str { - RSASSA_PSS_SHAKE::::ALG_NAME - } - - fn max_security_strength(&self) -> SecurityStrength { - RSASSA_PSS_SHAKE::::MAX_SECURITY_STRENGTH - } -} - -impl SignatureSigner for RsaPssShakeSigner<'_, K, X> -where - K: RsaSigningSize + RsaSize, - X: XOF + HashOneShot + HashAlgParams, +impl RsaSignatureAlgorithm + for RSASSA_PSS_SHAKE { - fn do_update(&mut self, msg_chunk: &[u8]) { - self.hash.do_update(msg_chunk); - } - - fn do_final(self) -> Result<[u8; K_LEN], SignatureError> { - let mut m_hash = [0u8; MAX_HASH_LEN]; - self.hash.do_final_out(&mut m_hash[..X::OUTPUT_LEN]); - sign_from_hash_with_salt::( - self.sk, - &m_hash[..X::OUTPUT_LEN], - &self.salt[..X::OUTPUT_LEN], - ) - } + type Size = K; + type Hash = X; - fn do_final_out(self, output: &mut [u8; K_LEN]) -> Result { - output.fill(0); - *output = self.do_final()?; - Ok(K_LEN) + fn emsa_verify(m_hash: &[u8], em: &[u8; K_LEN]) -> bool { + emsa_pss_verify_shake_from_hash::(m_hash, em) } } -impl AlgorithmInfo for RsaPssShakeVerifier<'_, K, X> { - fn alg_name(&self) -> &'static str { - RSASSA_PSS_SHAKE::::ALG_NAME - } - - fn max_security_strength(&self) -> SecurityStrength { - RSASSA_PSS_SHAKE::::MAX_SECURITY_STRENGTH - } -} - -impl SignatureVerifier for RsaPssShakeVerifier<'_, K, X> -where - K: RsaSize, - X: XOF + HashOneShot + HashAlgParams, -{ - fn do_update(&mut self, msg_chunk: &[u8]) { - self.hash.do_update(msg_chunk); - } - - fn do_verify_final(self, sig: &[u8]) -> Result<(), SignatureError> { - // RFC 8017 §8.1.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 mut m_hash = [0u8; MAX_HASH_LEN]; - self.hash.do_final_out(&mut m_hash[..X::OUTPUT_LEN]); - verify_from_hash::(self.pk, &m_hash[..X::OUTPUT_LEN], sig) - .map_err(|_| SignatureError::SignatureVerificationFailed) - } -} - -/// RSASSA-PSS-SIGN (RFC 8017 §8.1.1) from the message hash (`X::OUTPUT_LEN` bytes) with the -/// salt given (the same length): the EMSA-PSS encoding, then RSASP1. The known-answer entry -/// point; [`sign_from_hash`] draws the salt. -/// -/// # Errors -/// [`SignatureError::DecodingError`] if the encoded message is not below `n`, which the -/// encoding's cleared top bit rules out. -pub fn sign_from_hash_with_salt( - sk: &RsaPrivateKey, - m_hash: &[u8], - salt: &[u8], -) -> Result<[u8; K_LEN], SignatureError> -where - K: RsaSigningSize + RsaSize, - X: XOF + HashOneShot + HashAlgParams, -{ - let em = emsa_pss_encode_shake_from_hash::(m_hash, salt); - let m = K::limbs_from_be_bytes(&em); - let s = rsasp1::(sk, &m)?; - Ok(K::be_bytes_from_limbs(&s)) -} - -/// RSASSA-PSS-SIGN (RFC 8017 §8.1.1) from the message hash, with a fresh salt of one hash -/// output drawn from `rng` (EMSA-PSS-ENCODE step 4). -/// -/// # Errors -/// [`SignatureError::RNGError`] if the RNG fails to deliver; otherwise 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 - K: RsaSigningSize + RsaSize, - X: XOF + HashOneShot + HashAlgParams, -{ - let mut salt = [0u8; MAX_HASH_LEN]; - rng.next_bytes_out(&mut salt[..X::OUTPUT_LEN]).map_err(SignatureError::RNGError)?; - sign_from_hash_with_salt::(sk, m_hash, &salt[..X::OUTPUT_LEN]) -} - -/// RSASSA-PSS-VERIFY (RFC 8017 §8.1.2) from the message hash: RSAVP1, then the EMSA-PSS -/// verification against `m_hash`. -/// -/// # Errors -/// [`SignatureError::DecodingError`] for a signature representative not below `n` (step 2.b's -/// "invalid signature" from RSAVP1), [`SignatureError::SignatureVerificationFailed`] for an -/// encoding that does not verify. -pub fn verify_from_hash( - pk: &RsaPublicKey, - m_hash: &[u8], - signature: &[u8; K_LEN], -) -> Result<(), SignatureError> -where - K: RsaSize, - X: XOF + HashOneShot + HashAlgParams, +impl RsaRandomizedSignatureAlgorithm + for RSASSA_PSS_SHAKE { - let s = K::limbs_from_be_bytes(signature); - let m = rsavp1::(pk, &s)?; - let em = K::be_bytes_from_limbs(&m); - if emsa_pss_verify_shake_from_hash::(m_hash, &em) { - Ok(()) - } else { - Err(SignatureError::SignatureVerificationFailed) + fn emsa_encode(m_hash: &[u8], salt: &[u8]) -> [u8; K_LEN] { + emsa_pss_encode_shake_from_hash::(m_hash, salt) } } diff --git a/crypto/rsa/src/rsasve.rs b/crypto/rsa/src/rsasve.rs index fdd71f2f..616d458e 100644 --- a/crypto/rsa/src/rsasve.rs +++ b/crypto/rsa/src/rsasve.rs @@ -15,10 +15,10 @@ //! //! # Key separation //! -//! The key types here wrap the signature schemes' [`RsaPublicKey`]/[`RsaPrivateKey`] rather than +//! 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 -//! [`RsaPrivateKey`]. SP 800-56B Rev. 2 §6.1 item 5 is the requirement: "One key pair shall not +//! [`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 @@ -26,7 +26,7 @@ //! //! # Key validation //! -//! On top of what [`RsaPublicKey::new`]/[`RsaPrivateKey::from_crt_components`] already check, +//! 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, @@ -40,11 +40,11 @@ //! 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 [`RsaPublicKey::new`] checks). Nothing here +//! 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::{RsaPrivateKey, RsaPublicKey}; +use crate::keys::{RsaPrivateComponents, RsaPublicComponents}; use crate::size::{RsaSigningSize, RsaSize}; use bouncycastle_core::errors::{KEMError, RNGError, SignatureError}; use bouncycastle_core::hazmat::do_hazardous_operations; @@ -93,20 +93,20 @@ fn in_open_range(x: &K::Limbs, n: &K::Limbs) -> bool { K::is_less(x, &n_minus_1) && K::is_less(&one, x) } -/// An RSA key-establishment public key at the size `K`: [`RsaPublicKey`] under the KEM roles +/// 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) RsaPublicKey); +pub struct RsaKEMPublicKey(pub(crate) RsaPublicComponents); impl RsaKEMPublicKey { /// Builds a public key from its modulus and exponent. Returns - /// `Err(`[`KEMError::DecodingError`]`)` in the cases [`RsaPublicKey::new`] rejects, and also + /// `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(RsaPublicKey::new(n, e).map_err(kem_error)?) + Self::from_rsa_key(RsaPublicComponents::new(n, e).map_err(kem_error)?) } - pub(crate) fn from_rsa_key(pk: RsaPublicKey) -> Result { + 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", @@ -129,20 +129,26 @@ impl RsaKEMPublicKey { } } +/// `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 { - self.0.fmt(f) + 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`: [`RsaPrivateKey`] under the KEM roles +/// 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) RsaPrivateKey); +pub struct RsaKEMPrivateKey(pub(crate) RsaPrivateComponents); impl RsaKEMPrivateKey { /// Builds a private key from its CRT components. Returns - /// `Err(`[`KEMError::DecodingError`]`)` in the cases [`RsaPrivateKey::from_crt_components`] + /// `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( @@ -153,11 +159,11 @@ impl RsaKEMPrivateKey { q_inv: &K::HalfLimbs, ) -> Result { Self::from_rsa_key( - RsaPrivateKey::from_crt_components(p, q, d_p, d_q, q_inv).map_err(kem_error)?, + RsaPrivateComponents::from_crt_components(p, q, d_p, d_q, q_inv).map_err(kem_error)?, ) } - pub(crate) fn from_rsa_key(sk: RsaPrivateKey) -> Result { + 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")); } @@ -353,7 +359,7 @@ where "an RSA private key is five components of half the modulus length", ) })?; - Self::from_rsa_key(RsaPrivateKey::from_bytes_raw(bytes).map_err(kem_error)?) + Self::from_rsa_key(RsaPrivateComponents::from_bytes_raw(bytes).map_err(kem_error)?) } } @@ -374,14 +380,14 @@ where let bytes: &[u8; PK_LEN] = bytes.try_into().map_err(|_| { KEMError::DecodingError("an RSA public key is the modulus length plus four bytes") })?; - Self::from_rsa_key(RsaPublicKey::from_bytes_raw(bytes).map_err(kem_error)?) + Self::from_rsa_key(RsaPublicComponents::from_bytes_raw(bytes).map_err(kem_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<(RsaPublicKey, RsaPrivateKey), SignatureError>, + 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/size.rs b/crypto/rsa/src/size.rs index 5f13d13c..577923a3 100644 --- a/crypto/rsa/src/size.rs +++ b/crypto/rsa/src/size.rs @@ -10,12 +10,17 @@ use crate::codec::{be_bytes_from_limbs, limbs_from_be_bytes}; use crate::keygen::keygen_from_rng; -use crate::keys::{RsaPrivateKey, RsaPublicKey, modulus_strength}; +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::RSASSA_PSS; +use crate::rsassa_pss_shake::RSASSA_PSS_SHAKE; use crate::rsasve::{RsaKEMPrivateKey, RsaKEMPublicKey}; use bouncycastle_core::errors::{KEMError, SignatureError}; use bouncycastle_core::security_strength::SecurityStrength; -use bouncycastle_core::traits::RNG; +use bouncycastle_core::traits::{AlgorithmOID, HashAlgParams, HashOneShot, RNG, XOF}; use bouncycastle_ec::montgomery; use bouncycastle_ec::nat; use bouncycastle_utils::secret::{NoPadding, ZeroizablePrimitive}; @@ -96,7 +101,7 @@ pub trait RsaSigningSize: RsaSize { /// if no prime was found within the candidate budget. fn keygen( rng: &mut dyn RNG, - ) -> Result<(RsaPublicKey, RsaPrivateKey), SignatureError>; + ) -> Result<(RsaPublicComponents, RsaPrivateComponents), SignatureError>; // The private key's arithmetic: only a signing size has a private key, so only a signing // size routes it. @@ -110,36 +115,82 @@ pub trait RsaSigningSize: RsaSize { 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: &RsaPrivateKey, m: &Self::Limbs) -> Self::Limbs; + fn crt_exp(sk: &RsaPrivateComponents, m: &Self::Limbs) -> Self::Limbs; } -/// Implemented on a signing size marker: the signature key pair, so a caller starts from the -/// size (`RSA2048::generate_signature_key_pair(&mut rng)`). 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 { - /// The size's public key. - type PublicKey; - /// The size's private key. - type PrivateKey; +/// 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 three 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` (and MGF1 over it). + /// + /// # Errors + /// As [`RsaSigningSize::keygen`]. + #[allow(clippy::type_complexity)] + fn generate_pss_signature_key_pair( + rng: &mut dyn RNG, + ) -> Result< + (RsaPublicKey>, RsaPrivateKey>), + SignatureError, + >; - /// FIPS 186-5 Appendix A.1.3 key pair generation from `rng`. + /// A key pair for RSASSA-PSS with the XOF `X` as hash and mask (RFC 8702). /// /// # Errors /// As [`RsaSigningSize::keygen`]. - fn generate_signature_key_pair( + #[allow(clippy::type_complexity)] + fn generate_pss_shake_signature_key_pair( rng: &mut dyn RNG, - ) -> Result<(Self::PublicKey, Self::PrivateKey), SignatureError>; + ) -> Result< + (RsaPublicKey>, RsaPrivateKey>), + SignatureError, + >; } impl SignatureKeyPair for K { - type PublicKey = RsaPublicKey; - type PrivateKey = RsaPrivateKey; + 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_signature_key_pair( + fn generate_pss_shake_signature_key_pair( rng: &mut dyn RNG, - ) -> Result<(RsaPublicKey, RsaPrivateKey), SignatureError> { - K::keygen(rng) + ) -> Result< + (RsaPublicKey>, RsaPrivateKey>), + SignatureError, + > { + let (pk, sk) = K::keygen(rng)?; + Ok((RsaPublicKey::from_components(pk), RsaPrivateKey::from_components(sk))) } } @@ -330,7 +381,7 @@ impl RsaSigningSize for RSA2048 { fn keygen( rng: &mut dyn RNG, - ) -> Result<(RsaPublicKey, RsaPrivateKey), SignatureError> { + ) -> Result<(RsaPublicComponents, RsaPrivateComponents), SignatureError> { keygen_from_rng::(rng, Self::MR_ROUNDS, Self::STRENGTH) } @@ -350,7 +401,7 @@ impl RsaSigningSize for RSA2048 { nat::sub(x, y).1 == 1 } - fn crt_exp(sk: &RsaPrivateKey, m: &Self::Limbs) -> Self::Limbs { + fn crt_exp(sk: &RsaPrivateComponents, m: &Self::Limbs) -> Self::Limbs { rsa_core::crt_exp::<32, 64, 65, 16, 32, 33>( sk.p(), sk.q(), @@ -408,7 +459,7 @@ impl RsaSigningSize for RSA3072 { fn keygen( rng: &mut dyn RNG, - ) -> Result<(RsaPublicKey, RsaPrivateKey), SignatureError> { + ) -> Result<(RsaPublicComponents, RsaPrivateComponents), SignatureError> { keygen_from_rng::(rng, Self::MR_ROUNDS, Self::STRENGTH) } @@ -428,7 +479,7 @@ impl RsaSigningSize for RSA3072 { nat::sub(x, y).1 == 1 } - fn crt_exp(sk: &RsaPrivateKey, m: &Self::Limbs) -> Self::Limbs { + fn crt_exp(sk: &RsaPrivateComponents, m: &Self::Limbs) -> Self::Limbs { rsa_core::crt_exp::<48, 96, 97, 24, 48, 49>( sk.p(), sk.q(), @@ -486,7 +537,7 @@ impl RsaSigningSize for RSA4096 { fn keygen( rng: &mut dyn RNG, - ) -> Result<(RsaPublicKey, RsaPrivateKey), SignatureError> { + ) -> Result<(RsaPublicComponents, RsaPrivateComponents), SignatureError> { keygen_from_rng::(rng, Self::MR_ROUNDS, Self::STRENGTH) } @@ -506,7 +557,7 @@ impl RsaSigningSize for RSA4096 { nat::sub(x, y).1 == 1 } - fn crt_exp(sk: &RsaPrivateKey, m: &Self::Limbs) -> Self::Limbs { + fn crt_exp(sk: &RsaPrivateComponents, m: &Self::Limbs) -> Self::Limbs { rsa_core::crt_exp::<64, 128, 129, 32, 64, 65>( sk.p(), sk.q(), @@ -564,7 +615,7 @@ impl RsaSigningSize for RSA8192 { fn keygen( rng: &mut dyn RNG, - ) -> Result<(RsaPublicKey, RsaPrivateKey), SignatureError> { + ) -> Result<(RsaPublicComponents, RsaPrivateComponents), SignatureError> { keygen_from_rng::(rng, Self::MR_ROUNDS, Self::STRENGTH) } @@ -584,7 +635,7 @@ impl RsaSigningSize for RSA8192 { nat::sub(x, y).1 == 1 } - fn crt_exp(sk: &RsaPrivateKey, m: &Self::Limbs) -> Self::Limbs { + fn crt_exp(sk: &RsaPrivateComponents, m: &Self::Limbs) -> Self::Limbs { rsa_core::crt_exp::<128, 256, 257, 64, 128, 129>( sk.p(), sk.q(), diff --git a/crypto/rsa/tests/keygen_tests.rs b/crypto/rsa/tests/keygen_tests.rs index 779c5d78..46ee4055 100644 --- a/crypto/rsa/tests/keygen_tests.rs +++ b/crypto/rsa/tests/keygen_tests.rs @@ -27,11 +27,17 @@ use bouncycastle_core::traits::SignaturePrivateKey; 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::rsa_2048::{ - self, RSA2048PrivateKey, RSA2048PublicKey, RSASSA_PKCS1_v1_5_SHA256, RSASSA_PSS_SHA256, SIG_LEN, -}; +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 @@ -187,29 +193,26 @@ fn assert_fips_186_5_criteria(&sk.encode(), pk.n(), 5); + 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 = DeterministicSigningKey::::sign_deterministic( - &sk, msg, None, - ) - .unwrap(); - VerifyingKey::::verify(&pk, msg, None, &sig).unwrap(); - assert!( - VerifyingKey::::verify(&pk, b"other", None, &sig).is_err() - ); - let sig = - SigningKey::::sign(&sk, &mut DefaultRNG::default(), msg, None) - .unwrap(); - VerifyingKey::::verify(&pk, msg, None, &sig).unwrap(); + 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, _) = rsa_2048::keygen(&mut DefaultRNG::default()).unwrap(); + let (pk2, _) = RSA2048::keygen(&mut DefaultRNG::default()).unwrap(); assert_ne!(pk2.n(), pk.n()); } @@ -217,50 +220,52 @@ fn keygen_2048_meets_fips_186_5_criteria_and_signs() { /// 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::(|| rsa_2048::keygen(&mut DefaultRNG::default()), false); + 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) = rsa_3072::keygen(&mut DefaultRNG::default()).unwrap(); - assert_fips_186_5_criteria::<24, 48, 49>(&sk.encode(), pk.n(), 4); + 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 = - DeterministicSigningKey::::sign_deterministic( - &sk, msg, None, - ) - .unwrap(); - VerifyingKey::::verify(&pk, msg, None, &sig).unwrap(); + 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) = rsa_4096::keygen(&mut DefaultRNG::default()).unwrap(); - assert_fips_186_5_criteria::<32, 64, 65>(&sk.encode(), pk.n(), 4); + 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 = SigningKey::::sign( - &sk, - &mut DefaultRNG::default(), - msg, - None, - ) - .unwrap(); - VerifyingKey::::verify(&pk, msg, None, &sig).unwrap(); + 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) = rsa_8192::keygen(&mut DefaultRNG::default()).unwrap(); - assert_fips_186_5_criteria::<64, 128, 129>(&sk.encode(), pk.n(), 4); + 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 = - DeterministicSigningKey::::sign_deterministic( - &sk, msg, None, - ) - .unwrap(); - VerifyingKey::::verify(&pk, msg, None, &sig).unwrap(); + 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`. @@ -302,7 +307,7 @@ impl RNG for ConstantRng { fn keygen_rejects_an_rng_below_the_required_strength() { let mut weak = ConstantRng { fill: 0x42, strength: SecurityStrength::None }; assert!(matches!( - rsa_2048::keygen(&mut weak), + RSA2048::keygen(&mut weak), Err(SignatureError::RNGError(RNGError::SecurityStrengthInsufficientForAlgorithm)) )); } @@ -313,5 +318,5 @@ fn keygen_rejects_an_rng_below_the_required_strength() { #[test] fn keygen_gives_up_on_a_stuck_rng() { let mut stuck = ConstantRng { fill: 0x42, strength: SecurityStrength::_256bit }; - assert!(matches!(rsa_2048::keygen(&mut stuck), Err(SignatureError::GenericError(_)))); + 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 index d3b602d4..97daf99f 100644 --- a/crypto/rsa/tests/keys_tests.rs +++ b/crypto/rsa/tests/keys_tests.rs @@ -1,16 +1,23 @@ //! Validation tests for [`bouncycastle_rsa::keys`]'s public API, including the //! `SignaturePrivateKey`/`SignaturePublicKey` impls `rsa_2048` gives its aliases of these types -//! (`RsaPrivateKey<32, 16>` *is* `RSA2048PrivateKey`, so the traits' methods resolve here once +//! (`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::SignatureError; use bouncycastle_core::traits::{SignaturePrivateKey, SignaturePublicKey}; -use bouncycastle_rsa::keys::{RsaPrivateKey, RsaPublicKey}; +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, @@ -54,7 +61,7 @@ const N: [u64; 32] = [ #[test] fn from_crt_components_accepts_a_genuine_key_and_derives_n() { - let sk = RsaPrivateKey::::from_crt_components(&P, &Q, &D_P, &D_Q, &Q_INV) + 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); } @@ -62,7 +69,7 @@ fn from_crt_components_accepts_a_genuine_key_and_derives_n() { #[test] fn from_crt_components_rejects_equal_primes() { assert!(matches!( - RsaPrivateKey::::from_crt_components(&P, &P, &D_P, &D_Q, &Q_INV), + RsaPrivateComponents::::from_crt_components(&P, &P, &D_P, &D_Q, &Q_INV), Err(SignatureError::DecodingError(_)) )); } @@ -72,7 +79,7 @@ fn from_crt_components_rejects_even_prime() { let mut even_p = P; even_p[0] &= !1; assert!(matches!( - RsaPrivateKey::::from_crt_components(&even_p, &Q, &D_P, &D_Q, &Q_INV), + RsaPrivateComponents::::from_crt_components(&even_p, &Q, &D_P, &D_Q, &Q_INV), Err(SignatureError::DecodingError(_)) )); } @@ -82,7 +89,7 @@ fn from_crt_components_rejects_even_q() { let mut even_q = Q; even_q[0] &= !1; assert!(matches!( - RsaPrivateKey::::from_crt_components(&P, &even_q, &D_P, &D_Q, &Q_INV), + RsaPrivateComponents::::from_crt_components(&P, &even_q, &D_P, &D_Q, &Q_INV), Err(SignatureError::DecodingError(_)) )); } @@ -90,7 +97,7 @@ fn from_crt_components_rejects_even_q() { #[test] fn from_crt_components_rejects_dp_out_of_range() { assert!(matches!( - RsaPrivateKey::::from_crt_components(&P, &Q, &P, &D_Q, &Q_INV), + RsaPrivateComponents::::from_crt_components(&P, &Q, &P, &D_Q, &Q_INV), Err(SignatureError::DecodingError(_)) )); } @@ -98,14 +105,14 @@ fn from_crt_components_rejects_dp_out_of_range() { #[test] fn from_crt_components_rejects_qinv_out_of_range() { assert!(matches!( - RsaPrivateKey::::from_crt_components(&P, &Q, &D_P, &D_Q, &P), + RsaPrivateComponents::::from_crt_components(&P, &Q, &D_P, &D_Q, &P), Err(SignatureError::DecodingError(_)) )); } #[test] fn public_key_accepts_e_65537() { - let pk = RsaPublicKey::::new(&N, 0x00010001).expect("e = 65537 is valid"); + let pk = RsaPublicComponents::::new(&N, 0x00010001).expect("e = 65537 is valid"); assert_eq!(*pk.n(), N); assert_eq!(pk.e(), 0x00010001); } @@ -113,14 +120,17 @@ fn public_key_accepts_e_65537() { #[test] fn public_key_rejects_even_exponent() { assert!(matches!( - RsaPublicKey::::new(&N, 65536), + RsaPublicComponents::::new(&N, 65536), Err(SignatureError::DecodingError(_)) )); } #[test] fn public_key_rejects_exponent_below_three() { - assert!(matches!(RsaPublicKey::::new(&N, 1), Err(SignatureError::DecodingError(_)))); + assert!(matches!( + RsaPublicComponents::::new(&N, 1), + Err(SignatureError::DecodingError(_)) + )); } #[test] @@ -128,16 +138,16 @@ fn public_key_rejects_even_modulus() { let mut even_n = N; even_n[0] &= !1; assert!(matches!( - RsaPublicKey::::new(&even_n, 3), + RsaPublicComponents::::new(&even_n, 3), Err(SignatureError::DecodingError(_)) )); } #[test] fn public_key_encode_round_trips() { - let pk = RsaPublicKey::::new(&N, 0x10001).unwrap(); + let pk = RsaPublicComponents::::new(&N, 0x10001).unwrap().into_key::(); let bytes: [u8; 260] = pk.encode(); - let decoded = RsaPublicKey::::from_bytes(&bytes).expect("must decode"); + let decoded = RsaPublicKey::::from_bytes(&bytes).expect("must decode"); assert_eq!(decoded, pk); } @@ -145,7 +155,7 @@ fn public_key_encode_round_trips() { /// 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 = RsaPublicKey::::new(&N, 0x10001).unwrap(); + 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()); @@ -158,27 +168,27 @@ fn public_key_encode_layout_is_n_then_e_big_endian() { #[test] fn public_key_from_bytes_rejects_even_modulus() { - let pk = RsaPublicKey::::new(&N, 0x10001).unwrap(); + 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), + RsaPublicKey::::from_bytes(&bytes), Err(SignatureError::DecodingError(_)) )); } #[test] fn public_key_from_bytes_rejects_wrong_lengths() { - let pk = RsaPublicKey::::new(&N, 0x10001).unwrap(); + let pk = RsaPublicComponents::::new(&N, 0x10001).unwrap().into_key::(); let bytes = pk.encode(); assert!(matches!( - RsaPublicKey::::from_bytes(&bytes[..259]), + RsaPublicKey::::from_bytes(&bytes[..259]), Err(SignatureError::DecodingError(_)) )); let mut too_long = bytes.to_vec(); too_long.push(0); assert!(matches!( - RsaPublicKey::::from_bytes(&too_long), + RsaPublicKey::::from_bytes(&too_long), Err(SignatureError::DecodingError(_)) )); } @@ -187,24 +197,31 @@ fn public_key_from_bytes_rejects_wrong_lengths() { /// 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 = RsaPublicKey::::new(&N, 0x10001).unwrap(); + 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 }}")); + assert_eq!( + shown, + format!("RsaPublicKey {{ n: {n_hex}, e: 10001 }}") + ); } #[test] fn private_key_encode_round_trips() { - let sk = RsaPrivateKey::::from_crt_components(&P, &Q, &D_P, &D_Q, &Q_INV).unwrap(); + 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"); + let decoded = RsaPrivateKey::::from_bytes(&bytes).expect("must decode"); assert_eq!(decoded, sk); } /// `SignaturePrivateKey`'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 = RsaPrivateKey::::from_crt_components(&P, &Q, &D_P, &D_Q, &Q_INV).unwrap(); + 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; @@ -219,29 +236,33 @@ fn private_key_encode_layout_is_five_big_endian_fields() { #[test] fn private_key_from_bytes_rejects_equal_primes() { - let sk = RsaPrivateKey::::from_crt_components(&P, &Q, &D_P, &D_Q, &Q_INV).unwrap(); + 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), + RsaPrivateKey::::from_bytes(&bytes), Err(SignatureError::DecodingError(_)) )); } #[test] fn private_key_from_bytes_rejects_wrong_lengths() { - let sk = RsaPrivateKey::::from_crt_components(&P, &Q, &D_P, &D_Q, &Q_INV).unwrap(); + 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]), + RsaPrivateKey::::from_bytes(&bytes[..639]), Err(SignatureError::DecodingError(_)) )); let mut too_long = bytes.to_vec(); too_long.push(0); assert!(matches!( - RsaPrivateKey::::from_bytes(&too_long), + RsaPrivateKey::::from_bytes(&too_long), Err(SignatureError::DecodingError(_)) )); } @@ -256,17 +277,17 @@ fn crt_components_out_of_range_rejected() { q.as_mut()[0] = 11; let mut small = ::HalfLimbs::ZEROED; small.as_mut()[0] = 3; - assert!(RsaPrivateKey::::from_crt_components(&p, &q, &small, &small, &small).is_ok()); + assert!(RsaPrivateComponents::::from_crt_components(&p, &q, &small, &small, &small).is_ok()); assert!(matches!( - RsaPrivateKey::::from_crt_components(&p, &q, &p, &small, &small), + RsaPrivateComponents::::from_crt_components(&p, &q, &p, &small, &small), Err(SignatureError::DecodingError(_)) )); assert!(matches!( - RsaPrivateKey::::from_crt_components(&p, &q, &small, &q, &small), + RsaPrivateComponents::::from_crt_components(&p, &q, &small, &q, &small), Err(SignatureError::DecodingError(_)) )); assert!(matches!( - RsaPrivateKey::::from_crt_components(&p, &q, &small, &small, &p), + RsaPrivateComponents::::from_crt_components(&p, &q, &small, &small, &p), Err(SignatureError::DecodingError(_)) )); } diff --git a/crypto/rsa/tests/rsa_1024_tests.rs b/crypto/rsa/tests/rsa_1024_tests.rs index cc9f5a2d..d03ce929 100644 --- a/crypto/rsa/tests/rsa_1024_tests.rs +++ b/crypto/rsa/tests/rsa_1024_tests.rs @@ -10,9 +10,9 @@ use bouncycastle_core::errors::SignatureError; use bouncycastle_core::signature_key::VerifyingKey; use bouncycastle_core::traits::SignaturePublicKey; use bouncycastle_hex::decode as hex_decode; -use bouncycastle_rsa::rsa_1024::{ - PK_LEN, RSA1024PublicKey, RSASSA_PKCS1_v1_5_SHA256, RSASSA_PKCS1_v1_5_SHA384, -}; +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; @@ -50,7 +50,7 @@ fn limbs_from_hex(hex: &str) -> [u64; L] { fn run_sig_gen_group_as_verify_vectors( sha: &str, - verify: impl Fn(&RSA1024PublicKey, &[u8], &[u8; 128]) -> bool, + 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(); @@ -64,7 +64,7 @@ fn run_sig_gen_group_as_verify_vectors( 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 = RSA1024PublicKey::new(&n, e).expect("group public key must be valid"); + 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() { @@ -81,20 +81,20 @@ fn run_sig_gen_group_as_verify_vectors( #[test] fn pkcs1_v1_5_sha256_accepts_genuine_sig_gen_signatures() { run_sig_gen_group_as_verify_vectors("SHA-256", |pk, msg, sig| { - VerifyingKey::::verify(pk, msg, None, sig).is_ok() + 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| { - VerifyingKey::::verify(pk, msg, None, sig).is_ok() + pk.key::().verify(msg, None, sig).is_ok() }); } fn run_sig_gen_group_rejects_wrong_message( sha: &str, - verify: impl Fn(&RSA1024PublicKey, &[u8], &[u8; 128]) -> bool, + 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(); @@ -107,7 +107,7 @@ fn run_sig_gen_group_rejects_wrong_message( 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 = RSA1024PublicKey::new(&n, e).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(); @@ -117,7 +117,7 @@ fn run_sig_gen_group_rejects_wrong_message( #[test] fn pkcs1_v1_5_sha256_rejects_wrong_message() { run_sig_gen_group_rejects_wrong_message("SHA-256", |pk, msg, sig| { - VerifyingKey::::verify(pk, msg, None, sig).is_ok() + pk.key::().verify(msg, None, sig).is_ok() }); } @@ -127,7 +127,7 @@ fn pkcs1_v1_5_sha256_rejects_wrong_message() { #[test] fn pkcs1_v1_5_sha384_rejects_wrong_message() { run_sig_gen_group_rejects_wrong_message("SHA-384", |pk, msg, sig| { - VerifyingKey::::verify(pk, msg, None, sig).is_ok() + pk.key::().verify(msg, None, sig).is_ok() }); } @@ -144,7 +144,7 @@ fn pkcs1_v1_5_sha384_rejects_wrong_message() { fn trait_verify_rejects_truncated_signature() { run_sig_gen_group_as_verify_vectors("SHA-256", |pk, msg, sig| { matches!( - VerifyingKey::::verify(pk, msg, None, &sig[..127]), + pk.key::().verify(msg, None, &sig[..127]), Err(SignatureError::LengthError(_)) ) }); @@ -158,19 +158,20 @@ fn public_key_trait_encoding_round_trips_and_rejects_wrong_lengths() { 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 = RSA1024PublicKey::new(&n, e).unwrap(); + let pk = + RsaPublicComponents::::new(&n, e).unwrap().into_key::(); let bytes = pk.encode(); assert_eq!(bytes.len(), PK_LEN); - assert_eq!(RSA1024PublicKey::from_bytes(&bytes).unwrap(), pk); + assert_eq!(RsaPublicKey::::from_bytes(&bytes).unwrap(), pk); assert!(matches!( - RSA1024PublicKey::from_bytes(&bytes[..PK_LEN - 1]), + RsaPublicKey::::from_bytes(&bytes[..PK_LEN - 1]), Err(SignatureError::DecodingError(_)) )); let mut too_long = bytes.to_vec(); too_long.push(0); assert!(matches!( - RSA1024PublicKey::from_bytes(&too_long), + RsaPublicKey::::from_bytes(&too_long), Err(SignatureError::DecodingError(_)) )); } @@ -181,7 +182,7 @@ fn public_key_trait_encoding_round_trips_and_rejects_wrong_lengths() { fn trait_verify_reports_out_of_range_representative_as_invalid_signature() { run_sig_gen_group_as_verify_vectors("SHA-256", |pk, msg, _sig| { matches!( - VerifyingKey::::verify(pk, msg, None, &[0xffu8; 128]), + 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 index 17c53d48..a30a75e7 100644 --- a/crypto/rsa/tests/rsa_1536_tests.rs +++ b/crypto/rsa/tests/rsa_1536_tests.rs @@ -8,9 +8,10 @@ use bouncycastle_core::errors::SignatureError; use bouncycastle_core::signature_key::VerifyingKey; use bouncycastle_core::traits::SignaturePublicKey; use bouncycastle_hex::decode as hex_decode; +use bouncycastle_rsa::RSA1536; +use bouncycastle_rsa::keys::{RsaPublicComponents, RsaPublicKey}; use bouncycastle_rsa::rsa_1536::{ - PK_LEN, RSA1536PublicKey, RSASSA_PKCS1_v1_5_SHA256, RSASSA_PKCS1_v1_5_SHA384, - RSASSA_PKCS1_v1_5_SHA512, + PK_LEN, RSASSA_PKCS1_v1_5_SHA256, RSASSA_PKCS1_v1_5_SHA384, RSASSA_PKCS1_v1_5_SHA512, }; use serde_json::Value; use std::fs; @@ -49,7 +50,7 @@ fn limbs_from_hex(hex: &str) -> [u64; L] { fn run_sig_gen_group_as_verify_vectors( sha: &str, - verify: impl Fn(&RSA1536PublicKey, &[u8], &[u8; 192]) -> bool, + 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(); @@ -63,7 +64,7 @@ fn run_sig_gen_group_as_verify_vectors( 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 = RSA1536PublicKey::new(&n, e).expect("group public key must be valid"); + 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() { @@ -80,27 +81,27 @@ fn run_sig_gen_group_as_verify_vectors( #[test] fn pkcs1_v1_5_sha256_accepts_genuine_sig_gen_signatures() { run_sig_gen_group_as_verify_vectors("SHA-256", |pk, msg, sig| { - VerifyingKey::::verify(pk, msg, None, sig).is_ok() + 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| { - VerifyingKey::::verify(pk, msg, None, sig).is_ok() + 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| { - VerifyingKey::::verify(pk, msg, None, sig).is_ok() + pk.key::().verify(msg, None, sig).is_ok() }); } fn run_sig_gen_group_rejects_wrong_message( sha: &str, - verify: impl Fn(&RSA1536PublicKey, &[u8], &[u8; 192]) -> bool, + 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(); @@ -108,7 +109,7 @@ fn run_sig_gen_group_rejects_wrong_message( 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 = RSA1536PublicKey::new(&n, e).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(); @@ -118,7 +119,7 @@ fn run_sig_gen_group_rejects_wrong_message( #[test] fn pkcs1_v1_5_sha256_rejects_wrong_message() { run_sig_gen_group_rejects_wrong_message("SHA-256", |pk, msg, sig| { - VerifyingKey::::verify(pk, msg, None, sig).is_ok() + pk.key::().verify(msg, None, sig).is_ok() }); } @@ -128,14 +129,14 @@ fn pkcs1_v1_5_sha256_rejects_wrong_message() { #[test] fn pkcs1_v1_5_sha384_rejects_wrong_message() { run_sig_gen_group_rejects_wrong_message("SHA-384", |pk, msg, sig| { - VerifyingKey::::verify(pk, msg, None, sig).is_ok() + 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| { - VerifyingKey::::verify(pk, msg, None, sig).is_ok() + pk.key::().verify(msg, None, sig).is_ok() }); } @@ -148,7 +149,7 @@ fn pkcs1_v1_5_sha512_rejects_wrong_message() { fn trait_verify_rejects_truncated_signature() { run_sig_gen_group_as_verify_vectors("SHA-256", |pk, msg, sig| { matches!( - VerifyingKey::::verify(pk, msg, None, &sig[..191]), + pk.key::().verify(msg, None, &sig[..191]), Err(SignatureError::LengthError(_)) ) }); @@ -162,19 +163,20 @@ fn public_key_trait_encoding_round_trips_and_rejects_wrong_lengths() { 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 = RSA1536PublicKey::new(&n, e).unwrap(); + let pk = + RsaPublicComponents::::new(&n, e).unwrap().into_key::(); let bytes = pk.encode(); assert_eq!(bytes.len(), PK_LEN); - assert_eq!(RSA1536PublicKey::from_bytes(&bytes).unwrap(), pk); + assert_eq!(RsaPublicKey::::from_bytes(&bytes).unwrap(), pk); assert!(matches!( - RSA1536PublicKey::from_bytes(&bytes[..PK_LEN - 1]), + RsaPublicKey::::from_bytes(&bytes[..PK_LEN - 1]), Err(SignatureError::DecodingError(_)) )); let mut too_long = bytes.to_vec(); too_long.push(0); assert!(matches!( - RSA1536PublicKey::from_bytes(&too_long), + RsaPublicKey::::from_bytes(&too_long), Err(SignatureError::DecodingError(_)) )); } @@ -185,7 +187,7 @@ fn public_key_trait_encoding_round_trips_and_rejects_wrong_lengths() { fn trait_verify_reports_out_of_range_representative_as_invalid_signature() { run_sig_gen_group_as_verify_vectors("SHA-256", |pk, msg, _sig| { matches!( - VerifyingKey::::verify(pk, msg, None, &[0xffu8; 192]), + 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 index 879e0f4c..a48fc9f9 100644 --- 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 @@ -17,10 +17,11 @@ use bouncycastle_core::errors::SignatureError; use bouncycastle_core::signature_key::{DeterministicSigningKey, VerifyingKey}; use bouncycastle_core_test_framework::signature::TestFrameworkSignature; use bouncycastle_hex::decode as hex_decode; -use bouncycastle_rsa::rsa_2048::{ - RSA2048PrivateKey, RSA2048PublicKey, RSASSA_PKCS1_v1_5_SHA384, RSASSA_PKCS1_v1_5_SHA512, - SIG_LEN, +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; @@ -59,7 +60,7 @@ fn limbs_from_hex(hex: &str) -> [u64; L] { /// 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() -> RSA2048PrivateKey { +fn genuine_key() -> RsaPrivateComponents { let p: [u64; 16] = [ 0x0ea36cfb3a5b18f1, 0x48a6e65332119129, 0x110ad9e7b48a1c93, 0x569156b90113e2e9, 0xe79813a575cfad9c, 0x69d659d143ec6f17, 0xe81e6bab5ddaa783, 0xbff1c5b80a69f788, @@ -90,43 +91,37 @@ fn genuine_key() -> RSA2048PrivateKey { 0xe923e1097c0c562f, 0xc968b48a91c38b5b, 0x933e85179c0320b0, 0x7993d0445f758d51, 0x9bfc042ee0924b1b, 0x41f956d90fa8a793, 0xee7a87b6483a66ee, 0x2640fbfbcfefb163, ]; - RSA2048PrivateKey::from_crt_components(&p, &q, &d_p, &d_q, &q_inv) + 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 = RSA2048PublicKey::new(sk.n(), 0x10001).unwrap(); - let sig = DeterministicSigningKey::::sign_deterministic( - &sk, b"hello", None, - ) - .expect("signing must succeed"); - VerifyingKey::::verify(&pk, b"hello", None, &sig) - .expect("must verify"); - assert!( - VerifyingKey::::verify(&pk, b"goodbye", None, &sig).is_err() - ); + 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 = RSA2048PublicKey::new(sk.n(), 0x10001).unwrap(); - let sig = DeterministicSigningKey::::sign_deterministic( - &sk, b"hello", None, - ) - .expect("signing must succeed"); - VerifyingKey::::verify(&pk, b"hello", None, &sig) - .expect("must verify"); - assert!( - VerifyingKey::::verify(&pk, b"goodbye", None, &sig).is_err() - ); + 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(&RSA2048PublicKey, &[u8], &[u8; 256]) -> bool, + verify: impl Fn(&RsaPublicComponents, &[u8], &[u8; 256]) -> bool, expected_sha: &str, expected_num_tests: usize, expected_num_valid: usize, @@ -144,7 +139,8 @@ fn run_verify_vectors( 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 = RSA2048PublicKey::new(&n, e).expect("group public key must be valid"); + let pk = + RsaPublicComponents::::new(&n, e).expect("group public key must be valid"); for test in group["tests"].as_array().unwrap() { num_tests += 1; @@ -194,9 +190,7 @@ fn run_verify_vectors( fn rsa_signature_sha384_wycheproof_vectors() { run_verify_vectors( "rsa_signature_2048_sha384_test.json", - |pk, msg, sig| { - VerifyingKey::::verify(pk, msg, None, sig).is_ok() - }, + |pk, msg, sig| pk.key::().verify(msg, None, sig).is_ok(), "SHA-384", 258, 7, @@ -208,9 +202,7 @@ fn rsa_signature_sha384_wycheproof_vectors() { fn rsa_signature_sha512_wycheproof_vectors() { run_verify_vectors( "rsa_signature_2048_sha512_test.json", - |pk, msg, sig| { - VerifyingKey::::verify(pk, msg, None, sig).is_ok() - }, + |pk, msg, sig| pk.key::().verify(msg, None, sig).is_ok(), "SHA-512", 259, 8, @@ -220,9 +212,10 @@ fn rsa_signature_sha512_wycheproof_vectors() { // ---- bouncycastle_core trait conformance ------------------------------------------------------ -fn fixed_keypair() -> Result<(RSA2048PublicKey, RSA2048PrivateKey), SignatureError> { +fn fixed_keypair() +-> Result<(RsaPublicComponents, RsaPrivateComponents), SignatureError> { let sk = genuine_key(); - let pk = RSA2048PublicKey::new(sk.n(), 0x10001)?; + let pk = RsaPublicComponents::::new(sk.n(), 0x10001)?; Ok((pk, sk)) } @@ -232,6 +225,8 @@ fn fixed_keypair() -> Result<(RSA2048PublicKey, RSA2048PrivateKey), SignatureErr #[test] fn pkcs1_v1_5_sha384_sha512_trait_conformance_suite() { let framework = TestFrameworkSignature::new(false); - framework.test_deterministic_signature::(fixed_keypair, false); - framework.test_deterministic_signature::(fixed_keypair, 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 index 2d11b026..e913d373 100644 --- a/crypto/rsa/tests/rsa_2048_pkcs1_v1_5_tests.rs +++ b/crypto/rsa/tests/rsa_2048_pkcs1_v1_5_tests.rs @@ -39,10 +39,12 @@ use bouncycastle_core_test_framework::signature::{ }; use bouncycastle_hex::decode as hex_decode; use bouncycastle_rsa::RSA2048; -use bouncycastle_rsa::rsa_2048::{ - PK_LEN, RSA2048PrivateKey, RSA2048PublicKey, RSASSA_PKCS1_v1_5_SHA256, SIG_LEN, SK_LEN, +use bouncycastle_rsa::keys::{ + RsaPrivateComponents, RsaPrivateKey, RsaPublicComponents, RsaPublicKey, }; -use bouncycastle_rsa::rsassa_pkcs1_v1_5; +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; @@ -83,7 +85,7 @@ fn limbs_from_hex(hex: &str) -> [u64; L] { limbs } -fn wycheproof_key() -> RSA2048PrivateKey { +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 @@ -119,7 +121,7 @@ fn wycheproof_key() -> RSA2048PrivateKey { 0xe923e1097c0c562f, 0xc968b48a91c38b5b, 0x933e85179c0320b0, 0x7993d0445f758d51, 0x9bfc042ee0924b1b, 0x41f956d90fa8a793, 0xee7a87b6483a66ee, 0x2640fbfbcfefb163, ]; - RSA2048PrivateKey::from_crt_components(&p, &q, &d_p, &d_q, &q_inv) + RsaPrivateComponents::::from_crt_components(&p, &q, &d_p, &d_q, &q_inv) .expect("recovered CRT components must be accepted") } @@ -148,12 +150,12 @@ fn pkcs1_v1_5_sig_gen_2048_sha256() { 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 = DeterministicSigningKey::::sign_deterministic( - &sk, &msg, None, - ) - .unwrap_or_else(|e| { - panic!("tcId {tc_id}: signing failed: {e:?}"); - }); + 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); @@ -163,9 +165,10 @@ fn pkcs1_v1_5_sig_gen_2048_sha256() { /// 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<(RSA2048PublicKey, RSA2048PrivateKey), SignatureError> { +fn fixed_keypair() +-> Result<(RsaPublicComponents, RsaPrivateComponents), SignatureError> { let sk = wycheproof_key(); - let pk = RSA2048PublicKey::new(sk.n(), 0x10001)?; + let pk = RsaPublicComponents::::new(sk.n(), 0x10001)?; Ok((pk, sk)) } @@ -176,13 +179,16 @@ fn fixed_keypair() -> Result<(RSA2048PublicKey, RSA2048PrivateKey), SignatureErr /// 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::(fixed_keypair, true); + 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::(fixed_keypair); + .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 @@ -191,20 +197,15 @@ fn key_trait_boundary_conditions() { fn streamed_signature_equals_one_shot() { let (pk, sk) = fixed_keypair().unwrap(); let msg = b"the same message, two ways"; - let one_shot = DeterministicSigningKey::::sign_deterministic( - &sk, msg, None, - ) - .unwrap(); - let mut signer = - DeterministicSigningKey::::create_signer_deterministic( - &sk, None, - ) - .unwrap(); + 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); - VerifyingKey::::verify(&pk, msg, None, &streamed).unwrap(); + 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 @@ -214,21 +215,13 @@ fn streamed_signature_equals_one_shot() { #[test] fn trait_verify_rejects_short_signature() { let (pk, sk) = fixed_keypair().unwrap(); - let sig = DeterministicSigningKey::::sign_deterministic( - &sk, b"msg", None, - ) - .unwrap(); + let sig = sk.key::().sign_deterministic(b"msg", None).unwrap(); assert!(matches!( - VerifyingKey::::verify( - &pk, - b"msg", - None, - &sig[..SIG_LEN - 1] - ), + pk.key::().verify(b"msg", None, &sig[..SIG_LEN - 1]), Err(SignatureError::LengthError(_)) )); assert!(matches!( - VerifyingKey::::verify(&pk, b"msg", None, &[]), + pk.key::().verify(b"msg", None, &[]), Err(SignatureError::LengthError(_)) )); } @@ -249,15 +242,14 @@ fn rsa_signature_sha256_all_groups() { 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 = RSA2048PublicKey::new(&n, e).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 = - VerifyingKey::::verify(&pk, &msg, None, &sig); + 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" => { @@ -300,11 +292,15 @@ fn trait_verify_reports_out_of_range_representative_as_invalid_signature() { let mut digest = [0u8; 32]; SHA256::hash_out(b"msg", &mut digest); assert!(matches!( - rsassa_pkcs1_v1_5::verify_from_hash::(&pk, &digest, &too_big), + rsassa::verify_from_hash::, SIG_LEN>( + &pk.key::>(), + &digest, + &too_big + ), Err(SignatureError::DecodingError(_)) )); assert!(matches!( - VerifyingKey::::verify(&pk, b"msg", None, &too_big), + pk.key::().verify(b"msg", None, &too_big), Err(SignatureError::SignatureVerificationFailed) )); } diff --git a/crypto/rsa/tests/rsa_2048_pss_sha384_sha512_tests.rs b/crypto/rsa/tests/rsa_2048_pss_sha384_sha512_tests.rs index efdfe683..07f14deb 100644 --- a/crypto/rsa/tests/rsa_2048_pss_sha384_sha512_tests.rs +++ b/crypto/rsa/tests/rsa_2048_pss_sha384_sha512_tests.rs @@ -12,9 +12,11 @@ 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::rsa_2048::{ - RSA2048PrivateKey, RSA2048PublicKey, RSASSA_PSS_SHA384, RSASSA_PSS_SHA512, SIG_LEN, +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; @@ -23,8 +25,8 @@ use std::path::Path; /// 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 mut signer = - SigningKey::<$ty, 256>::create_signer($sk, &mut DefaultRNG::default(), None).unwrap(); + 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() @@ -64,7 +66,7 @@ fn limbs_from_hex(hex: &str) -> [u64; L] { /// 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() -> RSA2048PrivateKey { +fn genuine_key() -> RsaPrivateComponents { let p: [u64; 16] = [ 0x0ea36cfb3a5b18f1, 0x48a6e65332119129, 0x110ad9e7b48a1c93, 0x569156b90113e2e9, 0xe79813a575cfad9c, 0x69d659d143ec6f17, 0xe81e6bab5ddaa783, 0xbff1c5b80a69f788, @@ -95,62 +97,58 @@ fn genuine_key() -> RSA2048PrivateKey { 0xe923e1097c0c562f, 0xc968b48a91c38b5b, 0x933e85179c0320b0, 0x7993d0445f758d51, 0x9bfc042ee0924b1b, 0x41f956d90fa8a793, 0xee7a87b6483a66ee, 0x2640fbfbcfefb163, ]; - RSA2048PrivateKey::from_crt_components(&p, &q, &d_p, &d_q, &q_inv) + 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 = RSA2048PublicKey::new(sk.n(), 0x10001).unwrap(); + 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"); - VerifyingKey::::verify(&pk, b"hello", None, &sig).expect("must verify"); - assert!(VerifyingKey::::verify(&pk, b"goodbye", None, &sig).is_err()); + 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 = RSA2048PublicKey::new(sk.n(), 0x10001).unwrap(); + let pk = RsaPublicComponents::::new(sk.n(), 0x10001).unwrap(); let mut rng = DefaultRNG::default(); - let sig_a = SigningKey::::sign(&sk, &mut rng, b"hello", None) - .expect("signing must succeed"); - let sig_b = SigningKey::::sign(&sk, &mut rng, b"hello", None) - .expect("signing must succeed"); + 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); - VerifyingKey::::verify(&pk, b"hello", None, &sig_a) - .expect("sig_a must verify"); - VerifyingKey::::verify(&pk, b"hello", None, &sig_b) - .expect("sig_b must verify"); + 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 = RSA2048PublicKey::new(sk.n(), 0x10001).unwrap(); + 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"); - VerifyingKey::::verify(&pk, b"hello", None, &sig).expect("must verify"); - assert!(VerifyingKey::::verify(&pk, b"goodbye", None, &sig).is_err()); + 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 = RSA2048PublicKey::new(sk.n(), 0x10001).unwrap(); + let pk = RsaPublicComponents::::new(sk.n(), 0x10001).unwrap(); let mut rng = DefaultRNG::default(); - let sig_a = SigningKey::::sign(&sk, &mut rng, b"hello", None) - .expect("signing must succeed"); - let sig_b = SigningKey::::sign(&sk, &mut rng, b"hello", None) - .expect("signing must succeed"); + 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); - VerifyingKey::::verify(&pk, b"hello", None, &sig_a) - .expect("sig_a must verify"); - VerifyingKey::::verify(&pk, b"hello", None, &sig_b) - .expect("sig_b must verify"); + 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] @@ -169,7 +167,8 @@ fn rsa_pss_sha384_mgf1_48_wycheproof_vectors() { 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 = RSA2048PublicKey::new(&n, e).expect("group public key must be valid"); + let pk = + RsaPublicComponents::::new(&n, e).expect("group public key must be valid"); for test in group["tests"].as_array().unwrap() { num_tests += 1; @@ -183,8 +182,7 @@ fn rsa_pss_sha384_mgf1_48_wycheproof_vectors() { continue; }; - let verified = - VerifyingKey::::verify(&pk, &msg, None, &sig).is_ok(); + 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"); @@ -206,9 +204,10 @@ fn rsa_pss_sha384_mgf1_48_wycheproof_vectors() { // ---- bouncycastle_core trait conformance ------------------------------------------------------ -fn fixed_keypair() -> Result<(RSA2048PublicKey, RSA2048PrivateKey), SignatureError> { +fn fixed_keypair() +-> Result<(RsaPublicComponents, RsaPrivateComponents), SignatureError> { let sk = genuine_key(); - let pk = RSA2048PublicKey::new(sk.n(), 0x10001)?; + let pk = RsaPublicComponents::::new(sk.n(), 0x10001)?; Ok((pk, sk)) } @@ -217,11 +216,11 @@ fn fixed_keypair() -> Result<(RSA2048PublicKey, RSA2048PrivateKey), SignatureErr #[test] fn pss_sha384_sha512_trait_conformance_suite() { let framework = TestFrameworkSignature::new(false); - framework.test_signature::( - fixed_keypair, false, + framework.test_signature::, RsaPrivateKey, SIG_LEN>( + || fixed_keypair().map(|(pk, sk)| (pk.into_key::(), sk.into_key::())), false, ); - framework.test_signature::( - fixed_keypair, false, + framework.test_signature::, RsaPrivateKey, SIG_LEN>( + || fixed_keypair().map(|(pk, sk)| (pk.into_key::(), sk.into_key::())), false, ); } @@ -229,28 +228,26 @@ fn pss_sha384_sha512_trait_conformance_suite() { fn pss_sha384_and_sha512_reject_each_others_signatures() { let (pk, sk) = fixed_keypair().unwrap(); let msg = b"PSS across both APIs"; - VerifyingKey::::verify( - &pk, - msg, - None, - &SigningKey::::sign(&sk, &mut DefaultRNG::default(), msg, None) - .unwrap(), - ) - .unwrap(); - VerifyingKey::::verify( - &pk, - msg, - None, - &SigningKey::::sign(&sk, &mut DefaultRNG::default(), msg, None) - .unwrap(), - ) - .unwrap(); + 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 = SigningKey::::sign(&sk, &mut rng, msg, None).unwrap(); - let free_512 = SigningKey::::sign(&sk, &mut rng, msg, None).unwrap(); - VerifyingKey::::verify(&pk, msg, None, &free_384).unwrap(); - VerifyingKey::::verify(&pk, msg, None, &free_512).unwrap(); + 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!(VerifyingKey::::verify(&pk, msg, None, &free_512).is_err()); - assert!(VerifyingKey::::verify(&pk, msg, None, &free_384).is_err()); + 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 index 2a28f536..1d9dd5fc 100644 --- a/crypto/rsa/tests/rsa_2048_pss_shake128_tests.rs +++ b/crypto/rsa/tests/rsa_2048_pss_shake128_tests.rs @@ -13,10 +13,12 @@ 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::rsa_2048::{ - RSA2048PrivateKey, RSA2048PublicKey, RSASSA_PSS_SHAKE128, SIG_LEN, +use bouncycastle_rsa::keys::{ + RsaPrivateComponents, RsaPrivateKey, RsaPublicComponents, RsaPublicKey, }; -use bouncycastle_rsa::rsassa_pss_shake; +use bouncycastle_rsa::rsa_2048::{RSASSA_PSS_SHAKE128, SIG_LEN}; +use bouncycastle_rsa::rsassa; +use bouncycastle_rsa::rsassa_pss_shake::RSASSA_PSS_SHAKE; use bouncycastle_sha3::SHAKE128; use serde_json::Value; use std::fs; @@ -26,8 +28,8 @@ use std::path::Path; /// 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 mut signer = - SigningKey::<$ty, 256>::create_signer($sk, &mut DefaultRNG::default(), None).unwrap(); + 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() @@ -68,7 +70,7 @@ fn limbs_from_hex(hex: &str) -> [u64; L] { /// 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() -> RSA2048PrivateKey { +fn genuine_key() -> RsaPrivateComponents { let p: [u64; 16] = [ 0x0ea36cfb3a5b18f1, 0x48a6e65332119129, 0x110ad9e7b48a1c93, 0x569156b90113e2e9, 0xe79813a575cfad9c, 0x69d659d143ec6f17, 0xe81e6bab5ddaa783, 0xbff1c5b80a69f788, @@ -99,46 +101,46 @@ fn genuine_key() -> RSA2048PrivateKey { 0xe923e1097c0c562f, 0xc968b48a91c38b5b, 0x933e85179c0320b0, 0x7993d0445f758d51, 0x9bfc042ee0924b1b, 0x41f956d90fa8a793, 0xee7a87b6483a66ee, 0x2640fbfbcfefb163, ]; - RSA2048PrivateKey::from_crt_components(&p, &q, &d_p, &d_q, &q_inv) + 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 = RSA2048PublicKey::new(sk.n(), 0x10001).unwrap(); + 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"); - VerifyingKey::::verify(&pk, b"the message to sign", None, &sig) + 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!( - VerifyingKey::::verify(&pk, b"a different message", None, &sig) - .is_err() - ); + 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 = RSA2048PublicKey::new(sk.n(), 0x10001).unwrap(); + let pk = RsaPublicComponents::::new(sk.n(), 0x10001).unwrap(); let mut rng = DefaultRNG::default(); - let sig_a = SigningKey::::sign(&sk, &mut rng, b"hello", None) + let sig_a = sk + .key::() + .sign(&mut rng, b"hello", None) .expect("signing must succeed"); - let sig_b = SigningKey::::sign(&sk, &mut rng, b"hello", None) + 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"); - VerifyingKey::::verify(&pk, b"hello", None, &sig_a) - .expect("sig_a must verify"); - VerifyingKey::::verify(&pk, b"hello", None, &sig_b) - .expect("sig_b must verify"); + 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] @@ -157,7 +159,8 @@ fn rsa_pss_2048_shake128_wycheproof_vectors() { 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 = RSA2048PublicKey::new(&n, e).expect("group public key must be valid"); + let pk = + RsaPublicComponents::::new(&n, e).expect("group public key must be valid"); for test in group["tests"].as_array().unwrap() { num_tests += 1; @@ -171,8 +174,7 @@ fn rsa_pss_2048_shake128_wycheproof_vectors() { continue; }; - let verified = - VerifyingKey::::verify(&pk, &msg, None, &sig).is_ok(); + 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"); @@ -194,9 +196,10 @@ fn rsa_pss_2048_shake128_wycheproof_vectors() { // ---- bouncycastle_core trait conformance ------------------------------------------------------ -fn fixed_keypair() -> Result<(RSA2048PublicKey, RSA2048PrivateKey), SignatureError> { +fn fixed_keypair() +-> Result<(RsaPublicComponents, RsaPrivateComponents), SignatureError> { let sk = genuine_key(); - let pk = RSA2048PublicKey::new(sk.n(), 0x10001)?; + let pk = RsaPublicComponents::::new(sk.n(), 0x10001)?; Ok((pk, sk)) } @@ -206,8 +209,8 @@ fn fixed_keypair() -> Result<(RSA2048PublicKey, RSA2048PrivateKey), SignatureErr #[test] fn pss_shake128_trait_conformance_suite() { TestFrameworkSignature::new(false) - .test_signature::( - fixed_keypair, true, + .test_signature::, RsaPrivateKey, SIG_LEN>( + || fixed_keypair().map(|(pk, sk)| (pk.into_key::(), sk.into_key::())), true, ); } @@ -255,36 +258,33 @@ fn set_salt_fixes_the_salt_on_the_streaming_path() { let msg = b"fixed salt, streamed in two chunks"; let salt = [0x42u8; 32]; - let mut signer = SigningKey::::create_signer( - &sk, - &mut DefaultRNG::default(), - None, - ) - .unwrap(); + 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_pss_shake::sign_from_hash_with_salt::(&sk, &digest, &salt) - .unwrap(); - assert_eq!(sig, expected); - VerifyingKey::::verify(&pk, msg, None, &sig).unwrap(); - - let mut fresh = SigningKey::::create_signer( - &sk, - &mut DefaultRNG::default(), - None, + 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_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 mut verifier = - VerifyingKey::::create_verifier(&pk, None).unwrap(); + 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(); } @@ -296,18 +296,17 @@ fn set_salt_fixes_the_salt_on_the_streaming_path() { 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 = - SigningKey::::sign(&sk, &mut FixedRng, msg, None).unwrap(); + 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 = SigningKey::::sign(&sk, &mut rng, msg, None).unwrap(); - let b = SigningKey::::sign(&sk, &mut rng, msg, None).unwrap(); + let a = sk.key::().sign(&mut rng, msg, None).unwrap(); + let b = sk.key::().sign(&mut rng, msg, None).unwrap(); assert_ne!(a, b); - VerifyingKey::::verify(&pk, msg, None, &a).unwrap(); - VerifyingKey::::verify(&pk, msg, None, &b).unwrap(); - assert!(VerifyingKey::::verify(&pk, b"other", None, &a).is_err()); + 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 index 09b4da92..8f3513b9 100644 --- a/crypto/rsa/tests/rsa_2048_pss_tests.rs +++ b/crypto/rsa/tests/rsa_2048_pss_tests.rs @@ -18,8 +18,12 @@ 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::rsa_2048::{RSA2048PrivateKey, RSA2048PublicKey, RSASSA_PSS_SHA256, SIG_LEN}; -use bouncycastle_rsa::rsassa_pss; +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; @@ -29,8 +33,8 @@ use std::path::Path; /// 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 mut signer = - SigningKey::<$ty, 256>::create_signer($sk, &mut DefaultRNG::default(), None).unwrap(); + 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() @@ -71,7 +75,7 @@ fn limbs_from_hex(hex: &str) -> [u64; L] { /// 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() -> RSA2048PrivateKey { +fn wycheproof_key() -> RsaPrivateComponents { let p: [u64; 16] = [ 0x0ea36cfb3a5b18f1, 0x48a6e65332119129, 0x110ad9e7b48a1c93, 0x569156b90113e2e9, 0xe79813a575cfad9c, 0x69d659d143ec6f17, 0xe81e6bab5ddaa783, 0xbff1c5b80a69f788, @@ -102,46 +106,40 @@ fn wycheproof_key() -> RSA2048PrivateKey { 0xe923e1097c0c562f, 0xc968b48a91c38b5b, 0x933e85179c0320b0, 0x7993d0445f758d51, 0x9bfc042ee0924b1b, 0x41f956d90fa8a793, 0xee7a87b6483a66ee, 0x2640fbfbcfefb163, ]; - RSA2048PrivateKey::from_crt_components(&p, &q, &d_p, &d_q, &q_inv) + 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 = RSA2048PublicKey::new(sk.n(), 0x10001).unwrap(); + 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"); - VerifyingKey::::verify(&pk, b"the message to sign", None, &sig) - .expect("must verify"); + 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!( - VerifyingKey::::verify(&pk, b"a different message", None, &sig) - .is_err() - ); + 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 = RSA2048PublicKey::new(sk.n(), 0x10001).unwrap(); + let pk = RsaPublicComponents::::new(sk.n(), 0x10001).unwrap(); let mut rng = DefaultRNG::default(); - let sig_a = SigningKey::::sign(&sk, &mut rng, b"hello", None) - .expect("signing must succeed"); - let sig_b = SigningKey::::sign(&sk, &mut rng, b"hello", None) - .expect("signing must succeed"); + 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"); - VerifyingKey::::verify(&pk, b"hello", None, &sig_a) - .expect("sig_a must verify"); - VerifyingKey::::verify(&pk, b"hello", None, &sig_b) - .expect("sig_b must verify"); + 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] @@ -160,7 +158,8 @@ fn rsa_pss_sha256_mgf1_32_wycheproof_vectors() { 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 = RSA2048PublicKey::new(&n, e).expect("group public key must be valid"); + let pk = + RsaPublicComponents::::new(&n, e).expect("group public key must be valid"); for test in group["tests"].as_array().unwrap() { num_tests += 1; @@ -174,8 +173,7 @@ fn rsa_pss_sha256_mgf1_32_wycheproof_vectors() { continue; }; - let verified = - VerifyingKey::::verify(&pk, &msg, None, &sig).is_ok(); + 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"); @@ -197,9 +195,10 @@ fn rsa_pss_sha256_mgf1_32_wycheproof_vectors() { // ---- bouncycastle_core trait conformance ------------------------------------------------------ -fn fixed_keypair() -> Result<(RSA2048PublicKey, RSA2048PrivateKey), SignatureError> { +fn fixed_keypair() +-> Result<(RsaPublicComponents, RsaPrivateComponents), SignatureError> { let sk = wycheproof_key(); - let pk = RSA2048PublicKey::new(sk.n(), 0x10001)?; + let pk = RsaPublicComponents::::new(sk.n(), 0x10001)?; Ok((pk, sk)) } @@ -209,8 +208,8 @@ fn fixed_keypair() -> Result<(RSA2048PublicKey, RSA2048PrivateKey), SignatureErr #[test] fn pss_sha256_trait_conformance_suite() { TestFrameworkSignature::new(false) - .test_signature::( - fixed_keypair, true, + .test_signature::, RsaPrivateKey, SIG_LEN>( + || fixed_keypair().map(|(pk, sk)| (pk.into_key::(), sk.into_key::())), true, ); } @@ -258,28 +257,33 @@ fn set_salt_fixes_the_salt_on_the_streaming_path() { let msg = b"fixed salt, streamed in two chunks"; let salt = [0x42u8; 32]; - let mut signer = - SigningKey::::create_signer(&sk, &mut DefaultRNG::default(), None) - .unwrap(); + 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_pss::sign_from_hash_with_salt::(&sk, &digest, &salt).unwrap(); + let expected = rsassa::sign_from_hash_with_salt::, 256>( + &sk.key::>(), + &digest, + &salt, + ) + .unwrap(); assert_eq!(sig, expected); - VerifyingKey::::verify(&pk, msg, None, &sig).unwrap(); + pk.key::().verify(msg, None, &sig).unwrap(); + + let sk_rsassa_pss_sha256 = sk.key::(); - let mut fresh = - SigningKey::::create_signer(&sk, &mut DefaultRNG::default(), None) - .unwrap(); + 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 mut verifier = VerifyingKey::::create_verifier(&pk, None).unwrap(); + 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(); } @@ -291,15 +295,14 @@ fn set_salt_fixes_the_salt_on_the_streaming_path() { 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 = - SigningKey::::sign(&sk, &mut FixedRng, msg, None).unwrap(); + 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 = SigningKey::::sign(&sk, &mut rng, msg, None).unwrap(); - let b = SigningKey::::sign(&sk, &mut rng, msg, None).unwrap(); + let a = sk.key::().sign(&mut rng, msg, None).unwrap(); + let b = sk.key::().sign(&mut rng, msg, None).unwrap(); assert_ne!(a, b); - VerifyingKey::::verify(&pk, msg, None, &a).unwrap(); - VerifyingKey::::verify(&pk, msg, None, &b).unwrap(); - assert!(VerifyingKey::::verify(&pk, b"other", None, &a).is_err()); + 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 index 7c063796..986821b0 100644 --- a/crypto/rsa/tests/rsa_3072_pss_shake128_tests.rs +++ b/crypto/rsa/tests/rsa_3072_pss_shake128_tests.rs @@ -9,9 +9,11 @@ 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::rsa_3072::{ - RSA3072PrivateKey, RSA3072PublicKey, RSASSA_PSS_SHAKE128, SIG_LEN, +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; @@ -20,8 +22,8 @@ use std::path::Path; /// 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 mut signer = - SigningKey::<$ty, 384>::create_signer($sk, &mut DefaultRNG::default(), None).unwrap(); + 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() @@ -62,7 +64,7 @@ fn limbs_from_hex(hex: &str) -> [u64; L] { /// 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() -> RSA3072PrivateKey { +fn genuine_key() -> RsaPrivateComponents { let p: [u64; 24] = [ 0xb26d973345bc4c5f, 0x23251a1d29962ca9, 0x554fc3f23d6c9046, 0x89ffe73b1401e9b8, 0xe0b448b454670aca, 0xa73ea5c2413d1da2, 0xe9539bc7a8d3b351, 0x357984fc116af9cb, @@ -103,45 +105,45 @@ fn genuine_key() -> RSA3072PrivateKey { 0xfe6c3600d9b8e9a9, 0x744fac4daabf5488, 0xfbee6ec24b75fbf0, 0x8be552c8be44f139, 0xfb0da96bd423759d, 0xb3443d93e7e8ca62, 0x36fe01b950885ecd, 0x214a1f73130e48b3, ]; - RSA3072PrivateKey::from_crt_components(&p, &q, &d_p, &d_q, &q_inv) + 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 = RSA3072PublicKey::new(sk.n(), 0x10001).unwrap(); + 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"); - VerifyingKey::::verify(&pk, b"the message to sign", None, &sig) + 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!( - VerifyingKey::::verify(&pk, b"a different message", None, &sig) - .is_err() - ); + 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 = RSA3072PublicKey::new(sk.n(), 0x10001).unwrap(); + let pk = RsaPublicComponents::::new(sk.n(), 0x10001).unwrap(); let mut rng = DefaultRNG::default(); - let sig_a = SigningKey::::sign(&sk, &mut rng, b"hello", None) + let sig_a = sk + .key::() + .sign(&mut rng, b"hello", None) .expect("signing must succeed"); - let sig_b = SigningKey::::sign(&sk, &mut rng, b"hello", None) + 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"); - VerifyingKey::::verify(&pk, b"hello", None, &sig_a) - .expect("sig_a must verify"); - VerifyingKey::::verify(&pk, b"hello", None, &sig_b) - .expect("sig_b must verify"); + 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] @@ -160,7 +162,8 @@ fn rsa_pss_3072_shake128_wycheproof_vectors() { 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 = RSA3072PublicKey::new(&n, e).expect("group public key must be valid"); + let pk = + RsaPublicComponents::::new(&n, e).expect("group public key must be valid"); for test in group["tests"].as_array().unwrap() { num_tests += 1; @@ -174,8 +177,7 @@ fn rsa_pss_3072_shake128_wycheproof_vectors() { continue; }; - let verified = - VerifyingKey::::verify(&pk, &msg, None, &sig).is_ok(); + 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"); @@ -197,16 +199,17 @@ fn rsa_pss_3072_shake128_wycheproof_vectors() { // ---- bouncycastle_core trait conformance ------------------------------------------------------ -fn fixed_keypair() -> Result<(RSA3072PublicKey, RSA3072PrivateKey), SignatureError> { +fn fixed_keypair() +-> Result<(RsaPublicComponents, RsaPrivateComponents), SignatureError> { let sk = genuine_key(); - let pk = RSA3072PublicKey::new(sk.n(), 0x10001)?; + let pk = RsaPublicComponents::::new(sk.n(), 0x10001)?; Ok((pk, sk)) } #[test] fn pss_shake128_trait_conformance_suite() { TestFrameworkSignature::new(false) - .test_signature::( - fixed_keypair, 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 index 8afc2828..733cd93d 100644 --- a/crypto/rsa/tests/rsa_3072_tests.rs +++ b/crypto/rsa/tests/rsa_3072_tests.rs @@ -18,10 +18,13 @@ use bouncycastle_core_test_framework::signature::{ }; 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, RSA3072PrivateKey, RSA3072PublicKey, 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, + 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; @@ -31,8 +34,8 @@ use std::path::Path; /// 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 mut signer = - SigningKey::<$ty, 384>::create_signer($sk, &mut DefaultRNG::default(), None).unwrap(); + 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() @@ -70,7 +73,7 @@ fn limbs_from_hex(hex: &str) -> [u64; L] { limbs } -fn genuine_key() -> RSA3072PrivateKey { +fn genuine_key() -> RsaPrivateComponents { let p: [u64; 24] = [ 0xb26d973345bc4c5f, 0x23251a1d29962ca9, 0x554fc3f23d6c9046, 0x89ffe73b1401e9b8, 0xe0b448b454670aca, 0xa73ea5c2413d1da2, 0xe9539bc7a8d3b351, 0x357984fc116af9cb, @@ -111,7 +114,7 @@ fn genuine_key() -> RSA3072PrivateKey { 0xfe6c3600d9b8e9a9, 0x744fac4daabf5488, 0xfbee6ec24b75fbf0, 0x8be552c8be44f139, 0xfb0da96bd423759d, 0xb3443d93e7e8ca62, 0x36fe01b950885ecd, 0x214a1f73130e48b3, ]; - RSA3072PrivateKey::from_crt_components(&p, &q, &d_p, &d_q, &q_inv) + RsaPrivateComponents::::from_crt_components(&p, &q, &d_p, &d_q, &q_inv) .expect("recovered CRT components must be accepted") } @@ -133,12 +136,12 @@ fn pkcs1_v1_5_sig_gen_3072_sha256() { 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 = DeterministicSigningKey::::sign_deterministic( - &sk, &msg, None, - ) - .unwrap_or_else(|e| { - panic!("tcId {tc_id}: signing failed: {e:?}"); - }); + 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); @@ -147,17 +150,11 @@ fn pkcs1_v1_5_sig_gen_3072_sha256() { #[test] fn pkcs1_v1_5_sha384_and_sha512_round_trip() { let sk = genuine_key(); - let pk = RSA3072PublicKey::new(sk.n(), 0x10001).unwrap(); - let sig384 = DeterministicSigningKey::::sign_deterministic( - &sk, b"hello", None, - ) - .unwrap(); - VerifyingKey::::verify(&pk, b"hello", None, &sig384).unwrap(); - let sig512 = DeterministicSigningKey::::sign_deterministic( - &sk, b"hello", None, - ) - .unwrap(); - VerifyingKey::::verify(&pk, b"hello", None, &sig512).unwrap(); + 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, @@ -171,87 +168,81 @@ fn pkcs1_v1_5_sha384_and_sha512_round_trip() { #[test] fn pss_sha256_fixed_salt_round_trips() { let sk = genuine_key(); - let pk = RSA3072PublicKey::new(sk.n(), 0x10001).unwrap(); + 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"); - VerifyingKey::::verify(&pk, b"hello", None, &sig).expect("must verify"); - assert!(VerifyingKey::::verify(&pk, b"goodbye", None, &sig).is_err()); + 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 = RSA3072PublicKey::new(sk.n(), 0x10001).unwrap(); + let pk = RsaPublicComponents::::new(sk.n(), 0x10001).unwrap(); let mut rng = DefaultRNG::default(); - let sig_a = SigningKey::::sign(&sk, &mut rng, b"hello", None) - .expect("signing must succeed"); - let sig_b = SigningKey::::sign(&sk, &mut rng, b"hello", None) - .expect("signing must succeed"); + 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"); - VerifyingKey::::verify(&pk, b"hello", None, &sig_a) - .expect("sig_a must verify"); - VerifyingKey::::verify(&pk, b"hello", None, &sig_b) - .expect("sig_b must verify"); + 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 = RSA3072PublicKey::new(sk.n(), 0x10001).unwrap(); + 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"); - VerifyingKey::::verify(&pk, b"hello", None, &sig).expect("must verify"); - assert!(VerifyingKey::::verify(&pk, b"goodbye", None, &sig).is_err()); + 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 = RSA3072PublicKey::new(sk.n(), 0x10001).unwrap(); + let pk = RsaPublicComponents::::new(sk.n(), 0x10001).unwrap(); let mut rng = DefaultRNG::default(); - let sig_a = SigningKey::::sign(&sk, &mut rng, b"hello", None) - .expect("signing must succeed"); - let sig_b = SigningKey::::sign(&sk, &mut rng, b"hello", None) - .expect("signing must succeed"); + 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"); - VerifyingKey::::verify(&pk, b"hello", None, &sig_a) - .expect("sig_a must verify"); - VerifyingKey::::verify(&pk, b"hello", None, &sig_b) - .expect("sig_b must verify"); + 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 = RSA3072PublicKey::new(sk.n(), 0x10001).unwrap(); + 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"); - VerifyingKey::::verify(&pk, b"hello", None, &sig).expect("must verify"); - assert!(VerifyingKey::::verify(&pk, b"goodbye", None, &sig).is_err()); + 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 = RSA3072PublicKey::new(sk.n(), 0x10001).unwrap(); + let pk = RsaPublicComponents::::new(sk.n(), 0x10001).unwrap(); let mut rng = DefaultRNG::default(); - let sig_a = SigningKey::::sign(&sk, &mut rng, b"hello", None) - .expect("signing must succeed"); - let sig_b = SigningKey::::sign(&sk, &mut rng, b"hello", None) - .expect("signing must succeed"); + 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"); - VerifyingKey::::verify(&pk, b"hello", None, &sig_a) - .expect("sig_a must verify"); - VerifyingKey::::verify(&pk, b"hello", None, &sig_b) - .expect("sig_b must verify"); + 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(&RSA3072PublicKey, &[u8], &[u8; 384]) -> bool, + verify: impl Fn(&RsaPublicComponents, &[u8], &[u8; 384]) -> bool, expected_sha: &str, expected_valid: usize, expected_invalid: usize, @@ -266,7 +257,7 @@ fn run_pkcs1_v1_5_verify_vectors( 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 = RSA3072PublicKey::new(&n, e).unwrap(); + let pk = RsaPublicComponents::::new(&n, e).unwrap(); for test in group["tests"].as_array().unwrap() { let tc_id = test["tcId"].as_u64().unwrap(); @@ -308,9 +299,7 @@ fn run_pkcs1_v1_5_verify_vectors( fn rsa_signature_3072_sha256_wycheproof_vectors() { run_pkcs1_v1_5_verify_vectors( "rsa_signature_3072_sha256_test.json", - |pk, msg, sig| { - VerifyingKey::::verify(pk, msg, None, sig).is_ok() - }, + |pk, msg, sig| pk.key::().verify(msg, None, sig).is_ok(), "SHA-256", 8, 250, @@ -325,9 +314,7 @@ fn rsa_signature_3072_sha256_wycheproof_vectors() { fn rsa_signature_3072_sha384_wycheproof_vectors() { run_pkcs1_v1_5_verify_vectors( "rsa_signature_3072_sha384_test.json", - |pk, msg, sig| { - VerifyingKey::::verify(pk, msg, None, sig).is_ok() - }, + |pk, msg, sig| pk.key::().verify(msg, None, sig).is_ok(), "SHA-384", 7, 251, @@ -342,9 +329,7 @@ fn rsa_signature_3072_sha384_wycheproof_vectors() { fn rsa_signature_3072_sha512_wycheproof_vectors() { run_pkcs1_v1_5_verify_vectors( "rsa_signature_3072_sha512_test.json", - |pk, msg, sig| { - VerifyingKey::::verify(pk, msg, None, sig).is_ok() - }, + |pk, msg, sig| pk.key::().verify(msg, None, sig).is_ok(), "SHA-512", 8, 251, @@ -364,7 +349,7 @@ fn rsa_pss_3072_sha256_mgf1_32_wycheproof_vectors() { 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 = RSA3072PublicKey::new(&n, e).unwrap(); + let pk = RsaPublicComponents::::new(&n, e).unwrap(); for test in group["tests"].as_array().unwrap() { let tc_id = test["tcId"].as_u64().unwrap(); @@ -375,8 +360,7 @@ fn rsa_pss_3072_sha256_mgf1_32_wycheproof_vectors() { num_invalid += 1; continue; }; - let verified = - VerifyingKey::::verify(&pk, &msg, None, &sig).is_ok(); + let verified = pk.key::().verify(&msg, None, &sig).is_ok(); match test["result"].as_str().unwrap() { "valid" => { assert!(verified, "tcId {tc_id}: expected valid"); @@ -396,9 +380,10 @@ fn rsa_pss_3072_sha256_mgf1_32_wycheproof_vectors() { // ---- bouncycastle_core trait conformance ------------------------------------------------------ -fn fixed_keypair() -> Result<(RSA3072PublicKey, RSA3072PrivateKey), SignatureError> { +fn fixed_keypair() +-> Result<(RsaPublicComponents, RsaPrivateComponents), SignatureError> { let sk = genuine_key(); - let pk = RSA3072PublicKey::new(sk.n(), 0x10001)?; + let pk = RsaPublicComponents::::new(sk.n(), 0x10001)?; Ok((pk, sk)) } @@ -407,27 +392,32 @@ fn fixed_keypair() -> Result<(RSA3072PublicKey, RSA3072PrivateKey), SignatureErr #[test] fn pkcs1_v1_5_trait_conformance_suites() { let framework = TestFrameworkSignature::new(false); - framework.test_deterministic_signature::(fixed_keypair, false); - framework.test_deterministic_signature::(fixed_keypair, false); - framework.test_deterministic_signature::(fixed_keypair, 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::( - fixed_keypair, false, + framework.test_signature::, RsaPrivateKey, SIG_LEN>( + || fixed_keypair().map(|(pk, sk)| (pk.into_key::(), sk.into_key::())), false, ); - framework.test_signature::( - fixed_keypair, false, + framework.test_signature::, RsaPrivateKey, SIG_LEN>( + || fixed_keypair().map(|(pk, sk)| (pk.into_key::(), sk.into_key::())), false, ); - framework.test_signature::( - fixed_keypair, 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::(fixed_keypair); + .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 index e31c0bc9..5e70f5be 100644 --- a/crypto/rsa/tests/rsa_4096_pss_shake256_tests.rs +++ b/crypto/rsa/tests/rsa_4096_pss_shake256_tests.rs @@ -7,7 +7,9 @@ use bouncycastle_core::signature_key::{SigningKey, VerifyingKey}; use bouncycastle_core::traits::SignatureSigner; use bouncycastle_hex::decode as hex_decode; use bouncycastle_rng::DefaultRNG; -use bouncycastle_rsa::rsa_4096::{RSA4096PrivateKey, RSA4096PublicKey, RSASSA_PSS_SHAKE256}; +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; @@ -16,8 +18,8 @@ use std::path::Path; /// 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 mut signer = - SigningKey::<$ty, 512>::create_signer($sk, &mut DefaultRNG::default(), None).unwrap(); + 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() @@ -58,7 +60,7 @@ fn limbs_from_hex(hex: &str) -> [u64; L] { /// 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() -> RSA4096PrivateKey { +fn genuine_key() -> RsaPrivateComponents { let p: [u64; 32] = [ 0x5141acd4afd4771f, 0x5857742b7e4032dc, 0xb7a9b97fe5371396, 0x4b1783c5bc91a6dc, 0xaf5d0c912d97b728, 0xeb265a7f28b88976, 0x5e993302aa72f11d, 0xc007ad09d76ae22a, @@ -109,45 +111,45 @@ fn genuine_key() -> RSA4096PrivateKey { 0x748d7b5d94cacd4d, 0xcf634f3a07cea4b7, 0x8dbcca51f4da4379, 0x80774236a54ec9dc, 0x6a1ef00ee582d3d1, 0xdecfb14ca1e80c8e, 0xc78af5f6c807cc99, 0x484ad86e79415ea3, ]; - RSA4096PrivateKey::from_crt_components(&p, &q, &d_p, &d_q, &q_inv) + 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 = RSA4096PublicKey::new(sk.n(), 0x10001).unwrap(); + 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"); - VerifyingKey::::verify(&pk, b"the message to sign", None, &sig) + 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!( - VerifyingKey::::verify(&pk, b"a different message", None, &sig) - .is_err() - ); + 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 = RSA4096PublicKey::new(sk.n(), 0x10001).unwrap(); + let pk = RsaPublicComponents::::new(sk.n(), 0x10001).unwrap(); let mut rng = DefaultRNG::default(); - let sig_a = SigningKey::::sign(&sk, &mut rng, b"hello", None) + let sig_a = sk + .key::() + .sign(&mut rng, b"hello", None) .expect("signing must succeed"); - let sig_b = SigningKey::::sign(&sk, &mut rng, b"hello", None) + 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"); - VerifyingKey::::verify(&pk, b"hello", None, &sig_a) - .expect("sig_a must verify"); - VerifyingKey::::verify(&pk, b"hello", None, &sig_b) - .expect("sig_b must verify"); + 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] @@ -166,7 +168,8 @@ fn rsa_pss_4096_shake256_wycheproof_vectors() { 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 = RSA4096PublicKey::new(&n, e).expect("group public key must be valid"); + let pk = + RsaPublicComponents::::new(&n, e).expect("group public key must be valid"); for test in group["tests"].as_array().unwrap() { num_tests += 1; @@ -180,8 +183,7 @@ fn rsa_pss_4096_shake256_wycheproof_vectors() { continue; }; - let verified = - VerifyingKey::::verify(&pk, &msg, None, &sig).is_ok(); + 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"); @@ -209,18 +211,14 @@ fn rsa_pss_4096_shake256_wycheproof_vectors() { #[test] fn pss_shake256_trait_round_trips() { let sk = genuine_key(); - let pk = RSA4096PublicKey::new(sk.n(), 0x10001).unwrap(); + let pk = RsaPublicComponents::::new(sk.n(), 0x10001).unwrap(); let msg = b"PSS-SHAKE256 at RSA-4096, both APIs"; let from_trait = - SigningKey::::sign(&sk, &mut DefaultRNG::default(), msg, None) - .unwrap(); - VerifyingKey::::verify(&pk, msg, None, &from_trait).unwrap(); - VerifyingKey::::verify(&pk, msg, None, &from_trait).unwrap(); + 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 = - SigningKey::::sign(&sk, &mut DefaultRNG::default(), msg, None) - .unwrap(); - VerifyingKey::::verify(&pk, msg, None, &from_free).unwrap(); - assert!( - VerifyingKey::::verify(&pk, b"other", None, &from_free).is_err() - ); + 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 index b3e0eea9..3e8617f7 100644 --- a/crypto/rsa/tests/rsa_4096_tests.rs +++ b/crypto/rsa/tests/rsa_4096_tests.rs @@ -12,19 +12,23 @@ //! against all 8 of that group's real signatures before being pasted here. use bouncycastle_core::errors::SignatureError; -use bouncycastle_core::signature_key::{ - DeterministicSigningKey, SignatureAlgorithm, SigningKey, VerifyingKey, -}; +use bouncycastle_core::signature_key::{DeterministicSigningKey, SigningKey, VerifyingKey}; 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, RSA4096PrivateKey, RSA4096PublicKey, 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, + 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; @@ -34,8 +38,8 @@ use std::path::Path; /// 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 mut signer = - SigningKey::<$ty, 512>::create_signer($sk, &mut DefaultRNG::default(), None).unwrap(); + 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() @@ -73,7 +77,7 @@ fn limbs_from_hex(hex: &str) -> [u64; L] { limbs } -fn genuine_key() -> RSA4096PrivateKey { +fn genuine_key() -> RsaPrivateComponents { let p: [u64; 32] = [ 0x5141acd4afd4771f, 0x5857742b7e4032dc, 0xb7a9b97fe5371396, 0x4b1783c5bc91a6dc, 0xaf5d0c912d97b728, 0xeb265a7f28b88976, 0x5e993302aa72f11d, 0xc007ad09d76ae22a, @@ -124,7 +128,7 @@ fn genuine_key() -> RSA4096PrivateKey { 0x748d7b5d94cacd4d, 0xcf634f3a07cea4b7, 0x8dbcca51f4da4379, 0x80774236a54ec9dc, 0x6a1ef00ee582d3d1, 0xdecfb14ca1e80c8e, 0xc78af5f6c807cc99, 0x484ad86e79415ea3, ]; - RSA4096PrivateKey::from_crt_components(&p, &q, &d_p, &d_q, &q_inv) + RsaPrivateComponents::::from_crt_components(&p, &q, &d_p, &d_q, &q_inv) .expect("recovered CRT components must be accepted") } @@ -146,12 +150,12 @@ fn pkcs1_v1_5_sig_gen_4096_sha256() { 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 = DeterministicSigningKey::::sign_deterministic( - &sk, &msg, None, - ) - .unwrap_or_else(|e| { - panic!("tcId {tc_id}: signing failed: {e:?}"); - }); + 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); @@ -164,22 +168,16 @@ fn pkcs1_v1_5_sig_gen_4096_sha256() { #[test] fn pkcs1_v1_5_sha384_and_sha512_round_trip() { let sk = genuine_key(); - let pk = RSA4096PublicKey::new(sk.n(), 0x10001).unwrap(); - let sig384 = DeterministicSigningKey::::sign_deterministic( - &sk, b"hello", None, - ) - .unwrap(); - VerifyingKey::::verify(&pk, b"hello", None, &sig384).unwrap(); - let sig512 = DeterministicSigningKey::::sign_deterministic( - &sk, b"hello", None, - ) - .unwrap(); - VerifyingKey::::verify(&pk, b"hello", None, &sig512).unwrap(); + 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(&RSA4096PublicKey, &[u8], &[u8; 512]) -> bool, + verify: impl Fn(&RsaPublicComponents, &[u8], &[u8; 512]) -> bool, expected_sha: &str, expected_valid: usize, expected_invalid: usize, @@ -194,7 +192,7 @@ fn run_pkcs1_v1_5_verify_vectors( 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 = RSA4096PublicKey::new(&n, e).unwrap(); + let pk = RsaPublicComponents::::new(&n, e).unwrap(); for test in group["tests"].as_array().unwrap() { let tc_id = test["tcId"].as_u64().unwrap(); @@ -236,9 +234,7 @@ fn run_pkcs1_v1_5_verify_vectors( fn rsa_signature_4096_sha256_wycheproof_vectors() { run_pkcs1_v1_5_verify_vectors( "rsa_signature_4096_sha256_test.json", - |pk, msg, sig| { - VerifyingKey::::verify(pk, msg, None, sig).is_ok() - }, + |pk, msg, sig| pk.key::().verify(msg, None, sig).is_ok(), "SHA-256", 7, 250, @@ -249,9 +245,7 @@ fn rsa_signature_4096_sha256_wycheproof_vectors() { fn rsa_signature_4096_sha384_wycheproof_vectors() { run_pkcs1_v1_5_verify_vectors( "rsa_signature_4096_sha384_test.json", - |pk, msg, sig| { - VerifyingKey::::verify(pk, msg, None, sig).is_ok() - }, + |pk, msg, sig| pk.key::().verify(msg, None, sig).is_ok(), "SHA-384", 7, 251, @@ -262,9 +256,7 @@ fn rsa_signature_4096_sha384_wycheproof_vectors() { fn rsa_signature_4096_sha512_wycheproof_vectors() { run_pkcs1_v1_5_verify_vectors( "rsa_signature_4096_sha512_test.json", - |pk, msg, sig| { - VerifyingKey::::verify(pk, msg, None, sig).is_ok() - }, + |pk, msg, sig| pk.key::().verify(msg, None, sig).is_ok(), "SHA-512", 7, 251, @@ -273,7 +265,7 @@ fn rsa_signature_4096_sha512_wycheproof_vectors() { fn run_pss_verify_vectors( filename: &str, - verify: impl Fn(&RSA4096PublicKey, &[u8], &[u8; 512]) -> bool, + verify: impl Fn(&RsaPublicComponents, &[u8], &[u8; 512]) -> bool, expected_sha: &str, expected_slen: u64, expected_valid: usize, @@ -290,7 +282,7 @@ fn run_pss_verify_vectors( 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 = RSA4096PublicKey::new(&n, e).unwrap(); + let pk = RsaPublicComponents::::new(&n, e).unwrap(); for test in group["tests"].as_array().unwrap() { let tc_id = test["tcId"].as_u64().unwrap(); @@ -323,7 +315,7 @@ fn run_pss_verify_vectors( fn rsa_pss_4096_sha256_mgf1_32_wycheproof_vectors() { run_pss_verify_vectors( "rsa_pss_4096_sha256_mgf1_32_test.json", - |pk, msg, sig| VerifyingKey::::verify(pk, msg, None, sig).is_ok(), + |pk, msg, sig| pk.key::().verify(msg, None, sig).is_ok(), "SHA-256", 32, 63, @@ -335,7 +327,7 @@ fn rsa_pss_4096_sha256_mgf1_32_wycheproof_vectors() { fn rsa_pss_4096_sha384_mgf1_48_wycheproof_vectors() { run_pss_verify_vectors( "rsa_pss_4096_sha384_mgf1_48_test.json", - |pk, msg, sig| VerifyingKey::::verify(pk, msg, None, sig).is_ok(), + |pk, msg, sig| pk.key::().verify(msg, None, sig).is_ok(), "SHA-384", 48, 95, @@ -347,7 +339,7 @@ fn rsa_pss_4096_sha384_mgf1_48_wycheproof_vectors() { fn rsa_pss_4096_sha512_mgf1_64_wycheproof_vectors() { run_pss_verify_vectors( "rsa_pss_4096_sha512_mgf1_64_test.json", - |pk, msg, sig| VerifyingKey::::verify(pk, msg, None, sig).is_ok(), + |pk, msg, sig| pk.key::().verify(msg, None, sig).is_ok(), "SHA-512", 64, 132, @@ -364,89 +356,84 @@ fn rsa_pss_4096_sha512_mgf1_64_wycheproof_vectors() { #[test] fn pss_sha256_fixed_salt_round_trips() { let sk = genuine_key(); - let pk = RSA4096PublicKey::new(sk.n(), 0x10001).unwrap(); + 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"); - VerifyingKey::::verify(&pk, b"hello", None, &sig).expect("must verify"); - assert!(VerifyingKey::::verify(&pk, b"goodbye", None, &sig).is_err()); + 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 = RSA4096PublicKey::new(sk.n(), 0x10001).unwrap(); + let pk = RsaPublicComponents::::new(sk.n(), 0x10001).unwrap(); let mut rng = DefaultRNG::default(); - let sig_a = SigningKey::::sign(&sk, &mut rng, b"hello", None) - .expect("signing must succeed"); - let sig_b = SigningKey::::sign(&sk, &mut rng, b"hello", None) - .expect("signing must succeed"); + 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"); - VerifyingKey::::verify(&pk, b"hello", None, &sig_a) - .expect("sig_a must verify"); - VerifyingKey::::verify(&pk, b"hello", None, &sig_b) - .expect("sig_b must verify"); + 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 = RSA4096PublicKey::new(sk.n(), 0x10001).unwrap(); + 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"); - VerifyingKey::::verify(&pk, b"hello", None, &sig).expect("must verify"); - assert!(VerifyingKey::::verify(&pk, b"goodbye", None, &sig).is_err()); + 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 = RSA4096PublicKey::new(sk.n(), 0x10001).unwrap(); + let pk = RsaPublicComponents::::new(sk.n(), 0x10001).unwrap(); let mut rng = DefaultRNG::default(); - let sig_a = SigningKey::::sign(&sk, &mut rng, b"hello", None) - .expect("signing must succeed"); - let sig_b = SigningKey::::sign(&sk, &mut rng, b"hello", None) - .expect("signing must succeed"); + 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"); - VerifyingKey::::verify(&pk, b"hello", None, &sig_a) - .expect("sig_a must verify"); - VerifyingKey::::verify(&pk, b"hello", None, &sig_b) - .expect("sig_b must verify"); + 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 = RSA4096PublicKey::new(sk.n(), 0x10001).unwrap(); + 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"); - VerifyingKey::::verify(&pk, b"hello", None, &sig).expect("must verify"); - assert!(VerifyingKey::::verify(&pk, b"goodbye", None, &sig).is_err()); + 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 = RSA4096PublicKey::new(sk.n(), 0x10001).unwrap(); + let pk = RsaPublicComponents::::new(sk.n(), 0x10001).unwrap(); let mut rng = DefaultRNG::default(); - let sig_a = SigningKey::::sign(&sk, &mut rng, b"hello", None) - .expect("signing must succeed"); - let sig_b = SigningKey::::sign(&sk, &mut rng, b"hello", None) - .expect("signing must succeed"); + 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"); - VerifyingKey::::verify(&pk, b"hello", None, &sig_a) - .expect("sig_a must verify"); - VerifyingKey::::verify(&pk, b"hello", None, &sig_b) - .expect("sig_b must verify"); + 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<(RSA4096PublicKey, RSA4096PrivateKey), SignatureError> { +fn fixed_keypair() +-> Result<(RsaPublicComponents, RsaPrivateComponents), SignatureError> { let sk = genuine_key(); - let pk = RSA4096PublicKey::new(sk.n(), 0x10001)?; + let pk = RsaPublicComponents::::new(sk.n(), 0x10001)?; Ok((pk, sk)) } @@ -457,52 +444,54 @@ fn fixed_keypair() -> Result<(RSA4096PublicKey, RSA4096PrivateKey), SignatureErr /// 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::(fixed_keypair, false); + 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::( - fixed_keypair, 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::(fixed_keypair); + .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: &RSA4096PublicKey, sk: &RSA4096PrivateKey) -where - RSA4096PrivateKey: SigningKey, - RSA4096PublicKey: VerifyingKey, -{ +fn pss_round_trip>( + pk: &RsaPublicComponents, + sk: &RsaPrivateComponents, +) { let msg = b"RSA-4096 trait round trip"; let mut rng = DefaultRNG::default(); - let sig = SigningKey::::sign(sk, &mut rng, msg, None).unwrap(); - VerifyingKey::::verify(pk, msg, None, &sig).unwrap(); - let mut signer = SigningKey::::create_signer(sk, &mut rng, None).unwrap(); + 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..]); - VerifyingKey::::verify(pk, msg, None, &signer.do_final().unwrap()).unwrap(); - assert!(VerifyingKey::::verify(pk, b"a different message", None, &sig).is_err()); + 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: &RSA4096PublicKey, sk: &RSA4096PrivateKey) -where - RSA4096PrivateKey: DeterministicSigningKey, - RSA4096PublicKey: VerifyingKey, -{ +fn pkcs1_round_trip>( + pk: &RsaPublicComponents, + sk: &RsaPrivateComponents, +) { let msg = b"RSA-4096 trait round trip"; - let sig = DeterministicSigningKey::::sign_deterministic(sk, msg, None).unwrap(); - VerifyingKey::::verify(pk, msg, None, &sig).unwrap(); - let mut signer = - DeterministicSigningKey::::create_signer_deterministic(sk, None).unwrap(); + 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!(VerifyingKey::::verify(pk, b"a different message", None, &sig).is_err()); + assert!(pk.key::().verify(b"a different message", None, &sig).is_err()); } #[test] diff --git a/crypto/rsa/tests/rsa_8192_tests.rs b/crypto/rsa/tests/rsa_8192_tests.rs index 4445cb5e..b6083678 100644 --- a/crypto/rsa/tests/rsa_8192_tests.rs +++ b/crypto/rsa/tests/rsa_8192_tests.rs @@ -21,19 +21,23 @@ //! Wycheproof encodes for this hash is checked -- just not every repetition of it. use bouncycastle_core::errors::SignatureError; -use bouncycastle_core::signature_key::{ - DeterministicSigningKey, SignatureAlgorithm, SigningKey, VerifyingKey, -}; +use bouncycastle_core::signature_key::{DeterministicSigningKey, SigningKey, VerifyingKey}; 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, RSA8192PrivateKey, RSA8192PublicKey, 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, + 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; @@ -44,8 +48,8 @@ use std::path::Path; /// 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 mut signer = - SigningKey::<$ty, 1024>::create_signer($sk, &mut DefaultRNG::default(), None).unwrap(); + 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() @@ -84,7 +88,7 @@ fn limbs_from_hex(hex: &str) -> [u64; L] { } /// The fresh, self-generated key used for the BC Java cross-check and for self-consistency. -fn genuine_key() -> RSA8192PrivateKey { +fn genuine_key() -> RsaPrivateComponents { let p: [u64; 64] = [ 0xa9a87892c469b1e5, 0x038c3f4efcb198ac, 0xed4f14df1b8a1e1f, 0xef2330d78ee73020, 0xd3093ddaf276904c, 0x94a438d69aeaff23, 0x48dbb3d700ad58ed, 0xbbd763b5346ff916, @@ -175,7 +179,7 @@ fn genuine_key() -> RSA8192PrivateKey { 0xd1aac2fe108f98c0, 0x1e799537a42b3060, 0xdbcce6fc287e449b, 0x1985969e5afbc524, 0x61ba61f820f83597, 0x65c8523f0767bccc, 0xde04e1644a214f9a, 0x9748f8d853be7131, ]; - RSA8192PrivateKey::from_crt_components(&p, &q, &d_p, &d_q, &q_inv) + RsaPrivateComponents::::from_crt_components(&p, &q, &d_p, &d_q, &q_inv) .expect("self-generated CRT components must be accepted") } @@ -187,46 +191,41 @@ const BC_JAVA_PSS_SHA256_SIG: &str = "71c1b3dd982fd6e1e8be1e20c8a4d42fbe6a8b204a #[test] fn pkcs1_v1_5_matches_bc_java_byte_for_byte() { let sk = genuine_key(); - let sig256 = DeterministicSigningKey::::sign_deterministic( - &sk, b"hello", None, - ) - .unwrap(); + let sig256 = sk.key::().sign_deterministic(b"hello", None).unwrap(); assert_eq!(sig256.to_vec(), hex_decode(BC_JAVA_SHA256_SIG).unwrap()); - let sig384 = DeterministicSigningKey::::sign_deterministic( - &sk, b"hello", None, - ) - .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 = DeterministicSigningKey::::sign_deterministic( - &sk, b"hello", None, - ) - .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 = RSA8192PublicKey::new(sk.n(), 0x10001).unwrap(); + 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(); - VerifyingKey::::verify(&pk, b"hello", None, &sig256) + pk.key::() + .verify(b"hello", None, &sig256) .expect("BC Java's SHA-256 sig must verify"); - VerifyingKey::::verify(&pk, b"hello", None, &sig384) + pk.key::() + .verify(b"hello", None, &sig384) .expect("BC Java's SHA-384 sig must verify"); - VerifyingKey::::verify(&pk, b"hello", None, &sig512) + 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 = RSA8192PublicKey::new(sk.n(), 0x10001).unwrap(); + let pk = RsaPublicComponents::::new(sk.n(), 0x10001).unwrap(); let sig: [u8; 1024] = hex_decode(BC_JAVA_PSS_SHA256_SIG).unwrap().try_into().unwrap(); - VerifyingKey::::verify(&pk, b"hello", None, &sig) + pk.key::() + .verify(b"hello", None, &sig) .expect("BC Java's PSS/SHA-256 signature (default salt length = hLen) must verify"); } @@ -239,85 +238,76 @@ fn pss_verifies_bc_java_sha256_signature() { #[test] fn pss_sha256_fixed_salt_round_trips() { let sk = genuine_key(); - let pk = RSA8192PublicKey::new(sk.n(), 0x10001).unwrap(); + 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"); - VerifyingKey::::verify(&pk, b"hello", None, &sig) - .expect("must verify"); - assert!(VerifyingKey::::verify(&pk, b"goodbye", None, &sig).is_err()); + 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 = RSA8192PublicKey::new(sk.n(), 0x10001).unwrap(); + let pk = RsaPublicComponents::::new(sk.n(), 0x10001).unwrap(); let mut rng = DefaultRNG::default(); - let sig_a = SigningKey::::sign(&sk, &mut rng, b"hello", None) - .expect("signing must succeed"); - let sig_b = SigningKey::::sign(&sk, &mut rng, b"hello", None) - .expect("signing must succeed"); + 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"); - VerifyingKey::::verify(&pk, b"hello", None, &sig_a) - .expect("sig_a must verify"); - VerifyingKey::::verify(&pk, b"hello", None, &sig_b) - .expect("sig_b must verify"); + 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 = RSA8192PublicKey::new(sk.n(), 0x10001).unwrap(); + 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"); - VerifyingKey::::verify(&pk, b"hello", None, &sig) - .expect("must verify"); - assert!(VerifyingKey::::verify(&pk, b"goodbye", None, &sig).is_err()); + 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 = RSA8192PublicKey::new(sk.n(), 0x10001).unwrap(); + let pk = RsaPublicComponents::::new(sk.n(), 0x10001).unwrap(); let mut rng = DefaultRNG::default(); - let sig_a = SigningKey::::sign(&sk, &mut rng, b"hello", None) - .expect("signing must succeed"); - let sig_b = SigningKey::::sign(&sk, &mut rng, b"hello", None) - .expect("signing must succeed"); + 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"); - VerifyingKey::::verify(&pk, b"hello", None, &sig_a) - .expect("sig_a must verify"); - VerifyingKey::::verify(&pk, b"hello", None, &sig_b) - .expect("sig_b must verify"); + 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 = RSA8192PublicKey::new(sk.n(), 0x10001).unwrap(); + 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"); - VerifyingKey::::verify(&pk, b"hello", None, &sig) - .expect("must verify"); - assert!(VerifyingKey::::verify(&pk, b"goodbye", None, &sig).is_err()); + 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 = RSA8192PublicKey::new(sk.n(), 0x10001).unwrap(); + let pk = RsaPublicComponents::::new(sk.n(), 0x10001).unwrap(); let mut rng = DefaultRNG::default(); - let sig_a = SigningKey::::sign(&sk, &mut rng, b"hello", None) - .expect("signing must succeed"); - let sig_b = SigningKey::::sign(&sk, &mut rng, b"hello", None) - .expect("signing must succeed"); + 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"); - VerifyingKey::::verify(&pk, b"hello", None, &sig_a) - .expect("sig_a must verify"); - VerifyingKey::::verify(&pk, b"hello", None, &sig_b) - .expect("sig_b must verify"); + 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 @@ -340,7 +330,7 @@ fn distinct_cases(tests: &[Value]) -> Vec<&Value> { fn run_sampled_pkcs1_v1_5_verify_vectors( filename: &str, - verify: impl Fn(&RSA8192PublicKey, &[u8], &[u8; 1024]) -> bool, + 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"); @@ -349,7 +339,7 @@ fn run_sampled_pkcs1_v1_5_verify_vectors( 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 = RSA8192PublicKey::new(&n, e).unwrap(); + let pk = RsaPublicComponents::::new(&n, e).unwrap(); let tests = group["tests"].as_array().unwrap(); let sample = distinct_cases(tests); @@ -383,9 +373,7 @@ fn run_sampled_pkcs1_v1_5_verify_vectors( fn rsa_signature_8192_sha256_wycheproof_vectors_sampled() { run_sampled_pkcs1_v1_5_verify_vectors( "rsa_signature_8192_sha256_test.json", - |pk, msg, sig| { - VerifyingKey::::verify(pk, msg, None, sig).is_ok() - }, + |pk, msg, sig| pk.key::().verify(msg, None, sig).is_ok(), "SHA-256", ); } @@ -394,9 +382,7 @@ fn rsa_signature_8192_sha256_wycheproof_vectors_sampled() { fn rsa_signature_8192_sha384_wycheproof_vectors_sampled() { run_sampled_pkcs1_v1_5_verify_vectors( "rsa_signature_8192_sha384_test.json", - |pk, msg, sig| { - VerifyingKey::::verify(pk, msg, None, sig).is_ok() - }, + |pk, msg, sig| pk.key::().verify(msg, None, sig).is_ok(), "SHA-384", ); } @@ -405,18 +391,17 @@ fn rsa_signature_8192_sha384_wycheproof_vectors_sampled() { fn rsa_signature_8192_sha512_wycheproof_vectors_sampled() { run_sampled_pkcs1_v1_5_verify_vectors( "rsa_signature_8192_sha512_test.json", - |pk, msg, sig| { - VerifyingKey::::verify(pk, msg, None, sig).is_ok() - }, + |pk, msg, sig| pk.key::().verify(msg, None, sig).is_ok(), "SHA-512", ); } // ---- bouncycastle_core trait conformance ------------------------------------------------------ -fn fixed_keypair() -> Result<(RSA8192PublicKey, RSA8192PrivateKey), SignatureError> { +fn fixed_keypair() +-> Result<(RsaPublicComponents, RsaPrivateComponents), SignatureError> { let sk = genuine_key(); - let pk = RSA8192PublicKey::new(sk.n(), 0x10001)?; + let pk = RsaPublicComponents::::new(sk.n(), 0x10001)?; Ok((pk, sk)) } @@ -425,48 +410,50 @@ fn fixed_keypair() -> Result<(RSA8192PublicKey, RSA8192PrivateKey), SignatureErr /// slower still in a debug build). #[test] fn pkcs1_v1_5_sha256_trait_conformance_suite() { - TestFrameworkSignature::new(false).test_deterministic_signature::(fixed_keypair, false); + 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::(fixed_keypair); + .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: &RSA8192PublicKey, sk: &RSA8192PrivateKey) -where - RSA8192PrivateKey: SigningKey, - RSA8192PublicKey: VerifyingKey, -{ +fn pss_round_trip>( + pk: &RsaPublicComponents, + sk: &RsaPrivateComponents, +) { let msg = b"RSA-8192 trait round trip"; let mut rng = DefaultRNG::default(); - let sig = SigningKey::::sign(sk, &mut rng, msg, None).unwrap(); - VerifyingKey::::verify(pk, msg, None, &sig).unwrap(); - let mut signer = SigningKey::::create_signer(sk, &mut rng, None).unwrap(); + 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..]); - VerifyingKey::::verify(pk, msg, None, &signer.do_final().unwrap()).unwrap(); - assert!(VerifyingKey::::verify(pk, b"a different message", None, &sig).is_err()); + 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: &RSA8192PublicKey, sk: &RSA8192PrivateKey) -where - RSA8192PrivateKey: DeterministicSigningKey, - RSA8192PublicKey: VerifyingKey, -{ +fn pkcs1_round_trip>( + pk: &RsaPublicComponents, + sk: &RsaPrivateComponents, +) { let msg = b"RSA-8192 trait round trip"; - let sig = DeterministicSigningKey::::sign_deterministic(sk, msg, None).unwrap(); - VerifyingKey::::verify(pk, msg, None, &sig).unwrap(); - let mut signer = - DeterministicSigningKey::::create_signer_deterministic(sk, None).unwrap(); + 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!(VerifyingKey::::verify(pk, b"a different message", None, &sig).is_err()); + assert!(pk.key::().verify(b"a different message", None, &sig).is_err()); } #[test] @@ -485,11 +472,8 @@ fn remaining_pairings_trait_round_trips() { #[test] fn trait_matches_bc_java() { let (pk, sk) = fixed_keypair().unwrap(); - let sig = DeterministicSigningKey::::sign_deterministic( - &sk, b"hello", None, - ) - .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(); - VerifyingKey::::verify(&pk, b"hello", None, &pss).unwrap(); + pk.key::().verify(b"hello", None, &pss).unwrap(); } diff --git a/crypto/rsa/tests/rsassa_worker_tests.rs b/crypto/rsa/tests/rsassa_worker_tests.rs index 6cc67293..4db877ac 100644 --- a/crypto/rsa/tests/rsassa_worker_tests.rs +++ b/crypto/rsa/tests/rsassa_worker_tests.rs @@ -5,11 +5,11 @@ use bouncycastle_core::signature_key::{DeterministicSigningKey, SigningKey, Veri use bouncycastle_core::traits::{AlgorithmInfo, HashOneShot}; use bouncycastle_rng::DefaultRNG; use bouncycastle_rsa::RSA2048; -use bouncycastle_rsa::keys::{RsaPrivateKey, RsaPublicKey}; +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_rsa::rsassa_pss_shake::RSASSA_PSS_SHAKE; -use bouncycastle_rsa::{rsassa_pss, rsassa_pss_shake}; use bouncycastle_sha2::SHA256; use bouncycastle_sha3::SHAKE128; @@ -45,9 +45,10 @@ const Q_INV: [u64; 16] = [ 0x9bfc042ee0924b1b, 0x41f956d90fa8a793, 0xee7a87b6483a66ee, 0x2640fbfbcfefb163, ]; -fn key_pair() -> (RsaPublicKey, RsaPrivateKey) { - let sk = RsaPrivateKey::::from_crt_components(&P, &Q, &D_P, &D_Q, &Q_INV).unwrap(); - let pk = RsaPublicKey::::new(sk.n(), 0x10001).unwrap(); +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) } @@ -56,27 +57,30 @@ fn workers_name_their_algorithm() { let (pk, sk) = key_pair(); let mut rng = DefaultRNG::default(); - let signer = DeterministicSigningKey::, 256>::create_signer_deterministic(&sk, None).unwrap(); + 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 verifier = - VerifyingKey::, 256>::create_verifier(&pk, None) - .unwrap(); + 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 signer = - SigningKey::, 256>::create_signer(&sk, &mut rng, None).unwrap(); + 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 verifier = - VerifyingKey::, 256>::create_verifier(&pk, None).unwrap(); + 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 signer = - SigningKey::, 256>::create_signer(&sk, &mut rng, None) - .unwrap(); + let sk_rsassa_pss_shake_rsa2048_shake128 = sk.key::>(); + + let signer = sk_rsassa_pss_shake_rsa2048_shake128.create_signer(&mut rng, None).unwrap(); assert_eq!(signer.alg_name(), "RSASSA-PSS-SHAKE128"); - let verifier = - VerifyingKey::, 256>::create_verifier(&pk, None) - .unwrap(); + let pk_rsassa_pss_shake_rsa2048_shake128 = pk.key::>(); + + let verifier = pk_rsassa_pss_shake_rsa2048_shake128.create_verifier(None).unwrap(); assert_eq!(verifier.alg_name(), "RSASSA-PSS-SHAKE128"); } @@ -89,20 +93,65 @@ fn pss_sign_from_hash_draws_a_fresh_salt_and_verifies() { let mut digest = [0u8; 32]; SHA256::hash_out(b"the message", &mut digest); - let a = rsassa_pss::sign_from_hash::(&sk, &digest, &mut rng).unwrap(); - let b = rsassa_pss::sign_from_hash::(&sk, &digest, &mut rng).unwrap(); + 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_pss::verify_from_hash::(&pk, &digest, &a).unwrap(); - rsassa_pss::verify_from_hash::(&pk, &digest, &b).unwrap(); - assert!(rsassa_pss::verify_from_hash::(&pk, &[0u8; 32], &a).is_err()); + 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_pss_shake::sign_from_hash::(&sk, &digest, &mut rng).unwrap(); - let b = - rsassa_pss_shake::sign_from_hash::(&sk, &digest, &mut rng).unwrap(); + 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_pss_shake::verify_from_hash::(&pk, &digest, &a).unwrap(); - rsassa_pss_shake::verify_from_hash::(&pk, &digest, &b).unwrap(); + 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_tests.rs b/crypto/rsa/tests/rsasve_tests.rs index c8babc0d..a5374178 100644 --- a/crypto/rsa/tests/rsasve_tests.rs +++ b/crypto/rsa/tests/rsasve_tests.rs @@ -155,13 +155,11 @@ macro_rules! rsasve_suite { assert_eq!(sk_out, sk.encode()); assert_eq!(pk.n(), sk.n()); assert_eq!(pk.e(), 65537); - // `Display` is the wrapped signature key type's, unchanged. - let inner = bouncycastle_rsa::keys::RsaPublicKey::::new( - pk.n(), - 65537, - ) - .unwrap(); - assert_eq!(format!("{pk}"), format!("{inner}")); + // `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 diff --git a/mem_usage_benches/src/bench_rsa_mem_usage.rs b/mem_usage_benches/src/bench_rsa_mem_usage.rs index 935dee09..e658f289 100644 --- a/mem_usage_benches/src/bench_rsa_mem_usage.rs +++ b/mem_usage_benches/src/bench_rsa_mem_usage.rs @@ -37,7 +37,14 @@ use bouncycastle::core::traits::{ KEMPrivateKey, KEMPublicKey, SignaturePrivateKey, SignaturePublicKey, }; use bouncycastle::rng::DefaultRNG; -use bouncycastle::rsa::{rsa_1024, rsa_1536, rsa_2048, rsa_3072, rsa_4096, rsa_8192}; +use bouncycastle::rsa::keys::{ + RsaPrivateComponents, RsaPrivateKey, RsaPublicComponents, RsaPublicKey, +}; +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, +}; const MSG: &[u8] = b"peak stack usage of RSA sign/verify, held constant across every modulus size"; @@ -49,19 +56,31 @@ fn print_key_sizes() { println!("\nRSA-1024 (verification only)"); println!("public key on disk (n || e): {} bytes", 132); - println!("size_of: {} bytes", size_of::()); + 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!( + "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!( + "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::() @@ -76,9 +95,15 @@ fn print_key_sizes() { println!("\nRSA-3072"); println!("private key on disk (p||q||dP||dQ||qInv): {} bytes", 960); - println!("size_of: {} bytes", size_of::()); + 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::() @@ -93,9 +118,15 @@ fn print_key_sizes() { println!("\nRSA-4096"); println!("private key on disk (p||q||dP||dQ||qInv): {} bytes", 1280); - println!("size_of: {} bytes", size_of::()); + 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::() @@ -110,9 +141,15 @@ fn print_key_sizes() { println!("\nRSA-8192"); println!("private key on disk (p||q||dP||dQ||qInv): {} bytes", 2560); - println!("size_of: {} bytes", size_of::()); + 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::() @@ -142,7 +179,7 @@ fn bench_1024_verify() { 0xb909dd0f4c6014f2, 0x9c8a5810b6d05990, 0x40760d1f23fe9250, 0x90adb011a919575a, 0x45e48572113cab28, 0xcb9ca9ec12000fc8, 0x91b4fcaf62a14595, 0xac9048a7a4f560af, ]; - let pk = rsa_1024::RSA1024PublicKey::new(&n, 0x10001).unwrap(); + let pk = RsaPublicComponents::::new(&n, 0x10001).unwrap(); let mut sig = [0u8; 128]; sig.copy_from_slice( &bouncycastle::hex::decode( @@ -152,16 +189,14 @@ fn bench_1024_verify() { ); let msg = bouncycastle::hex::decode("0000000000000000000000000000000000000000").unwrap(); - if VerifyingKey::::verify(&pk, &msg, None, &sig) - .is_ok() - { + if pk.key::().verify(&msg, None, &sig).is_ok() { eprintln!("Verification succeeded!"); } else { panic!("Verification failed! -- figure that out"); } } -fn genuine_2048_key() -> rsa_2048::RSA2048PrivateKey { +fn genuine_2048_key() -> RsaPrivateComponents { let p: [u64; 16] = [ 0x0ea36cfb3a5b18f1, 0x48a6e65332119129, 0x110ad9e7b48a1c93, 0x569156b90113e2e9, 0xe79813a575cfad9c, 0x69d659d143ec6f17, 0xe81e6bab5ddaa783, 0xbff1c5b80a69f788, @@ -192,7 +227,7 @@ fn genuine_2048_key() -> rsa_2048::RSA2048PrivateKey { 0xe923e1097c0c562f, 0xc968b48a91c38b5b, 0x933e85179c0320b0, 0x7993d0445f758d51, 0x9bfc042ee0924b1b, 0x41f956d90fa8a793, 0xee7a87b6483a66ee, 0x2640fbfbcfefb163, ]; - rsa_2048::RSA2048PrivateKey::from_crt_components(&p, &q, &d_p, &d_q, &q_inv).unwrap() + 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 @@ -200,41 +235,32 @@ fn genuine_2048_key() -> rsa_2048::RSA2048PrivateKey { /// the modulus width. fn bench_2048_keygen() { eprintln!("RSA-2048/Keygen"); - let (pk, sk) = rsa_2048::keygen(&mut DefaultRNG::default()).unwrap(); - println!("{:x?}", pk.encode()); - println!("{}", sk.encode().len()); + 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 = - DeterministicSigningKey::::sign_deterministic( - &sk, MSG, None, - ) - .unwrap(); + 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 = rsa_2048::RSA2048PublicKey::new(sk.n(), 0x10001).unwrap(); - let sig = - DeterministicSigningKey::::sign_deterministic( - &sk, MSG, None, - ) - .unwrap(); + let pk = RsaPublicComponents::::new(sk.n(), 0x10001).unwrap(); + let sig = sk.key::().sign_deterministic(MSG, None).unwrap(); - if VerifyingKey::::verify(&pk, MSG, None, &sig).is_ok() - { + if pk.key::().verify(MSG, None, &sig).is_ok() { eprintln!("Verification succeeded!"); } else { panic!("Verification failed! -- figure that out"); } } -fn genuine_8192_key() -> rsa_8192::RSA8192PrivateKey { +fn genuine_8192_key() -> RsaPrivateComponents { let p: [u64; 64] = [ 0xa9a87892c469b1e5, 0x038c3f4efcb198ac, 0xed4f14df1b8a1e1f, 0xef2330d78ee73020, 0xd3093ddaf276904c, 0x94a438d69aeaff23, 0x48dbb3d700ad58ed, 0xbbd763b5346ff916, @@ -325,33 +351,23 @@ fn genuine_8192_key() -> rsa_8192::RSA8192PrivateKey { 0xd1aac2fe108f98c0, 0x1e799537a42b3060, 0xdbcce6fc287e449b, 0x1985969e5afbc524, 0x61ba61f820f83597, 0x65c8523f0767bccc, 0xde04e1644a214f9a, 0x9748f8d853be7131, ]; - rsa_8192::RSA8192PrivateKey::from_crt_components(&p, &q, &d_p, &d_q, &q_inv).unwrap() + 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 = - DeterministicSigningKey::::sign_deterministic( - &sk, MSG, None, - ) - .unwrap(); + 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 = rsa_8192::RSA8192PublicKey::new(sk.n(), 0x10001).unwrap(); - let sig = - DeterministicSigningKey::::sign_deterministic( - &sk, MSG, None, - ) - .unwrap(); + let pk = RsaPublicComponents::::new(sk.n(), 0x10001).unwrap(); + let sig = sk.key::().sign_deterministic(MSG, None).unwrap(); - if VerifyingKey::::verify(&pk, MSG, None, &sig) - .is_ok() - { + if pk.key::().verify(MSG, None, &sig).is_ok() { eprintln!("Verification succeeded!"); } else { panic!("Verification failed! -- figure that out"); @@ -363,8 +379,11 @@ fn bench_8192_verify() { fn bench_2048_rsasve_encaps() { eprintln!("RSA-2048/RSASVE encaps"); let sk = genuine_2048_key(); - let pk = rsa_2048::RSA2048PublicKey::new(sk.n(), 0x10001).unwrap(); - let pk = rsa_2048::RSA2048KEMPublicKey::from_bytes(&pk.encode()).unwrap(); + 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()); @@ -374,7 +393,10 @@ fn bench_2048_rsasve_encaps() { /// 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().encode()).unwrap(); + 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(); @@ -386,8 +408,11 @@ fn bench_2048_rsasve_decaps() { fn bench_8192_rsasve_encaps() { eprintln!("RSA-8192/RSASVE encaps"); let sk = genuine_8192_key(); - let pk = rsa_8192::RSA8192PublicKey::new(sk.n(), 0x10001).unwrap(); - let pk = rsa_8192::RSA8192KEMPublicKey::from_bytes(&pk.encode()).unwrap(); + 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()); @@ -397,7 +422,10 @@ fn bench_8192_rsasve_encaps() { /// 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().encode()).unwrap(); + 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(); From 5c31875683ac43ea60c14f7c8ff70c4d023b4aa8 Mon Sep 17 00:00:00 2001 From: David Hook Date: Fri, 13 Nov 2026 11:53:12 +1100 Subject: [PATCH 35/55] =?UTF-8?q?Merging=20fix/rsa-pss-params,=20which=20g?= =?UTF-8?q?ives=20RSASSA-PSS=20its=20parameters=20as=20a=20type=20and=20ma?= =?UTF-8?q?kes=20SHAKE=20a=20hash=20like=20any=20other:=20RFC=208017=20?= =?UTF-8?q?=C2=A79.1=20parameterises=20EMSA-PSS=20by=20the=20hash,=20the?= =?UTF-8?q?=20mask=20generation=20function=20and=20the=20salt=20length,=20?= =?UTF-8?q?and=20the=20crate=20fixed=20MGF1=20over=20the=20hash=20and=20sL?= =?UTF-8?q?en=20=3D=20hLen,=20with=20a=20second=20marker,=20RSASSA=5FPSS?= =?UTF-8?q?=5FSHAKE,=20for=20RFC=208702's=20XOF-as-mask.=20The=20m?= =?UTF-8?q?arker=20is=20now=20RSASSA=5FPSS=20over=20rsassa=5F?= =?UTF-8?q?pss::PssParams=20(the=20salt=20length,=20the=20mask,=20and?= =?UTF-8?q?=20what=20the=20name=20says=20after=20RSASSA-PSS-),=20P?= =?UTF-8?q?=20defaulting=20to=20Conventional,=20which=20reads=20the=20hash?= =?UTF-8?q?'s=20conventional=20pairing=20off=20PssHash,=20a=20trait=20impl?= =?UTF-8?q?emented=20once=20per=20hash=20family:=20MGF1=20over=20the=20has?= =?UTF-8?q?h=20itself=20with=20a=20salt=20one=20output=20long=20for=20SHA2?= =?UTF-8?q?56Internal,=20SHA512Internal=20and=20SHA3Internal=20(=C2=A78.1'?= =?UTF-8?q?s=20recommendation,=20=C2=A79.1=20note=204's=20typical=20length?= =?UTF-8?q?),=20the=20XOF=20as=20the=20mask=20with=20its=20output=20length?= =?UTF-8?q?=20as=20the=20salt=20for=20SHAKEInternal=20(RFC=208702=20=C2=A7?= =?UTF-8?q?3.2.1),=20so=20RSASSA=5FPSS=20is=20RSASSA-?= =?UTF-8?q?PSS-SHAKE128=20and=20a=20SHAKE=20pair=20comes=20from=20generate?= =?UTF-8?q?=5Fpss=5Fsignature=5Fkey=5Fpair::=20like=20a=20SHA-2?= =?UTF-8?q?=20one.=20Spelled=20parameters=20are=20the=20other=20two=20type?= =?UTF-8?q?s:=20Mgf1,=20MGF1=20over=20another=20hash=20an?= =?UTF-8?q?d=20any=20salt=20from=201=20to=2064=20bytes,=20which=20=C2=A78.?= =?UTF-8?q?1=20allows=20and=20Appendix=20A.2.3's=20RSASSA-PSS-params=20car?= =?UTF-8?q?ry,=20named=20-MGF1--;=20and=20NoSalt,=20=C2=A79?= =?UTF-8?q?.1=20note=204's=20zero=20salt,=20which=20makes=20the=20encoding?= =?UTF-8?q?=20a=20function=20of=20the=20key=20and=20message=20alone=20and?= =?UTF-8?q?=20so=20puts=20the=20key=20on=20the=20deterministic=20role=20(s?= =?UTF-8?q?ign=5Fdeterministic,=20create=5Fsigner=5Fdeterministic)=20rathe?= =?UTF-8?q?r=20than=20the=20salted=20one,=20the=20SaltedPss=20/=20Unsalted?= =?UTF-8?q?Pss=20markers=20deciding=20which=20of=20the=20two=20rsassa=20al?= =?UTF-8?q?gorithm=20traits=20a=20marker=20implements.=20A=20key=20is=20fo?= =?UTF-8?q?r=20one=20(H,=20P),=20so=20a=20verifier=20never=20guesses=20the?= =?UTF-8?q?=20mask=20or=20the=20salt=20length,=20and=20a=20conventional=20?= =?UTF-8?q?key=20rejects=20a=20zero-salt=20or=20short-salt=20signature=20o?= =?UTF-8?q?ver=20the=20same=20material.=20emsa=5Fpss=20is=20written=20once?= =?UTF-8?q?=20over=20H=20and=20P;=20emsa=5Fpss=5Fshake,=20rsassa=5Fpss=5Fs?= =?UTF-8?q?hake,=20the=20RSASSA=5FPSS=5FSHAKE=20alias=20and=20generate=5Fp?= =?UTF-8?q?ss=5Fshake=5Fsignature=5Fkey=5Fpair=20are=20gone,=20generate=5F?= =?UTF-8?q?pss=5Fsignature=5Fkey=5Fpair=5Fwith::=20added=20for=20t?= =?UTF-8?q?he=20spelled=20forms,=20and=20the=20signer's=20set=5Fsalt=20tak?= =?UTF-8?q?es=20[u8;=20A::SALT=5FLEN].=20The=20strength=20stays=20min(size?= =?UTF-8?q?,=20H):=20the=20mask's=20hash=20does=20not=20enter=20the=20proo?= =?UTF-8?q?f=20(=C2=A78.1).=20utils=20gains=20ConstStr::decimal,=20the=20d?= =?UTF-8?q?igits=20of=20a=20number=20for=20a=20name,=20with=20its=20tests.?= =?UTF-8?q?=20The=20CLI's=20only=20change=20is=20the=20generator=20name;?= =?UTF-8?q?=20the=20per-size=20aliases=20and=20every=20command=20are=20as?= =?UTF-8?q?=20before.=20Tests:=20tests/rsa=5F2048=5Fpss=5Fparams=5Ftests.r?= =?UTF-8?q?s=20runs=20Wycheproof's=20rsa=5Fpss=5F2048=5Fsha512=5Fmgf1sha25?= =?UTF-8?q?6=5F32=5Fparams=5Ftest.json=20(178=20vectors,=20132=20valid=20a?= =?UTF-8?q?nd=2046=20invalid)=20under=20RSASSA=5FPSS>=20and=20rsa=5Fpss=5F2048=5Fsha256=5Fmgf1=5F?= =?UTF-8?q?0=5Ftest.json=20(103=20vectors,=2061=20valid=20and=2042=20inval?= =?UTF-8?q?id)=20under=20RSASSA=5FPSS>?= =?UTF-8?q?,=20the=20names,=20the=20strengths=20against=20the=20size's=20a?= =?UTF-8?q?nd=20the=20hash's,=20each=20family's=20conventional=20mask=20an?= =?UTF-8?q?d=20salt=20length,=20no-salt=20signing=20deterministic=20and=20?= =?UTF-8?q?reproduced=20through=20the=20streaming=20signer,=20a=2016-byte?= =?UTF-8?q?=20salt=20pinned=20through=20set=5Fsalt,=20the=20parameters=20n?= =?UTF-8?q?ot=20interchangeable,=20and=20the=20generator=20with=20spelled?= =?UTF-8?q?=20parameters;=20keys=5Ftests=20checks=20the=20typed=20keys'=20?= =?UTF-8?q?e,=20Debug=20and=20PartialEq,=20the=20misses=20of=20the=20previ?= =?UTF-8?q?ous=20squash's=20run;=20the=20SHAKE=20suites=20and=20rsassa=5Fw?= =?UTF-8?q?orker=5Ftests=20use=20the=20one=20marker.=20Verified:=20the=20r?= =?UTF-8?q?sa=20suite,=20the=20utils=20suite,=20the=20rsa=20doctests,=20th?= =?UTF-8?q?e=20rsa=20CLI=20tests,=20the=20all-targets=20build,=20nightly?= =?UTF-8?q?=20rustfmt,=20clippy=20adding=20nothing=20on=20the=20changed=20?= =?UTF-8?q?lines,=20rustdoc=20with=20warnings=20denied=20apart=20from=20mo?= =?UTF-8?q?dexp.rs's=20pre-existing=20private-item=20links.=20Mutants=20on?= =?UTF-8?q?=20apollo,=20scoped=20to=20keys.rs,=20rsassa=5Fpss.rs,=20emsa?= =?UTF-8?q?=5Fpss.rs,=20rsassa.rs=20and=20size.rs=20against=20the=20signat?= =?UTF-8?q?ure=20suites=20at=202048=20and=20the=20verify-only=20sizes=20al?= =?UTF-8?q?one=20(the=20KEM=20suites=20left=20out,=20which=20is=20what=20m?= =?UTF-8?q?akes=20the=20run=2019=20minutes=20rather=20than=2032):=20481=20?= =?UTF-8?q?(187=20caught,=20264=20unviable,=20no=20timeouts,=2030=20missed?= =?UTF-8?q?,=20of=20which=20min=5Fstrength's=20comparison=20and=20the=20SH?= =?UTF-8?q?A-512=20and=20SHA-3=20masks=20emptied=20were=20then=20caught=20?= =?UTF-8?q?by=20the=20two=20test=20commits=20in=20a=20targeted=20re-run,?= =?UTF-8?q?=20leaving=2027:=20emsa=5Fpss's=20buffer-size=20arithmetic=20ov?= =?UTF-8?q?er=20MAX=5FHASH=5FLEN=20and=20its=20step=203=20length=20check?= =?UTF-8?q?=20that=20no=20modulus=20here=20reaches,=20as=20before;=20size.?= =?UTF-8?q?rs's=20check=5Flengths=20const=20assertion=20and=20is=5Fless=20?= =?UTF-8?q?at=20the=20two=20verify-only=20sizes,=20as=20before;=20and=20ke?= =?UTF-8?q?ys.rs's=20modulus=5Fstrength=20and=20size.rs's=20is=5Fless=20an?= =?UTF-8?q?d=20half=5Flimbs=5Ffrom=5Fbe=5Fbytes=20at=203072,=204096=20and?= =?UTF-8?q?=208192,=20which=20only=20the=20RSASVE=20suites=20reach=20and?= =?UTF-8?q?=20which=20the=20previous=20squash's=20run,=20with=20those=20su?= =?UTF-8?q?ites,=20caught);=20utils=20const=5Fstr.rs=2039=20(19=20caught,?= =?UTF-8?q?=2019=20unviable,=201=20timeout:=20the=20copy=20loop's=20increm?= =?UTF-8?q?ent=20made=20a=20no-op,=20so=20const=20evaluation=20never=20fin?= =?UTF-8?q?ishes=20and=20the=20build=20never=20completes,=20a=20kill=20in?= =?UTF-8?q?=20effect).?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Assisted-by: Claude:claude-mythos-5-1 --- cli/src/rsa_cmd.rs | 6 +- crypto/rsa/src/emsa_pss.rs | 169 +++++++++-- crypto/rsa/src/emsa_pss_shake.rs | 240 ---------------- crypto/rsa/src/lib.rs | 34 ++- crypto/rsa/src/rsa_2048.rs | 3 +- crypto/rsa/src/rsa_3072.rs | 3 +- crypto/rsa/src/rsa_4096.rs | 3 +- crypto/rsa/src/rsassa.rs | 34 +-- crypto/rsa/src/rsassa_pss.rs | 216 ++++++++++++-- crypto/rsa/src/rsassa_pss_shake.rs | 60 ---- crypto/rsa/src/size.rs | 27 +- crypto/rsa/tests/keys_tests.rs | 27 ++ crypto/rsa/tests/rsa_2048_pss_params_tests.rs | 264 ++++++++++++++++++ .../rsa/tests/rsa_2048_pss_shake128_tests.rs | 9 +- crypto/rsa/tests/rsassa_worker_tests.rs | 25 +- crypto/utils/src/const_str.rs | 25 ++ crypto/utils/tests/const_str_tests.rs | 18 ++ 17 files changed, 747 insertions(+), 416 deletions(-) delete mode 100644 crypto/rsa/src/emsa_pss_shake.rs delete mode 100644 crypto/rsa/src/rsassa_pss_shake.rs create mode 100644 crypto/rsa/tests/rsa_2048_pss_params_tests.rs diff --git a/cli/src/rsa_cmd.rs b/cli/src/rsa_cmd.rs index 999fc4c8..5d315bae 100644 --- a/cli/src/rsa_cmd.rs +++ b/cli/src/rsa_cmd.rs @@ -450,7 +450,7 @@ pub(crate) fn rsa_2048_cmd( (RSAScheme::Pss, RSAHash::Shake128) => { rsa_pss_cmd::( action, - RSA2048::generate_pss_shake_signature_key_pair::, + RSA2048::generate_pss_signature_key_pair::, skfile, pkfile, sigfile, @@ -548,7 +548,7 @@ pub(crate) fn rsa_3072_cmd( (RSAScheme::Pss, RSAHash::Shake128) => { rsa_pss_cmd::( action, - RSA3072::generate_pss_shake_signature_key_pair::, + RSA3072::generate_pss_signature_key_pair::, skfile, pkfile, sigfile, @@ -646,7 +646,7 @@ pub(crate) fn rsa_4096_cmd( (RSAScheme::Pss, RSAHash::Shake256) => { rsa_pss_cmd::( action, - RSA4096::generate_pss_shake_signature_key_pair::, + RSA4096::generate_pss_signature_key_pair::, skfile, pkfile, sigfile, diff --git a/crypto/rsa/src/emsa_pss.rs b/crypto/rsa/src/emsa_pss.rs index e812af8d..17e9c6a5 100644 --- a/crypto/rsa/src/emsa_pss.rs +++ b/crypto/rsa/src/emsa_pss.rs @@ -1,4 +1,7 @@ -//! EMSA-PSS (RFC 8017 §9.1): probabilistic signature encoding, built on [`crate::mgf1`]. +//! 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 //! @@ -10,7 +13,8 @@ //! 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, mgf1}; +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` @@ -23,16 +27,21 @@ use bouncycastle_core::traits::{HashAlgParams, HashOneShot}; /// 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 = H::OUTPUT_LEN` bytes here, the "typical" choice -/// of §9.1 note 4), 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( +/// `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] { +) -> [u8; K_LEN] +where + H: HashOneShot + HashAlgParams, + P: PssParams, +{ let h_len = H::OUTPUT_LEN; - let s_len = salt.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" @@ -51,9 +60,10 @@ pub fn emsa_pss_encode_from_hash(&h[..h_len], &mut db_mask[..db_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]; @@ -67,13 +77,14 @@ pub fn emsa_pss_encode_from_hash( - m_hash: &[u8], - em: &[u8; K_LEN], -) -> bool { +/// `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 = h_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 { @@ -95,7 +106,7 @@ pub fn emsa_pss_verify_from_hash(h, &mut db[..db_len]); + P::mask(h, &mut db[..db_len]); for i in 0..db_len { db[i] ^= masked_db[i]; } @@ -129,7 +140,9 @@ mod tests { //! 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, @@ -164,11 +177,11 @@ mod tests { } fn encode(message: &[u8], salt: &[u8; 32]) -> [u8; 256] { - emsa_pss_encode_from_hash::(&m_hash(message), salt) + 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) + emsa_pss_verify_from_hash::(&m_hash(message), em) } #[test] @@ -236,4 +249,122 @@ mod tests { 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/emsa_pss_shake.rs b/crypto/rsa/src/emsa_pss_shake.rs deleted file mode 100644 index d0ee936b..00000000 --- a/crypto/rsa/src/emsa_pss_shake.rs +++ /dev/null @@ -1,240 +0,0 @@ -//! EMSA-PSS with a SHAKE hash and native-SHAKE mask generation (RFC 8702 §3.2.1), rather than -//! MGF1: RFC 8017's own EMSA-PSS-ENCODE/VERIFY (§9.1), but per RFC 8702 §3.2.1 "the SHAKEs MUST be -//! used natively as the MGF, instead of the MGF1 algorithm ... In other words, the MGF is defined -//! as the SHAKE128 or SHAKE256 with input being the mgfSeed". A SHAKE (`X: XOF`) can already -//! produce an arbitrary-length output directly from one absorb, so this module has no counterpart -//! to [`crate::mgf1`] at all -- the "mask generation function" step is just `X::default().xof_out` -//! on the seed, one call instead of MGF1's counter loop. -//! -//! Otherwise this is [`crate::emsa_pss`] with `X` standing in for the hash: same steps, same -//! `8 * K_LEN - emBits == 1` simplification (see that module's docs) for the same reason (every -//! modulus size here is a whole number of 64-bit limbs). RFC 8702 §3.2.1 also fixes the hash -//! output length `H_LEN` and salt length `S_LEN` to be equal (32 bytes for SHAKE128, 64 for -//! SHAKE256) -- already this crate's own "typical" salt-length convention for MGF1-based PSS, so -//! no new relationship needs stating. - -use crate::mgf1::MAX_HASH_LEN; -use bouncycastle_core::traits::{HashAlgParams, HashOneShot, XOF}; - -/// EMSA-PSS-ENCODE (RFC 8017 §9.1.1) from step 3 onward with the mask generation function -/// replaced by native SHAKE output (RFC 8702 §3.2.1), given steps 1-2's `mHash = Hash(M)` by the -/// caller exactly as [`crate::emsa_pss::emsa_pss_encode_from_hash`] is. See the module docs for -/// `emBits` and the salt argument. -/// EMSA-PSS-ENCODE (RFC 8017 §9.1.1) with the XOF `X` as both the hash and the mask generation -/// function (RFC 8702 §3.2.1), from the message hash `m_hash` (`X::OUTPUT_LEN` bytes, the -/// output length §3.2.1 fixes for the XOF) and the salt (`sLen = X::OUTPUT_LEN`), into the -/// `K_LEN`-byte `EM`. -pub fn emsa_pss_encode_shake_from_hash( - m_hash: &[u8], - salt: &[u8], -) -> [u8; K_LEN] { - let h_len = X::OUTPUT_LEN; - let s_len = salt.len(); - debug_assert_eq!(m_hash.len(), h_len, "emsa_pss_encode_shake: mHash is one output"); - debug_assert!( - K_LEN >= h_len + s_len + 2, - "emsa_pss_encode_shake: 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]; - X::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 SHAKE itself in place of MGF1 (RFC 8702 - // §3.2.1), then clear the top bit (see module docs). - let mut db_mask = [0u8; K_LEN]; - X::default().xof_out(&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) with the XOF `X` as hash and mask (RFC 8702 §3.2.1), of -/// the `K_LEN`-byte `em` against the message hash `m_hash`, with `sLen = X::OUTPUT_LEN`. -pub fn emsa_pss_verify_shake_from_hash( - m_hash: &[u8], - em: &[u8; K_LEN], -) -> bool { - let h_len = X::OUTPUT_LEN; - let s_len = h_len; - debug_assert_eq!(m_hash.len(), h_len, "emsa_pss_verify_shake: mHash is one output"); - 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]; - X::default().xof_out(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]; - X::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_shake_from_hash`/`emsa_pss_verify_shake_from_hash` are crate-private - //! (only [`crate::rsassa_pss_shake`] 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 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::*; - - 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, - ]; - - 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_shake_from_hash::(&m_hash(message), salt) - } - - fn verify(message: &[u8], em: &[u8; 256]) -> bool { - emsa_pss_verify_shake_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/lib.rs b/crypto/rsa/src/lib.rs index 3fea1ebf..f40f9869 100644 --- a/crypto/rsa/src/lib.rs +++ b/crypto/rsa/src/lib.rs @@ -17,8 +17,11 @@ //! 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) and -//! [`RSASSA_PSS_SHAKE`](rsassa_pss_shake::RSASSA_PSS_SHAKE), named by scheme and hash +//! [`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, @@ -234,10 +237,14 @@ //! //! 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 also implemented ([`rsassa_pss_shake`], built on `emsa_pss_shake` rather than -//! `mgf1`), 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. +//! 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 @@ -348,11 +355,14 @@ //! 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 salt length is fixed to the hash's own output length** (RFC 8017 §9.1 note -//! 4's "typical" choice) rather than being caller-configurable. A verifier that expects a -//! different salt length (including the zero-length salt some other implementations default -//! to) will not interoperate with signatures this crate produces, and this crate's own verifier -//! will reject signatures made with a different salt length. +//! - **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)] @@ -361,7 +371,6 @@ mod codec; mod emsa_pkcs1_v1_5; mod emsa_pss; -mod emsa_pss_shake; pub mod keygen; pub mod keys; mod mgf1; @@ -376,7 +385,6 @@ mod rsa_core; pub mod rsassa; pub mod rsassa_pkcs1_v1_5; pub mod rsassa_pss; -pub mod rsassa_pss_shake; pub mod rsasve; pub mod rsasve_kdf; pub mod size; diff --git a/crypto/rsa/src/rsa_2048.rs b/crypto/rsa/src/rsa_2048.rs index 5200506c..7a234a90 100644 --- a/crypto/rsa/src/rsa_2048.rs +++ b/crypto/rsa/src/rsa_2048.rs @@ -7,7 +7,6 @@ use crate::rsassa_pkcs1_v1_5::RSASSA_PKCS1_v1_5; use crate::rsassa_pss::RSASSA_PSS; -use crate::rsassa_pss_shake::RSASSA_PSS_SHAKE; use crate::rsasve::{RsaKEMPrivateKey, RsaKEMPublicKey}; pub use crate::size::RSA2048; use crate::size::RsaSize; @@ -41,7 +40,7 @@ pub type RSASSA_PSS_SHA384 = RSASSA_PSS; 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_SHAKE; +pub type RSASSA_PSS_SHAKE128 = RSASSA_PSS; /// An RSA-2048 key-establishment private key. pub type RSA2048KEMPrivateKey = RsaKEMPrivateKey; diff --git a/crypto/rsa/src/rsa_3072.rs b/crypto/rsa/src/rsa_3072.rs index 9343efb9..41091ae4 100644 --- a/crypto/rsa/src/rsa_3072.rs +++ b/crypto/rsa/src/rsa_3072.rs @@ -7,7 +7,6 @@ use crate::rsassa_pkcs1_v1_5::RSASSA_PKCS1_v1_5; use crate::rsassa_pss::RSASSA_PSS; -use crate::rsassa_pss_shake::RSASSA_PSS_SHAKE; use crate::rsasve::{RsaKEMPrivateKey, RsaKEMPublicKey}; pub use crate::size::RSA3072; use crate::size::RsaSize; @@ -41,7 +40,7 @@ pub type RSASSA_PSS_SHA384 = RSASSA_PSS; 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_SHAKE; +pub type RSASSA_PSS_SHAKE128 = RSASSA_PSS; /// An RSA-3072 key-establishment private key. pub type RSA3072KEMPrivateKey = RsaKEMPrivateKey; diff --git a/crypto/rsa/src/rsa_4096.rs b/crypto/rsa/src/rsa_4096.rs index 56338175..b3bb6ca8 100644 --- a/crypto/rsa/src/rsa_4096.rs +++ b/crypto/rsa/src/rsa_4096.rs @@ -7,7 +7,6 @@ use crate::rsassa_pkcs1_v1_5::RSASSA_PKCS1_v1_5; use crate::rsassa_pss::RSASSA_PSS; -use crate::rsassa_pss_shake::RSASSA_PSS_SHAKE; use crate::rsasve::{RsaKEMPrivateKey, RsaKEMPublicKey}; pub use crate::size::RSA4096; use crate::size::RsaSize; @@ -41,7 +40,7 @@ pub type RSASSA_PSS_SHA384 = RSASSA_PSS; 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_SHAKE; +pub type RSASSA_PSS_SHAKE256 = RSASSA_PSS; /// An RSA-4096 key-establishment private key. pub type RSA4096KEMPrivateKey = RsaKEMPrivateKey; diff --git a/crypto/rsa/src/rsassa.rs b/crypto/rsa/src/rsassa.rs index 25167e4c..05161c0f 100644 --- a/crypto/rsa/src/rsassa.rs +++ b/crypto/rsa/src/rsassa.rs @@ -1,7 +1,6 @@ //! 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), -//! [`RSASSA_PSS_SHAKE`](crate::rsassa_pss_shake::RSASSA_PSS_SHAKE)) implements, the size, +//! [`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 @@ -45,11 +44,13 @@ pub trait RsaDeterministicSignatureAlgorithm: RsaSignatureAlgorithm { fn emsa_encode(m_hash: &[u8]) -> [u8; K_LEN]; } -/// An RSA signature algorithm whose encoding takes a salt: RSASSA-PSS, with MGF1 or a native -/// XOF mask. Its keys sign through [`SigningKey`], the salt (one hash output, RFC 8017 §9.1 -/// note 4's "typical" choice) drawn from the RNG when the signer is made. +/// 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 { - /// EMSA-PSS-ENCODE of the message hash with `salt`. + /// 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]; } @@ -62,10 +63,11 @@ pub struct RsaSigner<'k, A: RsaRandomizedSignatureAlgorithm> { } impl RsaSigner<'_, A> { - /// Replaces the drawn salt with `salt`, one hash output long (a compile-time check), for a - /// known-answer test: the signature is then a function of the key and the message alone. + /// 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::Hash::OUTPUT_LEN, "the PSS salt is one hash output long") }; + const { assert!(N == A::SALT_LEN, "the salt is the algorithm's salt length") }; self.salt[..N].copy_from_slice(&salt); } } @@ -107,8 +109,9 @@ where 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::Hash::OUTPUT_LEN]).map_err(SignatureError::RNGError)?; + rng.next_bytes_out(&mut salt[..A::SALT_LEN]).map_err(SignatureError::RNGError)?; Ok(RsaSigner { sk: self, hash: A::Hash::default(), salt }) } } @@ -174,7 +177,7 @@ where let h_len = A::Hash::OUTPUT_LEN; let mut m_hash = [0u8; MAX_HASH_LEN]; self.hash.do_final_out(&mut m_hash[..h_len]); - sign_from_hash_with_salt::(self.sk, &m_hash[..h_len], &self.salt[..h_len]) + sign_from_hash_with_salt::(self.sk, &m_hash[..h_len], &self.salt[..A::SALT_LEN]) } fn do_final_out(self, output: &mut [u8; K_LEN]) -> Result { @@ -288,10 +291,10 @@ where A: RsaRandomizedSignatureAlgorithm, A::Size: RsaSigningSize + RsaSize, { - let h_len = A::Hash::OUTPUT_LEN; + 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[..h_len]).map_err(SignatureError::RNGError)?; - sign_from_hash_with_salt::(sk, m_hash, &salt[..h_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 @@ -342,6 +345,5 @@ where 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 {} - impl Sealed for crate::rsassa_pss_shake::RSASSA_PSS_SHAKE {} + impl Sealed for crate::rsassa_pss::RSASSA_PSS {} } diff --git a/crypto/rsa/src/rsassa_pss.rs b/crypto/rsa/src/rsassa_pss.rs index 50d559ba..9e7f755e 100644 --- a/crypto/rsa/src/rsassa_pss.rs +++ b/crypto/rsa/src/rsassa_pss.rs @@ -1,58 +1,218 @@ -//! RSASSA-PSS (RFC 8017 §8.1) over the modulus size `K` ([`RsaSize`]) and the hash `H` (also -//! MGF1's hash): [`RSASSA_PSS`] is the algorithm marker a key names, named -//! `RSASSA-PSS-` at the lesser of the size's and the hash's strength, and its -//! [`RsaRandomizedSignatureAlgorithm`] impl is `emsa_pss`'s probabilistic encoding, the salt one -//! hash output long (RFC 8017 §9.1 note 4's "typical" choice); the keys, the workers (with -//! `set_salt` for a known answer) and the `*_from_hash` entry points are [`crate::rsassa`]'s, -//! once over every algorithm. +//! 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::rsassa::{RsaRandomizedSignatureAlgorithm, RsaSignatureAlgorithm}; +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}; +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; -/// RSASSA-PSS (RFC 8017 §8.1) over the hash `H`, with MGF1 over `H`, at the modulus size `K`: the algorithm marker the key role traits are implemented -/// over, named `RSASSA-PSS-` (`RSASSA-PSS-SHA256`), at the lesser of the size's and the hash's -/// strength. [`RsaPrivateKey`](crate::keys::RsaPrivateKey) signs through [`SigningKey`](bouncycastle_core::signature_key::SigningKey) at a signing size: a fresh salt, one -/// hash output long, from the caller's RNG per signer (EMSA-PSS-ENCODE step 4), so two -/// signatures of one message differ. [`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 `SigningKey`, `sk.sign(&mut rng, msg, None)`. `ctx` is accepted and -/// ignored, since RSA has no context string. +/// 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)>, +pub struct RSASSA_PSS { + _params: PhantomData<(K, H, P)>, } -impl RSASSA_PSS { - const NAME: ConstStr<40> = ConstStr::concat(&["RSASSA-PSS-", H::ALG_NAME]); +impl> RSASSA_PSS { + const NAME: ConstStr<80> = + ConstStr::concat(&["RSASSA-PSS-", H::ALG_NAME, P::NAME_SUFFIX.as_str()]); } -impl Algorithm for RSASSA_PSS { +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> SignatureAlgorithm for RSASSA_PSS {} -impl RsaSignatureAlgorithm 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) + emsa_pss_verify_from_hash::(m_hash, em) } } -impl RsaRandomizedSignatureAlgorithm - for RSASSA_PSS +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) + 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/rsassa_pss_shake.rs b/crypto/rsa/src/rsassa_pss_shake.rs deleted file mode 100644 index 84ee4c15..00000000 --- a/crypto/rsa/src/rsassa_pss_shake.rs +++ /dev/null @@ -1,60 +0,0 @@ -//! RSASSA-PSS with SHAKE128 or SHAKE256 as both the hash and the (native, non-MGF1) mask -//! generation function, `id-RSASSA-PSS-SHAKE128` / `id-RSASSA-PSS-SHAKE256` (RFC 8702 §3.2.1), -//! over the modulus size `K` ([`RsaSize`]) and the XOF `X`: [`RSASSA_PSS_SHAKE`] is the -//! algorithm marker a key names, named `RSASSA-PSS-`, and its -//! [`RsaRandomizedSignatureAlgorithm`] impl is `emsa_pss_shake`'s encoding in place of -//! [`crate::rsassa_pss`]'s; the keys, the workers and the `*_from_hash` entry points are -//! [`crate::rsassa`]'s, once over every algorithm. - -use crate::emsa_pss_shake::{emsa_pss_encode_shake_from_hash, emsa_pss_verify_shake_from_hash}; -use crate::rsassa::{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_utils::const_str::ConstStr; -use core::marker::PhantomData; - -/// RSASSA-PSS with a SHAKE XOF `X` as both hash and mask (RFC 8702 §3.2.1), at the modulus size `K`: the algorithm marker the key role traits are implemented -/// over, named `RSASSA-PSS-` (`RSASSA-PSS-SHAKE128`), at the lesser of the size's and the hash's -/// strength. [`RsaPrivateKey`](crate::keys::RsaPrivateKey) signs through [`SigningKey`](bouncycastle_core::signature_key::SigningKey) at a signing size: a fresh salt, one -/// hash output long, from the caller's RNG per signer (EMSA-PSS-ENCODE step 4), so two -/// signatures of one message differ. [`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 `SigningKey`, `sk.sign(&mut rng, msg, None)`. `ctx` is accepted and -/// ignored, since RSA has no context string. -#[allow(non_camel_case_types)] -pub struct RSASSA_PSS_SHAKE { - _params: PhantomData<(K, X)>, -} - -impl RSASSA_PSS_SHAKE { - const NAME: ConstStr<40> = ConstStr::concat(&["RSASSA-PSS-", X::ALG_NAME]); -} - -impl Algorithm for RSASSA_PSS_SHAKE { - const ALG_NAME: &'static str = Self::NAME.as_str(); - const MAX_SECURITY_STRENGTH: SecurityStrength = - min_strength(K::STRENGTH, X::MAX_SECURITY_STRENGTH); -} - -impl SignatureAlgorithm for RSASSA_PSS_SHAKE {} - -impl RsaSignatureAlgorithm - for RSASSA_PSS_SHAKE -{ - type Size = K; - type Hash = X; - - fn emsa_verify(m_hash: &[u8], em: &[u8; K_LEN]) -> bool { - emsa_pss_verify_shake_from_hash::(m_hash, em) - } -} - -impl RsaRandomizedSignatureAlgorithm - for RSASSA_PSS_SHAKE -{ - fn emsa_encode(m_hash: &[u8], salt: &[u8]) -> [u8; K_LEN] { - emsa_pss_encode_shake_from_hash::(m_hash, salt) - } -} diff --git a/crypto/rsa/src/size.rs b/crypto/rsa/src/size.rs index 577923a3..38a9f9fe 100644 --- a/crypto/rsa/src/size.rs +++ b/crypto/rsa/src/size.rs @@ -15,12 +15,11 @@ use crate::keys::{ }; use crate::rsa_core; use crate::rsassa_pkcs1_v1_5::RSASSA_PKCS1_v1_5; -use crate::rsassa_pss::RSASSA_PSS; -use crate::rsassa_pss_shake::RSASSA_PSS_SHAKE; +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, XOF}; +use bouncycastle_core::traits::{AlgorithmOID, HashAlgParams, HashOneShot, RNG}; use bouncycastle_ec::montgomery; use bouncycastle_ec::nat; use bouncycastle_utils::secret::{NoPadding, ZeroizablePrimitive}; @@ -123,7 +122,7 @@ pub trait RsaSigningSize: RsaSize { /// `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 three run [`RsaSigningSize::keygen`], FIPS 186-5 Appendix A.1.3; the RNG is +/// 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 { @@ -139,27 +138,31 @@ pub trait SignatureKeyPair: RsaSigningSize { SignatureError, >; - /// A key pair for RSASSA-PSS with `H` (and MGF1 over it). + /// 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( + fn generate_pss_signature_key_pair( rng: &mut dyn RNG, ) -> Result< (RsaPublicKey>, RsaPrivateKey>), SignatureError, >; - /// A key pair for RSASSA-PSS with the XOF `X` as hash and mask (RFC 8702). + /// 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_shake_signature_key_pair( + fn generate_pss_signature_key_pair_with>( rng: &mut dyn RNG, ) -> Result< - (RsaPublicKey>, RsaPrivateKey>), + (RsaPublicKey>, RsaPrivateKey>), SignatureError, >; } @@ -175,7 +178,7 @@ impl SignatureKeyPair for K { Ok((RsaPublicKey::from_components(pk), RsaPrivateKey::from_components(sk))) } - fn generate_pss_signature_key_pair( + fn generate_pss_signature_key_pair( rng: &mut dyn RNG, ) -> Result<(RsaPublicKey>, RsaPrivateKey>), SignatureError> { @@ -183,10 +186,10 @@ impl SignatureKeyPair for K { Ok((RsaPublicKey::from_components(pk), RsaPrivateKey::from_components(sk))) } - fn generate_pss_shake_signature_key_pair( + fn generate_pss_signature_key_pair_with>( rng: &mut dyn RNG, ) -> Result< - (RsaPublicKey>, RsaPrivateKey>), + (RsaPublicKey>, RsaPrivateKey>), SignatureError, > { let (pk, sk) = K::keygen(rng)?; diff --git a/crypto/rsa/tests/keys_tests.rs b/crypto/rsa/tests/keys_tests.rs index 97daf99f..4d4662ab 100644 --- a/crypto/rsa/tests/keys_tests.rs +++ b/crypto/rsa/tests/keys_tests.rs @@ -299,3 +299,30 @@ fn crt_components_out_of_range_rejected_at_every_signing_size() { 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/rsa_2048_pss_params_tests.rs b/crypto/rsa/tests/rsa_2048_pss_params_tests.rs new file mode 100644 index 00000000..3e3d1973 --- /dev/null +++ b/crypto/rsa/tests/rsa_2048_pss_params_tests.rs @@ -0,0 +1,264 @@ +//! 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::{DeterministicSigningKey, SigningKey, VerifyingKey}; +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_shake128_tests.rs b/crypto/rsa/tests/rsa_2048_pss_shake128_tests.rs index 1d9dd5fc..772e1c58 100644 --- a/crypto/rsa/tests/rsa_2048_pss_shake128_tests.rs +++ b/crypto/rsa/tests/rsa_2048_pss_shake128_tests.rs @@ -18,7 +18,6 @@ use bouncycastle_rsa::keys::{ }; use bouncycastle_rsa::rsa_2048::{RSASSA_PSS_SHAKE128, SIG_LEN}; use bouncycastle_rsa::rsassa; -use bouncycastle_rsa::rsassa_pss_shake::RSASSA_PSS_SHAKE; use bouncycastle_sha3::SHAKE128; use serde_json::Value; use std::fs; @@ -250,7 +249,7 @@ impl RNG for FixedRng { /// `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_shake::sign_from_hash_with_salt` over the same digest and salt, while an unfixed +/// `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() { @@ -267,10 +266,8 @@ fn set_salt_fixes_the_salt_on_the_streaming_path() { 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::, 256>( - &sk.key::>(), - &digest, - &salt, + let expected = rsassa::sign_from_hash_with_salt::( + &sk_rsassa_pss_shake128, &digest, &salt, ) .unwrap(); assert_eq!(sig, expected); diff --git a/crypto/rsa/tests/rsassa_worker_tests.rs b/crypto/rsa/tests/rsassa_worker_tests.rs index 4db877ac..ab49ad21 100644 --- a/crypto/rsa/tests/rsassa_worker_tests.rs +++ b/crypto/rsa/tests/rsassa_worker_tests.rs @@ -9,7 +9,6 @@ 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_rsa::rsassa_pss_shake::RSASSA_PSS_SHAKE; use bouncycastle_sha2::SHA256; use bouncycastle_sha3::SHAKE128; @@ -74,13 +73,13 @@ fn workers_name_their_algorithm() { let verifier = pk_rsassa_pss_rsa2048_sha256.create_verifier(None).unwrap(); assert_eq!(verifier.alg_name(), "RSASSA-PSS-SHA256"); - let sk_rsassa_pss_shake_rsa2048_shake128 = sk.key::>(); + let sk_rsassa_pss_rsa2048_shake128 = sk.key::>(); - let signer = sk_rsassa_pss_shake_rsa2048_shake128.create_signer(&mut rng, None).unwrap(); + 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_shake_rsa2048_shake128 = pk.key::>(); + let pk_rsassa_pss_rsa2048_shake128 = pk.key::>(); - let verifier = pk_rsassa_pss_shake_rsa2048_shake128.create_verifier(None).unwrap(); + let verifier = pk_rsassa_pss_rsa2048_shake128.create_verifier(None).unwrap(); assert_eq!(verifier.alg_name(), "RSASSA-PSS-SHAKE128"); } @@ -129,27 +128,27 @@ fn pss_sign_from_hash_draws_a_fresh_salt_and_verifies() { let mut digest = [0u8; 32]; SHAKE128::hash_out(b"the message", &mut digest); - let a = rsassa::sign_from_hash::, 256>( - &sk.key::>(), + let a = rsassa::sign_from_hash::, 256>( + &sk.key::>(), &digest, &mut rng, ) .unwrap(); - let b = rsassa::sign_from_hash::, 256>( - &sk.key::>(), + let b = rsassa::sign_from_hash::, 256>( + &sk.key::>(), &digest, &mut rng, ) .unwrap(); assert_ne!(a, b); - rsassa::verify_from_hash::, 256>( - &pk.key::>(), + rsassa::verify_from_hash::, 256>( + &pk.key::>(), &digest, &a, ) .unwrap(); - rsassa::verify_from_hash::, 256>( - &pk.key::>(), + rsassa::verify_from_hash::, 256>( + &pk.key::>(), &digest, &b, ) 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"); +} From 165a5d48c6bd867bb5d3a18bdd50b616c2d74360 Mon Sep 17 00:00:00 2001 From: David Hook Date: Tue, 17 Nov 2026 08:40:33 +1100 Subject: [PATCH 36/55] rsa: modexp's docs name its private helpers without linking to them rustdoc with warnings denied failed on eight intra-doc links from public documentation to private items (crate::rsa_core, to_montgomery, double_mod_n, pow2_mod); they are plain code spans now. Docs only; cargo doc with -D warnings is clean for the crate. Assisted-by: Claude:claude-mythos-5-2 --- crypto/rsa/src/modexp.rs | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/crypto/rsa/src/modexp.rs b/crypto/rsa/src/modexp.rs index 6507a019..0d3109a1 100644 --- a/crypto/rsa/src/modexp.rs +++ b/crypto/rsa/src/modexp.rs @@ -27,7 +27,7 @@ //! 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 +//! (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. @@ -60,7 +60,7 @@ fn double_mod_n(a: &[u64; L], n: &[u64; L]) -> [u64; L] { } /// `2^bits mod n` for odd `n`, by `bits` repeated doublings from `1`. Variable time, like -/// [`double_mod_n`]: the modulus is public. +/// `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; @@ -153,7 +153,7 @@ fn from_montgomery( /// 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. +/// `to_montgomery` relies on -- see the module docs' note on [`montgomery::redc`]'s precondition. pub fn mul_mod( a: &[u64; L], b: &[u64; L], @@ -169,7 +169,7 @@ pub fn mul_mod( /// `(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 +/// 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); @@ -179,7 +179,7 @@ pub fn sub_mod(a: &[u64; N], b: &[u64; N], modulus: &[u64; N]) - } /// `(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). +/// [`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; @@ -201,7 +201,7 @@ fn ct_shift_in_bit_mod(acc: &[u64; N], bit: u64, modulus: &[u64; } /// `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* +/// 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 @@ -209,7 +209,7 @@ fn ct_shift_in_bit_mod(acc: &[u64; N], bit: u64, modulus: &[u64; /// 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 +/// 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. From 2a83f31e4e38afb1f65ee9aeddd3c5cdd795b408 Mon Sep 17 00:00:00 2001 From: David Hook Date: Tue, 17 Nov 2026 08:41:05 +1100 Subject: [PATCH 37/55] cli: do_verify's doc links to the commands that call it The doc linked to rsa_sign_verify_cmd, which no longer exists; the Verify arms are rsa_pss_cmd's and rsa_pkcs1_cmd's. With the rsa crate's fix, cargo doc with -D warnings is clean over the workspace. Assisted-by: Claude:claude-mythos-5-2 --- cli/src/rsa_cmd.rs | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/cli/src/rsa_cmd.rs b/cli/src/rsa_cmd.rs index 5d315bae..fd6e820e 100644 --- a/cli/src/rsa_cmd.rs +++ b/cli/src/rsa_cmd.rs @@ -157,9 +157,10 @@ fn parse_pk, const PK_LEN: usize>( } /// Verifies stdin against `--pkfile`/`--sigfile` through `PK`'s streaming `VerifyingKey` -/// impl. Shared by [`rsa_sign_verify_cmd`]'s `Verify` arm, 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. +/// 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, From 93602657a128f0494d4647ee9d06147f784701dd Mon Sep 17 00:00:00 2001 From: David Hook Date: Tue, 17 Nov 2026 16:06:39 +1100 Subject: [PATCH 38/55] cli: the rsa keygen commands write the private key through the wiped writer The key is encoded into a Secret by helpers::write_private_key, as the other keygen commands do since d9143c8a, and no longer by value through the plain hex writer. Output is unchanged. Verified with the rsa CLI tests, the cli build with no warnings and nightly rustfmt. Assisted-by: Claude:claude-mythos-5-2 --- cli/src/rsa_cmd.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/cli/src/rsa_cmd.rs b/cli/src/rsa_cmd.rs index 8e6a9fe4..30a53644 100644 --- a/cli/src/rsa_cmd.rs +++ b/cli/src/rsa_cmd.rs @@ -37,7 +37,7 @@ use crate::helpers::{ println_stdout, read_input_file, read_secret_file, stream_stdin, write_bytes_or_hex, - write_bytes_or_hex_to_file, + write_bytes_or_hex_to_file, write_private_key, }; use bouncycastle::core::errors::SignatureError; use bouncycastle::core::key_material::KeyMaterialTrait; @@ -203,7 +203,7 @@ fn rsa_keygen_cmd Date: Tue, 17 Nov 2026 18:10:10 +1100 Subject: [PATCH 39/55] sha1: SHA-1 (FIPS 180-4), for interoperation with what already uses it The new bouncycastle-sha1 is SHA1 on the Hash, HashOneShot and Suspendable traits, with its AlgorithmOID (id-sha1, RFC 8017 Appendix B.1), written against FIPS 180-4 Sections 4.1.1, 4.2.1, 5.3.1 and 6.1.2 and laid out as the SHA-256 code is: bit-oriented messages, a 96-byte suspended state, the hash value and block buffer in Secrets. It is here for RSA-OAEP with the hash or MGF1 an older peer chose, and the like. SHA-1 is not collision resistant, so its MAX_SECURITY_STRENGTH is SecurityStrength::None, and the crate docs' Security Considerations say what it must not be used for. There is no HMAC-SHA1 or HKDF-SHA1. The workspace and the umbrella crate gain the member. Tests: NIST's CAVP SHAVS vectors for SHA-1, byte- and bit-oriented, short, long and Monte Carlo (the SHA1*.rsp files of shabytetestvectors.zip and shabittestvectors.zip, copied into bc-test-data/crypto/sha1, which that repository does not hold yet); printed in the test file, RFC 3174 Section 7.3's four results and CAVP entries either side of the 56- and 64-byte and 448-bit padding points; the shared hash and suspended-state frameworks; output buffer lengths; a state suspended across a block boundary. Mutants on apollo: 138 (128 caught, 5 unviable, 5 missed, all equivalent: the or/xor swaps in Ch and Maj and the two in the padding that the code comments already name). Assisted-by: Claude:claude-mythos-5-2 --- Cargo.toml | 2 + crypto/sha1/Cargo.toml | 18 ++ crypto/sha1/benches/sha1_benches.rs | 30 +++ crypto/sha1/src/lib.rs | 123 +++++++++ crypto/sha1/src/sha1.rs | 331 +++++++++++++++++++++++++ crypto/sha1/tests/sha1_bc-test-data.rs | 180 ++++++++++++++ crypto/sha1/tests/sha1_tests.rs | 262 +++++++++++++++++++ src/lib.rs | 1 + 8 files changed, 947 insertions(+) create mode 100644 crypto/sha1/Cargo.toml create mode 100644 crypto/sha1/benches/sha1_benches.rs create mode 100644 crypto/sha1/src/lib.rs create mode 100644 crypto/sha1/src/sha1.rs create mode 100644 crypto/sha1/tests/sha1_bc-test-data.rs create mode 100644 crypto/sha1/tests/sha1_tests.rs diff --git a/Cargo.toml b/Cargo.toml index 0610549e..2b8aaa84 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -43,6 +43,7 @@ bouncycastle-mldsa-lowmemory = { path = "./crypto/mldsa-lowmemory" } bouncycastle-poly1305 = { path = "./crypto/poly1305" } 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" } @@ -105,6 +106,7 @@ bouncycastle-mlkem-lowmemory.workspace = true bouncycastle-poly1305.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/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/src/lib.rs b/src/lib.rs index 866524af..e2a22184 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -26,6 +26,7 @@ pub use bouncycastle_mlkem_lowmemory as mlkem_lowmemory; pub use bouncycastle_poly1305 as poly1305; pub use bouncycastle_rng as rng; pub use bouncycastle_rsa as rsa; +pub use bouncycastle_sha1 as sha1; pub use bouncycastle_sha2 as sha2; pub use bouncycastle_sha3 as sha3; pub use bouncycastle_sm2 as sm2; From b77923fb76d0493fade7a2236b0cf7cfe8ca08fb Mon Sep 17 00:00:00 2001 From: David Hook Date: Tue, 17 Nov 2026 18:10:10 +1100 Subject: [PATCH 40/55] factory: HashFactory knows SHA1 by name SHA-1 is reached as "SHA1" and reports no security strength; it is not a default. Tested against RFC 3174 Section 7.3's TEST1 and TEST2. Assisted-by: Claude:claude-mythos-5-2 --- crypto/factory/Cargo.toml | 1 + crypto/factory/src/hash_factory.rs | 13 +++++++++++++ crypto/factory/tests/hash_factory_tests.rs | 20 ++++++++++++++++++++ 3 files changed, 34 insertions(+) diff --git a/crypto/factory/Cargo.toml b/crypto/factory/Cargo.toml index 9b921992..2d8a853a 100644 --- a/crypto/factory/Cargo.toml +++ b/crypto/factory/Cargo.toml @@ -10,6 +10,7 @@ bouncycastle-blake3.workspace = true bouncycastle-concatkdf.workspace = true bouncycastle-core.workspace = true bouncycastle-hmac.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 eca983ab..2690d001 100644 --- a/crypto/factory/src/hash_factory.rs +++ b/crypto/factory/src/hash_factory.rs @@ -38,6 +38,8 @@ use bouncycastle_blake3::BLAKE3_NAME; use bouncycastle_core::errors::HashError; use bouncycastle_core::security_strength::SecurityStrength; use bouncycastle_core::traits::{AlgorithmInfo, FinishToken, Hash}; +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, @@ -74,6 +76,9 @@ pub enum HashFactory { SHA3_512(sha3::SHA3_512), /// SM3(sm3::SM3), + /// 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 @@ -121,6 +126,7 @@ impl AlgorithmFactory for HashFactory { SHA3_384_NAME => Ok(Self::SHA3_384(sha3::SHA3_384::new())), SHA3_512_NAME => Ok(Self::SHA3_512(sha3::SHA3_512::new())), SM3_NAME => Ok(Self::SM3(sm3::SM3::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())), @@ -147,6 +153,7 @@ impl AlgorithmInfo for HashFactory { Self::SHA3_384(h) => h.alg_name(), Self::SHA3_512(h) => h.alg_name(), Self::SM3(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(), @@ -167,6 +174,7 @@ impl AlgorithmInfo for HashFactory { Self::SHA3_384(h) => h.max_security_strength(), Self::SHA3_512(h) => h.max_security_strength(), Self::SM3(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(), @@ -189,6 +197,7 @@ impl Hash for HashFactory { Self::SHA3_384(h) => h.block_bitlen(), Self::SHA3_512(h) => h.block_bitlen(), Self::SM3(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(), @@ -209,6 +218,7 @@ impl Hash for HashFactory { Self::SHA3_384(h) => h.output_len(), Self::SHA3_512(h) => h.output_len(), Self::SM3(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(), @@ -229,6 +239,7 @@ impl Hash for HashFactory { Self::SHA3_384(h) => h.do_update(data), Self::SHA3_512(h) => h.do_update(data), Self::SM3(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), @@ -251,6 +262,7 @@ impl Hash for HashFactory { Self::SHA3_384(h) => h.finish_into(token, output), Self::SHA3_512(h) => h.finish_into(token, output), Self::SM3(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), @@ -281,6 +293,7 @@ impl Hash for HashFactory { Self::SHA3_384(h) => h.finish_partial_bits_into(token, partial_byte, num_bits, output), Self::SHA3_512(h) => h.finish_partial_bits_into(token, partial_byte, num_bits, output), Self::SM3(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 1b8fc155..3cc98a5b 100644 --- a/crypto/factory/tests/hash_factory_tests.rs +++ b/crypto/factory/tests/hash_factory_tests.rs @@ -24,6 +24,7 @@ mod hash_factory_tests { (bouncycastle_sha3::SHA3_384_NAME, _192bit), (bouncycastle_sha3::SHA3_512_NAME, _256bit), (bouncycastle_sm3::SM3_NAME, _128bit), + (bouncycastle_sha1::SHA1_NAME, SecurityStrength::None), (bouncycastle_ascon::ASCON_HASH256_NAME, _128bit), ]; for (name, strength) in table { @@ -125,6 +126,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; From 4bddf06d275e1315f1b48617d53f798b341072dd Mon Sep 17 00:00:00 2001 From: David Hook Date: Tue, 17 Nov 2026 18:10:10 +1100 Subject: [PATCH 41/55] cli: the sha1 command Streams stdin through SHA-1, as the other hash commands do; the help says it is for checking existing digests. cli/tests/test_sha1.sh checks RFC 3174 Section 7.3's TEST1, TEST2 and TEST4 and that raw and hex output agree. Assisted-by: Claude:claude-mythos-5-2 --- cli/src/main.rs | 13 +++++++++++++ cli/src/sha1_cmd.rs | 6 ++++++ cli/tests/test_sha1.sh | 37 +++++++++++++++++++++++++++++++++++++ 3 files changed, 56 insertions(+) create mode 100644 cli/src/sha1_cmd.rs create mode 100755 cli/tests/test_sha1.sh diff --git a/cli/src/main.rs b/cli/src/main.rs index 400820a7..1b20bf65 100644 --- a/cli/src/main.rs +++ b/cli/src/main.rs @@ -26,6 +26,7 @@ mod ofb_cmd; mod rng_cmd; mod rsa_cmd; mod rsasve_cmd; +mod sha1_cmd; mod sha2_cmd; mod sha3_cmd; mod sm2_cmd; @@ -4331,6 +4332,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 { @@ -7908,6 +7918,9 @@ fn run() { Some(Subcommands::SM2 { action, idfile, skfile, pkfile, sigfile, x }) => { sm2_cmd::sm2_cmd(action, idfile, skfile, pkfile, sigfile, *x); } + Some(Subcommands::SHA1 { x }) => { + sha1_cmd::sha1_cmd(*x); + } Some(Subcommands::SM3 { x }) => { sm3_cmd::sm3_cmd(*x); } 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/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 From 09e076870e60e11d855e35c2d8ec929c8f2fde11 Mon Sep 17 00:00:00 2001 From: David Hook Date: Tue, 17 Nov 2026 18:10:10 +1100 Subject: [PATCH 42/55] mem_usage_benches: a SHA-1 stack harness bench_sha1_mem_usage calls each SHA1 entry point as the SM3 harness does; the crate docs' table is from the frames the compiler reports for it. Assisted-by: Claude:claude-mythos-5-2 --- mem_usage_benches/Cargo.toml | 4 + mem_usage_benches/src/bench_sha1_mem_usage.rs | 161 ++++++++++++++++++ mem_usage_benches/src/lib.rs | 1 + 3 files changed, 166 insertions(+) create mode 100644 mem_usage_benches/src/bench_sha1_mem_usage.rs diff --git a/mem_usage_benches/Cargo.toml b/mem_usage_benches/Cargo.toml index 5f0f8e21..8c4bdb57 100644 --- a/mem_usage_benches/Cargo.toml +++ b/mem_usage_benches/Cargo.toml @@ -79,6 +79,10 @@ path = "src/bench_camellia_mem_usage.rs" name = "bench_aria_mem_usage" path = "src/bench_aria_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_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 adfd641a..8969a236 100644 --- a/mem_usage_benches/src/lib.rs +++ b/mem_usage_benches/src/lib.rs @@ -19,6 +19,7 @@ mod bench_mldsa_mem_usage; mod bench_mlkem_mem_usage; mod bench_poly1305_mem_usage; mod bench_rsa_mem_usage; +mod bench_sha1_mem_usage; mod bench_sha2_mem_usage; mod bench_sha3_mem_usage; mod bench_sm2_mem_usage; From bd66b93d1e34897471cbdb673474b33233da171d Mon Sep 17 00:00:00 2001 From: David Hook Date: Tue, 17 Nov 2026 18:10:10 +1100 Subject: [PATCH 43/55] release notes: SHA-1 Assisted-by: Claude:claude-mythos-5-2 --- alpha_0.1.4_release_notes.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/alpha_0.1.4_release_notes.md b/alpha_0.1.4_release_notes.md index f81e27f1..4111b398 100644 --- a/alpha_0.1.4_release_notes.md +++ b/alpha_0.1.4_release_notes.md @@ -49,6 +49,10 @@ for implementors of a DHKEM group. Checked against the RFC's machine-readable vectors for P-256 and P-521 (32 sets each; P-521's key derivation is the first two-block `LabeledExpand`), and, for P-384, which the RFC defines but publishes no vectors for, against BC Java 1.84 in both directions. +* 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. ## Minor features / bug fixes From 365c2f6aa7e2f87ad49fc647144acc00e7871a40 Mon Sep 17 00:00:00 2001 From: David Hook Date: Tue, 17 Nov 2026 19:52:04 +1100 Subject: [PATCH 44/55] core: the key-transport roles core::key_transport_key is the pair of roles for transporting a key the sender already holds under a public key: KeyTransportEncryptingKey (transport_out, transport, max_key_len) and KeyTransportDecryptingKey (recover_out, into a KeyMaterial of any capacity), with KeyTransportAlgorithm as the marker their algorithm implements and KeyTransportError as their error. As on the KEM roles, the parameters are the role's type parameter. A recipient's failure is one error, DecryptionFailed, whatever the cause, a key that does not fit the buffer included; a recovered key comes back CryptographicRandom at the lesser of the algorithm's strength and its length's. RSAES-OAEP in bouncycastle-rsa is the first implementor; CMS and JOSE recipients are what it is for. Mutants on apollo over key_transport_key.rs with the rsa tests: 4 (2 caught, 2 unviable, 0 missed). Assisted-by: Claude:claude-mythos-5-2 --- crypto/core/src/errors.rs | 27 ++++++++++ crypto/core/src/key_transport_key.rs | 76 ++++++++++++++++++++++++++++ crypto/core/src/lib.rs | 1 + 3 files changed, 104 insertions(+) create mode 100644 crypto/core/src/key_transport_key.rs 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; From 6bdf3904f24f42bfc3a9580e252124a2e7b0420f Mon Sep 17 00:00:00 2001 From: David Hook Date: Tue, 17 Nov 2026 19:52:04 +1100 Subject: [PATCH 45/55] core-test-framework: a suite for the key-transport roles TestFrameworkKeyTransport::test runs a key pair through both roles: a round trip by value and into a stale buffer, the recovered key's type and strength, a damaged ciphertext, another private key and a too-short buffer as the one error with the buffer zeroized, the longest key and one byte more, a zeroized key refused, and an RNG below the algorithm's strength, each failure leaving the ciphertext buffer zeroized. Assisted-by: Claude:claude-mythos-5-2 --- .../core-test-framework/src/key_transport.rs | 139 ++++++++++++++++++ crypto/core-test-framework/src/lib.rs | 1 + 2 files changed, 140 insertions(+) create mode 100644 crypto/core-test-framework/src/key_transport.rs 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; From 738ee9b7568b7d971ed6b6e3b7f45c11d3e05350 Mon Sep 17 00:00:00 2001 From: David Hook Date: Tue, 17 Nov 2026 19:52:04 +1100 Subject: [PATCH 46/55] rsa: RSAES-OAEP key transport (RFC 8017 Section 7.1; SP 800-56B Rev. 2 Sections 7.2.2 and 9.2.3) The key-establishment keys RsaKEMPublicKey and RsaKEMPrivateKey run RSAES_OAEP under OaepParams<'l, H, M = H, const LEN = 32>: the label hash, the MGF1 hash (SP 800-56B Section 7.2.2.1 item 2 lets them differ), the label, and for the KEM the length of the key. Two roles over one implementation: the KEM roles, which draw LEN bytes and transport them (KTS-OAEP-basic) and on decapsulation require exactly LEN bytes back, and core's key-transport roles for a key the caller holds, of any length up to k - 2hLen - 2. The plaintext is always a key; there is no general message encryption and no RSAES-PKCS1-v1_5. LEN is checked against the modulus at compile time (a compile_fail doctest), as is k >= 2hLen + 2. eme_oaep.rs is the encoding (Section 7.1.1 step 2) and the decoding (7.1.2 step 3), commented step by step. The decoding folds the leading octet, lHash' and the search for the 0x01 separator into one mask, reads all of DB whatever it holds, and copies the message out by scanning DB for every output byte, so that neither the control flow nor the addresses touched depend on where the padding ends; every failure, a ciphertext not below the modulus included, is one error. mgf1.rs gains mgf1_xor, a streaming MGF1 that takes a seed of any length (one of OAEP's is maskedDB) and XORs into its target, its block in a Secret. The algorithm is named with both hashes (RSAES-OAEP-2048-SHA256-MGF1-SHA256) and its strength is the modulus's capped by what the shorter hash output can carry, not by collision strength, so SHA-1 (bouncycastle-sha1, a dev-dependency here) is usable for peers that need it and caps RSA-8192 at 128 bits. Tests: every group of Wycheproof's rsa_oaep_*_test.json at 2048, 3072, 4096 and 8192 bits, for every pairing of label hash and MGF1 hash, SHA-1 included, through the key-transport role: 569 valid messages recovered and 389 invalid ciphertexts refused with the one error and a zeroized buffer (140 cases of the misc file are at sizes with no private key type here and are counted as skipped). The KEM and key-transport frameworks; the label and both hashes bound; the two roles interoperating, with a key of another length refused by the KEM; out-of-range ciphertexts; names and strengths; an RNG at exactly the algorithm's strength accepted and a weaker one refused by both roles. Encryption is randomized and RFC 8017 prints no vectors, so the encrypt side is checked by round trip against the decrypt side; outside the suite, BC Java 1.84 decrypted this code's ciphertexts and this code BC Java's for five hash pairings (local/OaepCheck.java, first checked on 18 Wycheproof vectors). The crate docs gain the example and the stack table's two rows (massif: 10280 / 10264 bytes at 2048, 31000 / 39976 at 8192), and the benches the two operations. Not done: the decoding was written branch-free but not checked against its assembly. Mutants on apollo over eme_oaep.rs, rsaes_oaep.rs and mgf1_xor with the OAEP tests and the unit tests: 123 (97 caught, 21 unviable, 5 missed). The five are equivalent: three or/xor swaps on masks that are disjoint or whose top bit is clear for the values reached, and two comparisons between equal strengths. Assisted-by: Claude:claude-mythos-5-2 --- crypto/rsa/Cargo.toml | 1 + crypto/rsa/benches/rsa_2048_benches.rs | 13 + crypto/rsa/src/eme_oaep.rs | 161 +++++++++ crypto/rsa/src/lib.rs | 29 +- crypto/rsa/src/mgf1.rs | 52 +++ crypto/rsa/src/rsa_2048.rs | 4 + crypto/rsa/src/rsa_3072.rs | 4 + crypto/rsa/src/rsa_4096.rs | 4 + crypto/rsa/src/rsa_8192.rs | 4 + crypto/rsa/src/rsaes_oaep.rs | 431 +++++++++++++++++++++++++ crypto/rsa/tests/rsaes_oaep_tests.rs | 363 +++++++++++++++++++++ 11 files changed, 1062 insertions(+), 4 deletions(-) create mode 100644 crypto/rsa/src/eme_oaep.rs create mode 100644 crypto/rsa/src/rsaes_oaep.rs create mode 100644 crypto/rsa/tests/rsaes_oaep_tests.rs diff --git a/crypto/rsa/Cargo.toml b/crypto/rsa/Cargo.toml index 129c3a81..4ace0ab9 100644 --- a/crypto/rsa/Cargo.toml +++ b/crypto/rsa/Cargo.toml @@ -16,6 +16,7 @@ bouncycastle-utils.workspace = true [dev-dependencies] bouncycastle-core-test-framework.workspace = true bouncycastle-hex.workspace = true +bouncycastle-sha1.workspace = true criterion.workspace = true serde_json = "1.0" diff --git a/crypto/rsa/benches/rsa_2048_benches.rs b/crypto/rsa/benches/rsa_2048_benches.rs index 029a924f..6a88b74d 100644 --- a/crypto/rsa/benches/rsa_2048_benches.rs +++ b/crypto/rsa/benches/rsa_2048_benches.rs @@ -9,7 +9,9 @@ use bouncycastle_core::signature_key::{DeterministicSigningKey, SigningKey, Veri 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; @@ -198,6 +200,17 @@ fn bench_rsa_2048(c: &mut Criterion) { 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; diff --git a/crypto/rsa/src/eme_oaep.rs b/crypto/rsa/src/eme_oaep.rs new file mode 100644 index 00000000..bf02e88e --- /dev/null +++ b/crypto/rsa/src/eme_oaep.rs @@ -0,0 +1,161 @@ +//! 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 copies 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; + +/// `0xFF` if `x` is not zero, else `0x00`, without a branch. +fn nonzero_mask(x: u8) -> u8 { + let x = value_barrier(x as u32); + // x | -x has its top bit set exactly when x is not zero. + (((x | x.wrapping_neg()) >> 31) as u8).wrapping_neg() +} + +/// `0xFF` if `a == b`, else `0x00`, without a branch. +fn eq_mask_u32(a: u32, b: u32) -> u8 { + let x = value_barrier(a ^ b); + !(((x | x.wrapping_neg()) >> 31) as u8).wrapping_neg() +} + +/// `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'". `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(h_len); + let mut diff = 0u8; + for (a, b) in l_hash.iter().zip(l_hash_prime) { + 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 = nonzero & !found; + bad |= first & nonzero_mask(*b ^ 0x01); + // index = first ? i : index + let first32 = (first as u32).wrapping_mul(0x0101_0101); + index = (first32 & i as u32) | (!first32 & index); + 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 => { + bad |= ((((out.len() as u32).wrapping_sub(value_barrier(m_len))) >> 31) as u8) + .wrapping_neg() + } + } + + // out[j] = ps_and_m[m_start + j], taken by scanning every octet of DB for every octet of + // the output, so that no address depends on m_start. Positions past the message stay zero. + let good = !bad; + for (j, o) in out.iter_mut().enumerate() { + let want = m_start.wrapping_add(j as u32); + let mut byte = 0u8; + for (i, b) in ps_and_m.iter().enumerate() { + byte |= b & eq_mask_u32(i as u32, want); + } + *o = byte & good; + } + + // The one visible outcome: the error, or the length. + if 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/lib.rs b/crypto/rsa/src/lib.rs index 115fb1f3..bd1587be 100644 --- a/crypto/rsa/src/lib.rs +++ b/crypto/rsa/src/lib.rs @@ -1,5 +1,6 @@ -//! RSA digital signatures, RSASSA-PKCS1-v1_5 and RSASSA-PSS (RFC 8017 §8), and the RSASVE -//! key-encapsulation mechanism (NIST SP 800-56B Rev. 2 §7.2.1), built on +//! 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 @@ -8,8 +9,9 @@ //! //! # Scope //! -//! Signature schemes, plus RSASVE as a KEM ([`rsasve`]; see below). There is no RSAES-OAEP or -//! RSAES-PKCS1-v1_5 encryption, and so no KTS-OAEP. A modulus size is a marker type at the +//! 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 @@ -213,6 +215,21 @@ //! // 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>(()) //! ``` //! @@ -277,6 +294,8 @@ //! | 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 @@ -369,6 +388,7 @@ #![forbid(missing_docs)] mod codec; +mod eme_oaep; mod emsa_pkcs1_v1_5; mod emsa_pss; pub mod keygen; @@ -382,6 +402,7 @@ 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; diff --git a/crypto/rsa/src/mgf1.rs b/crypto/rsa/src/mgf1.rs index 326cc255..78ec6c07 100644 --- a/crypto/rsa/src/mgf1.rs +++ b/crypto/rsa/src/mgf1.rs @@ -4,6 +4,7 @@ //! seed: `mgfSeed` here is always exactly `H_LEN` bytes. 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 @@ -37,6 +38,27 @@ pub fn mgf1(seed: &[u8], mask: &mut [u8]) { } } +/// 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 @@ -54,6 +76,12 @@ mod tests { 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] @@ -93,4 +121,28 @@ mod tests { 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/rsa_2048.rs b/crypto/rsa/src/rsa_2048.rs index 7a234a90..983f10ac 100644 --- a/crypto/rsa/src/rsa_2048.rs +++ b/crypto/rsa/src/rsa_2048.rs @@ -52,3 +52,7 @@ pub const CT_LEN: usize = RSA2048::K_LEN; 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 index 41091ae4..b9ee4143 100644 --- a/crypto/rsa/src/rsa_3072.rs +++ b/crypto/rsa/src/rsa_3072.rs @@ -52,3 +52,7 @@ pub const CT_LEN: usize = RSA3072::K_LEN; 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 index b3bb6ca8..68e1d129 100644 --- a/crypto/rsa/src/rsa_4096.rs +++ b/crypto/rsa/src/rsa_4096.rs @@ -52,3 +52,7 @@ pub const CT_LEN: usize = RSA4096::K_LEN; 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 index cced1dc7..aa88f7a3 100644 --- a/crypto/rsa/src/rsa_8192.rs +++ b/crypto/rsa/src/rsa_8192.rs @@ -48,3 +48,7 @@ pub const CT_LEN: usize = RSA8192::K_LEN; 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/rsaes_oaep.rs b/crypto/rsa/src/rsaes_oaep.rs new file mode 100644 index 00000000..80abbdd2 --- /dev/null +++ b/crypto/rsa/src/rsaes_oaep.rs @@ -0,0 +1,431 @@ +//! 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. +//! * **SHA-1** (`bouncycastle_sha1::SHA1`) is accepted as either hash, 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}; +use crate::size::{RsaSigningSize, RsaSize}; +use bouncycastle_core::errors::{KEMError, KeyMaterialError, KeyTransportError, RNGError}; +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::key_transport_key::{ + KeyTransportAlgorithm, KeyTransportDecryptingKey, KeyTransportEncryptingKey, +}; +use bouncycastle_core::security_strength::SecurityStrength; +use bouncycastle_core::traits::{ + Algorithm, HashAlgParams, HashOneShot, KEMDecapsulator, KEMEncapsulator, RNG, +}; +use bouncycastle_utils::const_str::ConstStr; +use bouncycastle_utils::secret::Secret; +use core::marker::PhantomData; + +/// 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: 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: +/// +/// ```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: HashOneShot + HashAlgParams, + M: HashOneShot + HashAlgParams, +{ + 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: HashOneShot + HashAlgParams, + M: HashOneShot + HashAlgParams, +{ + out.fill(0); + // Step 2.a, 2.b: c = OS2IP(C); "If RSADP outputs 'ciphertext representative out of range' + // (meaning that c >= n), output 'decryption error' and stop". The ciphertext and the + // modulus are public, so this branch tells an observer nothing it could not compute. + let c = K::limbs_from_be_bytes(ct); + if !K::is_less(&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. +fn key_into( + bytes: &[u8], + strength: SecurityStrength, + key: &mut KeyMaterial, +) -> Result<(), KeyMaterialError> { + key.zeroize(); + let result = do_hazardous_operations(key, |key| { + // An empty or all-zero key is typed Zeroized by the buffer and carries no strength; + // that is a value, not an error. + match key.set_bytes_as_type(bytes, KeyType::CryptographicRandom) { + Ok(()) => {} + Err(KeyMaterialError::ActingOnZeroizedKey) => return Ok(()), + Err(e) => return Err(e), + } + if key.security_strength() > strength { + key.set_security_strength(strength)?; + } + Ok(()) + }); + if result.is_err() { + key.zeroize(); + } + result +} + +/// 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: HashOneShot + HashAlgParams, + M: HashOneShot + HashAlgParams, +{ + /// 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: HashOneShot + HashAlgParams, + M: HashOneShot + HashAlgParams, +{ + /// 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: HashOneShot + HashAlgParams, + M: HashOneShot + HashAlgParams, +{ + 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 <= 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: HashOneShot + HashAlgParams, + M: HashOneShot + HashAlgParams, +{ + 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 <= 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: HashOneShot + HashAlgParams, + M: HashOneShot + HashAlgParams, +{ + 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'". + 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: HashOneShot + HashAlgParams, + M: HashOneShot + HashAlgParams, +{ + 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/tests/rsaes_oaep_tests.rs b/crypto/rsa/tests/rsaes_oaep_tests.rs new file mode 100644 index 00000000..26fbe5ee --- /dev/null +++ b/crypto/rsa/tests/rsaes_oaep_tests.rs @@ -0,0 +1,363 @@ +//! 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, HashAlgParams, HashOneShot, PrivateKey}; +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::{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; + +/// `(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: HashOneShot + HashAlgParams, + M: HashOneShot + HashAlgParams, +{ + // 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}"); + 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}"), + } + } + (valid, invalid, 0) +} + +/// The MGF1 hash by Wycheproof's name. +fn with_mgf(group: &Value) -> Counts +where + K: RsaSigningSize + RsaSize, + H: HashOneShot + HashAlgParams, +{ + 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""); + for ct in [[0xFFu8; 256], [0u8; 256]] { + 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 before anything is drawn, 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]); +} From b97f976a1135357799bb5eafaf96693b58042d08 Mon Sep 17 00:00:00 2001 From: David Hook Date: Tue, 17 Nov 2026 19:52:04 +1100 Subject: [PATCH 47/55] cli: the rsasve commands write their private key and shared secret through the wiped writers As the other key-generating and KEM commands do. Output is unchanged. Assisted-by: Claude:claude-mythos-5-2 --- cli/src/rsasve_cmd.rs | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/cli/src/rsasve_cmd.rs b/cli/src/rsasve_cmd.rs index 40dfe3d9..0fb89647 100644 --- a/cli/src/rsasve_cmd.rs +++ b/cli/src/rsasve_cmd.rs @@ -20,7 +20,7 @@ use crate::helpers::{ println_stdout, read_input_file_or_stdin, read_secret_file, write_bytes_or_hex, - write_bytes_or_hex_to_file, + 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}; @@ -87,7 +87,7 @@ fn rsasve_cmd< exit(-1); }); write_bytes_or_hex_to_file(&pk.encode(), pkfile, output_hex); - write_bytes_or_hex(&sk.encode(), 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| { @@ -104,12 +104,12 @@ fn rsasve_cmd< match ctfile { Some(ctfile) => { write_bytes_or_hex_to_file(&ct, ctfile, output_hex); - write_bytes_or_hex(ss.ref_to_bytes(), output_hex); + write_secret_bytes_or_hex(ss.ref_to_bytes(), output_hex); } None => { write_bytes_or_hex(&ct, true); println_stdout(""); - write_bytes_or_hex(ss.ref_to_bytes(), true); + write_secret_bytes_or_hex(ss.ref_to_bytes(), true); } } } @@ -126,7 +126,7 @@ fn rsasve_cmd< eprintln!("Error: {alg_name} decapsulation failed: {e:?}"); exit(-1); }); - write_bytes_or_hex(ss.ref_to_bytes(), output_hex); + write_secret_bytes_or_hex(ss.ref_to_bytes(), output_hex); } } } From e68465e0086dcb367dbaf210e1e7dcbd5b5c343d Mon Sep 17 00:00:00 2001 From: David Hook Date: Tue, 17 Nov 2026 19:52:04 +1100 Subject: [PATCH 48/55] cli: the rsa-oaep- commands rsa-oaep-2048, -3072, -4096 and -8192 on rsasve's keys and key files: keygen; encaps and decaps, which draw and recover a 32-byte key; transport and recover, which carry a key supplied on stdin; --hash and --mgf-hash over SHA-1, SHA-224, SHA-256, SHA-384, SHA-512, SHA-512/224 and SHA-512/256 (the MGF1 hash is the label's unless given), and --label in hex. Secrets go through the wiped writers, and a decryption failure is one message whatever its cause. Tests: three cases of Wycheproof's rsa_oaep_2048_sha256_mgf1sha256 file under its key pin recover; transport, encaps and decaps are checked against it and each other across hash pairings, with the 190-byte limit, the one error, and the files each action needs. Assisted-by: Claude:claude-mythos-5-2 --- cli/src/main.rs | 230 ++++++++++++++++++++++++++ cli/src/rsa_oaep_cmd.rs | 279 ++++++++++++++++++++++++++++++++ cli/tests/rsa_oaep_cli_tests.rs | 219 +++++++++++++++++++++++++ 3 files changed, 728 insertions(+) create mode 100644 cli/src/rsa_oaep_cmd.rs create mode 100644 cli/tests/rsa_oaep_cli_tests.rs diff --git a/cli/src/main.rs b/cli/src/main.rs index 1b20bf65..882b024d 100644 --- a/cli/src/main.rs +++ b/cli/src/main.rs @@ -25,6 +25,7 @@ mod mlkem_cmd; mod ofb_cmd; mod rng_cmd; mod rsa_cmd; +mod rsa_oaep_cmd; mod rsasve_cmd; mod sha1_cmd; mod sha2_cmd; @@ -54,6 +55,7 @@ use crate::mac_cmd::HMACVariant; use crate::mldsa_cmd::{MLDSAAction, PreHashAlg}; 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}; @@ -4135,6 +4137,150 @@ enum Subcommands { 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 { @@ -7897,6 +8043,90 @@ fn run() { 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); } diff --git a/cli/src/rsa_oaep_cmd.rs b/cli/src/rsa_oaep_cmd.rs new file mode 100644 index 00000000..20dd684a --- /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::{HashAlgParams, HashOneShot, PrivateKey, PublicKey}; +use bouncycastle::rng::HashDRBG_SHA512; +use bouncycastle::rsa::rsaes_oaep::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: HashOneShot + HashAlgParams, + M: HashOneShot + HashAlgParams, +{ + 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: HashOneShot + HashAlgParams, +{ + 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/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; +} From e534f9054d93451db02fe522bef7a3c5d234ec28 Mon Sep 17 00:00:00 2001 From: David Hook Date: Tue, 17 Nov 2026 19:52:04 +1100 Subject: [PATCH 49/55] mem_usage_benches: OAEP encapsulation and decapsulation in the RSA stack harness At 2048 and 8192 bits with SHA-256; the rsa crate docs' two new rows are from it. Assisted-by: Claude:claude-mythos-5-2 --- mem_usage_benches/src/bench_rsa_mem_usage.rs | 66 ++++++++++++++++++++ 1 file changed, 66 insertions(+) diff --git a/mem_usage_benches/src/bench_rsa_mem_usage.rs b/mem_usage_benches/src/bench_rsa_mem_usage.rs index ffb88105..84c4b82e 100644 --- a/mem_usage_benches/src/bench_rsa_mem_usage.rs +++ b/mem_usage_benches/src/bench_rsa_mem_usage.rs @@ -38,11 +38,13 @@ 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"; @@ -430,6 +432,66 @@ fn bench_8192_rsasve_decaps() { 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() @@ -443,4 +505,8 @@ fn main() { // 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() } From 6e6f9f8cfa1e6fc335e3aef04c00343dbaa78f1a Mon Sep 17 00:00:00 2001 From: David Hook Date: Tue, 17 Nov 2026 19:52:04 +1100 Subject: [PATCH 50/55] release notes: RSAES-OAEP Assisted-by: Claude:claude-mythos-5-2 --- alpha_0.1.4_release_notes.md | 3 +++ 1 file changed, 3 insertions(+) diff --git a/alpha_0.1.4_release_notes.md b/alpha_0.1.4_release_notes.md index 4111b398..9721ca4f 100644 --- a/alpha_0.1.4_release_notes.md +++ b/alpha_0.1.4_release_notes.md @@ -53,6 +53,9 @@ 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. ## Minor features / bug fixes From 1de17cd17477f460ae79eb6f89f6afd2528a38ba Mon Sep 17 00:00:00 2001 From: David Hook Date: Tue, 17 Nov 2026 20:52:43 +1100 Subject: [PATCH 51/55] rsa: RSAES-OAEP review fixes From an independent review of the OAEP commits, which found no functional defect and no secret-dependent branch. eme_oaep.rs: the mask helpers are rebuilt the way utils::ct builds its own, a barrier after each step of the not-zero identity and again where a mask selects or is tested; the message is moved to the front of its buffer by one conditional shift per bit of its offset, every pass reading and writing every octet, in place of a copy that scanned the buffer for every output byte. rsaes_oaep.rs: the hashes are a sealed trait OaepHash over RFC 8017 Appendix A.2.1's seven (SHA-1, SHA-224, SHA-256, SHA-384, SHA-512, SHA-512/224, SHA-512/256), which removes the strength overstated for a XOF and the run-time panic for a hash wider than 64 bytes, and makes bouncycastle-sha1 a normal dependency; a ciphertext is refused outside 1 < c < n - 1 (SP 800-56B Rev. 2 Section 7.2.2.4), through rsasve's range check; an empty or all-zero recovered key is typed Zeroized without the hazardous-operations escape; a zero-length KEM key is a compile error; the RNG strength check is the roles', not the shared encrypt's; an unreachable strength arm is gone. Tests: three Wycheproof cases printed in the file so known answers run without the checkout, an encrypt round trip for every Wycheproof group (encryption at 3072, 4096 and 8192 bits), c = 1 refused, an RNG that fails on the seed draw, the 190-byte KEM key, SHA-224's strength at RSA-8192, an RNG at exactly the algorithm's strength. Benches: OAEP at 3072, 4096 and 8192. Mutants on apollo over eme_oaep.rs, rsaes_oaep.rs and mgf1_xor after the fixes: 143 (115 caught, 21 unviable, 2 timeouts, 5 missed). The timeouts are the shift loop made endless (<< to >> in its bound, += to *= on its counter). The missed are equivalent: | to ^ in not_zero_bit (the same top bit for every value below 2^31, which is all that reach it) and on the disjoint masks of the index select and the shift's byte select, < to <= in min_strength, and > to >= where key_into lowers a strength to the one it has. Assisted-by: Claude:claude-mythos-5-2 --- crypto/rsa/Cargo.toml | 2 +- crypto/rsa/benches/rsa_3072_benches.rs | 12 ++ crypto/rsa/benches/rsa_4096_benches.rs | 12 ++ crypto/rsa/benches/rsa_8192_benches.rs | 12 ++ crypto/rsa/src/eme_oaep.rs | 74 ++++++--- crypto/rsa/src/mgf1.rs | 10 +- crypto/rsa/src/rsaes_oaep.rs | 136 ++++++++++------ crypto/rsa/src/rsasve.rs | 2 +- crypto/rsa/tests/rsaes_oaep_tests.rs | 211 ++++++++++++++++++++++++- 9 files changed, 381 insertions(+), 90 deletions(-) diff --git a/crypto/rsa/Cargo.toml b/crypto/rsa/Cargo.toml index 4ace0ab9..43d1aebb 100644 --- a/crypto/rsa/Cargo.toml +++ b/crypto/rsa/Cargo.toml @@ -9,6 +9,7 @@ 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 @@ -16,7 +17,6 @@ bouncycastle-utils.workspace = true [dev-dependencies] bouncycastle-core-test-framework.workspace = true bouncycastle-hex.workspace = true -bouncycastle-sha1.workspace = true criterion.workspace = true serde_json = "1.0" diff --git a/crypto/rsa/benches/rsa_3072_benches.rs b/crypto/rsa/benches/rsa_3072_benches.rs index 6ac680ec..6e364021 100644 --- a/crypto/rsa/benches/rsa_3072_benches.rs +++ b/crypto/rsa/benches/rsa_3072_benches.rs @@ -7,7 +7,9 @@ use bouncycastle_core::signature_key::{DeterministicSigningKey, SigningKey, Veri 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; @@ -206,6 +208,16 @@ fn bench_rsa_3072(c: &mut Criterion) { 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; diff --git a/crypto/rsa/benches/rsa_4096_benches.rs b/crypto/rsa/benches/rsa_4096_benches.rs index 6318cb36..463cd947 100644 --- a/crypto/rsa/benches/rsa_4096_benches.rs +++ b/crypto/rsa/benches/rsa_4096_benches.rs @@ -8,6 +8,8 @@ use bouncycastle_core::signature_key::{DeterministicSigningKey, SigningKey, Veri 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; @@ -216,6 +218,16 @@ fn bench_rsa_4096(c: &mut Criterion) { 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(); } diff --git a/crypto/rsa/benches/rsa_8192_benches.rs b/crypto/rsa/benches/rsa_8192_benches.rs index e9e788da..a7c97e3a 100644 --- a/crypto/rsa/benches/rsa_8192_benches.rs +++ b/crypto/rsa/benches/rsa_8192_benches.rs @@ -8,6 +8,8 @@ use bouncycastle_core::signature_key::{DeterministicSigningKey, SigningKey, Veri 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; @@ -239,6 +241,16 @@ fn bench_rsa_8192(c: &mut Criterion) { 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(); } diff --git a/crypto/rsa/src/eme_oaep.rs b/crypto/rsa/src/eme_oaep.rs index bf02e88e..51044e7d 100644 --- a/crypto/rsa/src/eme_oaep.rs +++ b/crypto/rsa/src/eme_oaep.rs @@ -7,7 +7,7 @@ //! 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 copies the message out without branching or +//! 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}; @@ -15,17 +15,28 @@ 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 { - let x = value_barrier(x as u32); - // x | -x has its top bit set exactly when x is not zero. - (((x | x.wrapping_neg()) >> 31) as u8).wrapping_neg() + 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 { - let x = value_barrier(a ^ b); - !(((x | x.wrapping_neg()) >> 31) as u8).wrapping_neg() + // 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`. @@ -101,11 +112,11 @@ where // 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'". `bad` gathers all three, and the length checks below. + // "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(h_len); + 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) { + for (a, b) in l_hash.iter().zip(l_hash_prime.iter()) { diff |= a ^ b; } bad |= nonzero_mask(diff); @@ -117,12 +128,12 @@ where let mut index = 0u32; for (i, b) in ps_and_m.iter().enumerate() { let nonzero = nonzero_mask(*b); - let first = nonzero & !found; + let first = value_barrier(nonzero & !found); bad |= first & nonzero_mask(*b ^ 0x01); - // index = first ? i : index - let first32 = (first as u32).wrapping_mul(0x0101_0101); - index = (first32 & i as u32) | (!first32 & index); - found |= nonzero; + // 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; @@ -133,25 +144,36 @@ where Some(len) => bad |= !eq_mask_u32(m_len, len as u32), // m_len > out.len(): the subtraction borrows. None => { - bad |= ((((out.len() as u32).wrapping_sub(value_barrier(m_len))) >> 31) as u8) - .wrapping_neg() + let borrow = value_barrier((out.len() as u32).wrapping_sub(value_barrier(m_len)) >> 31); + bad |= value_barrier((borrow as u8).wrapping_neg()); } } - // out[j] = ps_and_m[m_start + j], taken by scanning every octet of DB for every octet of - // the output, so that no address depends on m_start. Positions past the message stay zero. - let good = !bad; - for (j, o) in out.iter_mut().enumerate() { - let want = m_start.wrapping_add(j as u32); - let mut byte = 0u8; - for (i, b) in ps_and_m.iter().enumerate() { - byte |= b & eq_mask_u32(i as u32, want); + // 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); } - *o = byte & good; + 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 bad != 0 { + if value_barrier(bad) != 0 { return None; } Some(m_len as usize) diff --git a/crypto/rsa/src/mgf1.rs b/crypto/rsa/src/mgf1.rs index 78ec6c07..4ef3b63c 100644 --- a/crypto/rsa/src/mgf1.rs +++ b/crypto/rsa/src/mgf1.rs @@ -1,7 +1,7 @@ -//! MGF1 (RFC 8017 Appendix B.2.1): a mask generation function based on a hash function, used by -//! [`crate::emsa_pss`]. Specialized to PSS's own call shape (`MGF(H, maskLen)`, where `H` is -//! always the hash's own `hLen`-byte output) rather than MGF1's fully general arbitrary-length -//! seed: `mgfSeed` here is always exactly `H_LEN` bytes. +//! 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; @@ -46,7 +46,7 @@ pub fn mgf1(seed: &[u8], mask: &mut [u8]) { 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), + // "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(); diff --git a/crypto/rsa/src/rsaes_oaep.rs b/crypto/rsa/src/rsaes_oaep.rs index 80abbdd2..3f27e453 100644 --- a/crypto/rsa/src/rsaes_oaep.rs +++ b/crypto/rsa/src/rsaes_oaep.rs @@ -24,16 +24,15 @@ //! 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. -//! * **SHA-1** (`bouncycastle_sha1::SHA1`) is accepted as either hash, for peers that use it. +//! * **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}; +use crate::rsasve::{RsaKEMPrivateKey, RsaKEMPublicKey, in_open_range}; use crate::size::{RsaSigningSize, RsaSize}; use bouncycastle_core::errors::{KEMError, KeyMaterialError, KeyTransportError, RNGError}; -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::key_transport_key::{ @@ -43,10 +42,36 @@ 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. @@ -55,8 +80,9 @@ pub struct RSAES_OAEP { _params: PhantomData<(K, H, M)>, } -/// What a hash output of `h_len` bytes can carry as a preimage strength: OAEP's hashes are -/// used as random oracles, not for collision resistance. +/// 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, @@ -71,7 +97,7 @@ const fn min_strength(a: SecurityStrength, b: SecurityStrength) -> SecurityStren if (a as u8) < (b as u8) { a } else { b } } -impl RSAES_OAEP { +impl RSAES_OAEP { const NAME: ConstStr<64> = ConstStr::concat(&["RSAES-OAEP-", K::BITS_NAME, "-", H::ALG_NAME, "-MGF1-", M::ALG_NAME]); @@ -89,20 +115,21 @@ impl RSAES_OAEP { }; } -impl Algorithm for RSAES_OAEP { +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 KEMAlgorithm for RSAES_OAEP {} -impl KeyTransportAlgorithm 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: +/// 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; @@ -149,8 +176,8 @@ fn encrypt( ) -> Result<(), RNGError> where K: RsaSize, - H: HashOneShot + HashAlgParams, - M: HashOneShot + HashAlgParams, + H: OaepHash, + M: OaepHash, { ct.fill(0); let h_len = H::OUTPUT_LEN; @@ -184,15 +211,17 @@ fn decrypt( ) -> Option where K: RsaSigningSize + RsaSize, - H: HashOneShot + HashAlgParams, - M: HashOneShot + HashAlgParams, + H: OaepHash, + M: OaepHash, { out.fill(0); - // Step 2.a, 2.b: c = OS2IP(C); "If RSADP outputs 'ciphertext representative out of range' - // (meaning that c >= n), output 'decryption error' and stop". The ciphertext and the - // modulus are public, so this branch tells an observer nothing it could not compute. + // 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 !K::is_less(&c, sk.n()) { + 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). @@ -207,30 +236,30 @@ where } /// 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. +/// `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(); - let result = do_hazardous_operations(key, |key| { - // An empty or all-zero key is typed Zeroized by the buffer and carries no strength; - // that is a value, not an error. - match key.set_bytes_as_type(bytes, KeyType::CryptographicRandom) { - Ok(()) => {} - Err(KeyMaterialError::ActingOnZeroizedKey) => return Ok(()), - Err(e) => return Err(e), + 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 { - key.set_security_strength(strength)?; + } + 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(()) - }); - if result.is_err() { - key.zeroize(); } - result + Ok(()) } /// The worker [`EncapsulatingKey::create_encapsulator`] hands out under [`OaepParams`]: the @@ -240,7 +269,7 @@ pub struct RsaOaepEncapsulator<'k, 'l, K: RsaSize, H, M, const LEN: usize> { params: OaepParams<'l, H, M, LEN>, } -impl Algorithm +impl Algorithm for RsaOaepEncapsulator<'_, '_, K, H, M, LEN> { const ALG_NAME: &'static str = RSAES_OAEP::::ALG_NAME; @@ -251,8 +280,8 @@ impl KEMEncapsulator for RsaOaepEncapsulator<'_, '_, K, H, M, LEN> where K: RsaSize, - H: HashOneShot + HashAlgParams, - M: HashOneShot + HashAlgParams, + 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 @@ -289,7 +318,7 @@ pub struct RsaOaepDecapsulator<'k, 'l, K: RsaSize, H, M, const LEN: usize> { params: OaepParams<'l, H, M, LEN>, } -impl Algorithm +impl Algorithm for RsaOaepDecapsulator<'_, '_, K, H, M, LEN> { const ALG_NAME: &'static str = RSAES_OAEP::::ALG_NAME; @@ -300,8 +329,8 @@ impl KEMDecapsulator for RsaOaepDecapsulator<'_, '_, K, H, M, LEN> where K: RsaSigningSize + RsaSize, - H: HashOneShot + HashAlgParams, - M: HashOneShot + HashAlgParams, + 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. @@ -323,8 +352,8 @@ impl<'l, K, H, M, const N: usize, const LEN: usize> EncapsulatingKey, N, LEN> for RsaKEMPublicKey where K: RsaSize, - H: HashOneShot + HashAlgParams, - M: HashOneShot + HashAlgParams, + H: OaepHash, + M: OaepHash, { type Algorithm = RSAES_OAEP; type Encapsulator<'k> @@ -337,7 +366,10 @@ where &'k self, params: OaepParams<'l, H, M, LEN>, ) -> Result, KEMError> { - const { assert!(LEN <= RSAES_OAEP::::MAX_MESSAGE_LEN, "LEN > k - 2hLen - 2") }; + 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 }) } } @@ -346,8 +378,8 @@ impl<'l, K, H, M, const N: usize, const LEN: usize> DecapsulatingKey, N, LEN> for RsaKEMPrivateKey where K: RsaSigningSize + RsaSize, - H: HashOneShot + HashAlgParams, - M: HashOneShot + HashAlgParams, + H: OaepHash, + M: OaepHash, { type Algorithm = RSAES_OAEP; type Decapsulator<'k> @@ -360,7 +392,10 @@ where &'k self, params: OaepParams<'l, H, M, LEN>, ) -> Result, KEMError> { - const { assert!(LEN <= RSAES_OAEP::::MAX_MESSAGE_LEN, "LEN > k - 2hLen - 2") }; + 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 }) } } @@ -371,8 +406,8 @@ impl<'l, K, H, M, const N: usize, const LEN: usize> KeyTransportEncryptingKey, N> for RsaKEMPublicKey where K: RsaSize, - H: HashOneShot + HashAlgParams, - M: HashOneShot + HashAlgParams, + H: OaepHash, + M: OaepHash, { type Algorithm = RSAES_OAEP; @@ -392,7 +427,8 @@ where 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'". + // 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); } @@ -410,8 +446,8 @@ impl<'l, K, H, M, const N: usize, const LEN: usize> KeyTransportDecryptingKey, N> for RsaKEMPrivateKey where K: RsaSigningSize + RsaSize, - H: HashOneShot + HashAlgParams, - M: HashOneShot + HashAlgParams, + H: OaepHash, + M: OaepHash, { type Algorithm = RSAES_OAEP; diff --git a/crypto/rsa/src/rsasve.rs b/crypto/rsa/src/rsasve.rs index 0087d922..57986695 100644 --- a/crypto/rsa/src/rsasve.rs +++ b/crypto/rsa/src/rsasve.rs @@ -92,7 +92,7 @@ fn has_full_bit_length(n: &K::Limbs) -> bool { } /// Whether `1 < x < n - 1` (§7.2.1.2 step 2's range, §7.2.1.3 step 1's check). -fn in_open_range(x: &K::Limbs, n: &K::Limbs) -> bool { +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; diff --git a/crypto/rsa/tests/rsaes_oaep_tests.rs b/crypto/rsa/tests/rsaes_oaep_tests.rs index 26fbe5ee..05a4e4ce 100644 --- a/crypto/rsa/tests/rsaes_oaep_tests.rs +++ b/crypto/rsa/tests/rsaes_oaep_tests.rs @@ -17,13 +17,13 @@ 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, HashAlgParams, HashOneShot, PrivateKey}; +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::{OaepParams, RSAES_OAEP}; +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}; @@ -32,6 +32,116 @@ 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); @@ -51,8 +161,8 @@ fn be_bytes(hex: &str, len: usize) -> Vec { fn run_group(group: &Value) -> Counts where K: RsaSigningSize + RsaSize, - H: HashOneShot + HashAlgParams, - M: HashOneShot + HashAlgParams, + H: OaepHash, + M: OaepHash, { // The private key's encoding is p || q || dP || dQ || qInv, each half the modulus long. let key = &group["privateKey"]; @@ -80,6 +190,13 @@ where "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" => { @@ -90,6 +207,18 @@ where 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) } @@ -97,7 +226,7 @@ where fn with_mgf(group: &Value) -> Counts where K: RsaSigningSize + RsaSize, - H: HashOneShot + HashAlgParams, + H: OaepHash, { match group["mgfSha"].as_str().unwrap() { "SHA-1" => run_group::(group), @@ -286,7 +415,10 @@ fn the_kem_and_the_transport_roles_interoperate() { fn ciphertexts_out_of_range_are_refused() { let [(_, sk), _] = key_pairs(); let params = OaepParams::::new(b""); - for ct in [[0xFFu8; 256], [0u8; 256]] { + // 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!( @@ -328,7 +460,7 @@ fn names_and_strengths() { } /// The RNG must offer the algorithm's strength, and exactly that is enough, for both roles; a -/// weaker one is refused before anything is drawn, with the outputs left zeroized. +/// weaker one is refused, with the outputs left zeroized. #[test] fn the_rng_must_offer_the_algorithms_strength() { let [(pk, sk), _] = key_pairs(); @@ -361,3 +493,68 @@ fn the_rng_must_offer_the_algorithms_strength() { ); 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); +} From 6d6f6f6a2b03408d5a0e0dd6c1f818381fef2b8f Mon Sep 17 00:00:00 2001 From: David Hook Date: Tue, 17 Nov 2026 20:52:43 +1100 Subject: [PATCH 52/55] cli: the rsa-oaep commands bound their hashes on OaepHash The generic actions take H: OaepHash, M: OaepHash, the trait bouncycastle-rsa now seals over RFC 8017's digest algorithms; the hashes the command offers are unchanged. Assisted-by: Claude:claude-mythos-5-2 --- cli/src/rsa_oaep_cmd.rs | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/cli/src/rsa_oaep_cmd.rs b/cli/src/rsa_oaep_cmd.rs index 20dd684a..f35cc57b 100644 --- a/cli/src/rsa_oaep_cmd.rs +++ b/cli/src/rsa_oaep_cmd.rs @@ -15,9 +15,9 @@ use crate::helpers::{ 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::{HashAlgParams, HashOneShot, PrivateKey, PublicKey}; +use bouncycastle::core::traits::{PrivateKey, PublicKey}; use bouncycastle::rng::HashDRBG_SHA512; -use bouncycastle::rsa::rsaes_oaep::OaepParams; +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}; @@ -98,8 +98,8 @@ fn run( PublicKeyEncoded = [u8; PK_LEN], PrivateKeyEncoded = [u8; SK_LEN], >, - H: HashOneShot + HashAlgParams, - M: HashOneShot + HashAlgParams, + 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); @@ -226,7 +226,7 @@ fn with_mgf( PublicKeyEncoded = [u8; PK_LEN], PrivateKeyEncoded = [u8; SK_LEN], >, - H: HashOneShot + HashAlgParams, + H: OaepHash, { match args.mgf_hash.unwrap_or(args.hash) { RSAOAEPHash::Sha1 => run::(args, alg_name), From 7661f53382591768c27dccabea248ee272fa875f Mon Sep 17 00:00:00 2001 From: David Hook Date: Tue, 17 Nov 2026 20:52:43 +1100 Subject: [PATCH 53/55] core-test-framework: wycheproof() falls back to the copies in bc-test-data Without a Wycheproof checkout beside the repository, the loader reads bc-test-data/crypto/wycheproof/, and skips a file that has not been copied there, the copies being a selection; with the checkout nothing changes. bc-test-data gains the 22 rsa_oaep_*_test.json files (upstream 3fa63dd0344a), so the RSAES-OAEP Wycheproof tests run from bc-test-data alone: checked in a checkout with no Wycheproof beside it, where both tests ran and passed with their asserted counts. Assisted-by: Claude:claude-mythos-5-2 --- .../src/test_data_loaders.rs | 28 +++++++++++++++++-- 1 file changed, 25 insertions(+), 3 deletions(-) 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. From a1d124e9f1ad4b6701253e7eb5fe5181b6ce8ab8 Mon Sep 17 00:00:00 2001 From: David Hook Date: Tue, 17 Nov 2026 20:52:43 +1100 Subject: [PATCH 54/55] dev_scripts: a constant-time check of the EME-OAEP decoding, run on pull requests dev_scripts/check_oaep_ct.sh, over dev_scripts/oaep_ct_harness, which includes crypto/rsa/src/eme_oaep.rs by path with the MGF an opaque call and a stub for the two bouncycastle-core trait names the file imports (core is not yet no_std). On the host it runs decode_out under valgrind memcheck with the encoded message undefined, on the any-length and exact-length paths, and requires a variable-time separator search over the same bytes to be reported, so a memcheck that reports nothing is noticed. For thumbv6m and riscv32i it requires the assembly of decode_out to hold no multiply or divide and no call but the buffer clear, the two MGF calls and the length-check panics, and to show the two MGF calls. Branches are not grepped for, the decode's loops branching on lengths; the memcheck run covers them. Before this the assembly was read by hand on x86-64, aarch64, thumbv6m, thumbv7em, riscv32i, riscv64gc and i686: every branch is on a length or on whether an exact length was asked for, and the result is produced by a set-on-condition. .github/workflows/oaep-ct.yml runs the script; CLAUDE.md's toolchain and CI sections and the 0.1.4 release notes name it. Verified on the branch: the workspace suite (3470 tests), the all-targets build with no warnings, rustdoc with warnings denied and nightly rustfmt. Assisted-by: Claude:claude-mythos-5-2 --- .github/workflows/oaep-ct.yml | 29 ++++++ .gitignore | 1 + CLAUDE.md | 8 +- alpha_0.1.4_release_notes.md | 5 +- dev_scripts/check_oaep_ct.sh | 93 +++++++++++++++++++ dev_scripts/oaep_ct_harness/Cargo.toml | 18 ++++ .../oaep_ct_harness/src/bin/memcheck.rs | 46 +++++++++ dev_scripts/oaep_ct_harness/src/lib.rs | 51 ++++++++++ .../oaep_ct_harness/stub_core/Cargo.toml | 5 + .../oaep_ct_harness/stub_core/src/lib.rs | 13 +++ 10 files changed, 266 insertions(+), 3 deletions(-) create mode 100644 .github/workflows/oaep-ct.yml create mode 100755 dev_scripts/check_oaep_ct.sh create mode 100644 dev_scripts/oaep_ct_harness/Cargo.toml create mode 100644 dev_scripts/oaep_ct_harness/src/bin/memcheck.rs create mode 100644 dev_scripts/oaep_ct_harness/src/lib.rs create mode 100644 dev_scripts/oaep_ct_harness/stub_core/Cargo.toml create mode 100644 dev_scripts/oaep_ct_harness/stub_core/src/lib.rs 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 2749f82d..44eeccb2 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 @@ -395,7 +395,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. - `rust-test.yml`: `cargo test --all` on stable. @@ -404,6 +404,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/alpha_0.1.4_release_notes.md b/alpha_0.1.4_release_notes.md index 69dc7aa4..e9dc7670 100644 --- a/alpha_0.1.4_release_notes.md +++ b/alpha_0.1.4_release_notes.md @@ -62,7 +62,10 @@ `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 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/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/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; + } +} From b7e46cb0448694a631971e3922029c59b9a7da06 Mon Sep 17 00:00:00 2001 From: David Hook Date: Thu, 19 Nov 2026 22:26:59 +1100 Subject: [PATCH 55/55] rsa: the RSA keys implement the one-shot signature roles Release now has the one-shot roles as supertraits of the streaming ones, so after the merge the RSA keys need them to build: - OneShotSigningKey (PSS), DeterministicOneShotSigningKey (PKCS#1 v1.5) and OneShotVerifyingKey, beside the streaming impls with the same bounds, over sign_out_with_signer / verify_with_verifier. - Callers of sign, sign_deterministic and verify in the rsa tests and benches, the CLI and the stack benches import the one-shot traits. The framework's new assertions hold for RSA: a context is ignored, and PSS sign_out under a failing RNG returns RNGError with the buffer zeroized. Workspace suite 3655 passed; all-targets build, rustdoc and rustfmt clean. Assisted-by: Claude:claude-mythos-5-2 --- cli/tests/rsa_cli_tests.rs | 2 +- crypto/rsa/benches/rsa_1024_benches.rs | 2 +- crypto/rsa/benches/rsa_1536_benches.rs | 2 +- crypto/rsa/benches/rsa_2048_benches.rs | 4 +- crypto/rsa/benches/rsa_3072_benches.rs | 4 +- crypto/rsa/benches/rsa_4096_benches.rs | 4 +- crypto/rsa/benches/rsa_8192_benches.rs | 4 +- crypto/rsa/src/lib.rs | 4 +- crypto/rsa/src/rsassa.rs | 48 ++++++++++++++++++- crypto/rsa/tests/keygen_tests.rs | 4 +- crypto/rsa/tests/rsa_1024_tests.rs | 2 +- crypto/rsa/tests/rsa_1536_tests.rs | 2 +- ...rsa_2048_pkcs1_v1_5_sha384_sha512_tests.rs | 2 +- crypto/rsa/tests/rsa_2048_pkcs1_v1_5_tests.rs | 4 +- crypto/rsa/tests/rsa_2048_pss_params_tests.rs | 5 +- .../tests/rsa_2048_pss_sha384_sha512_tests.rs | 2 +- .../rsa/tests/rsa_2048_pss_shake128_tests.rs | 4 +- crypto/rsa/tests/rsa_2048_pss_tests.rs | 4 +- .../rsa/tests/rsa_3072_pss_shake128_tests.rs | 2 +- crypto/rsa/tests/rsa_3072_tests.rs | 4 +- .../rsa/tests/rsa_4096_pss_shake256_tests.rs | 2 +- crypto/rsa/tests/rsa_4096_tests.rs | 5 +- crypto/rsa/tests/rsa_8192_tests.rs | 5 +- mem_usage_benches/src/bench_rsa_mem_usage.rs | 5 +- 24 files changed, 101 insertions(+), 25 deletions(-) diff --git a/cli/tests/rsa_cli_tests.rs b/cli/tests/rsa_cli_tests.rs index 0b338182..4f98d448 100644 --- a/cli/tests/rsa_cli_tests.rs +++ b/cli/tests/rsa_cli_tests.rs @@ -8,7 +8,7 @@ //! `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::{DeterministicSigningKey, VerifyingKey}; +use bouncycastle::core::signature_key::{DeterministicOneShotSigningKey, OneShotVerifyingKey}; use bouncycastle::core::traits::{PrivateKey, PublicKey}; use bouncycastle::rsa::RSA2048; use bouncycastle::rsa::keys::{ diff --git a/crypto/rsa/benches/rsa_1024_benches.rs b/crypto/rsa/benches/rsa_1024_benches.rs index 8f7f5bc4..64034a00 100644 --- a/crypto/rsa/benches/rsa_1024_benches.rs +++ b/crypto/rsa/benches/rsa_1024_benches.rs @@ -3,7 +3,7 @@ //! `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::VerifyingKey; +use bouncycastle_core::signature_key::OneShotVerifyingKey; use criterion::{Criterion, criterion_group, criterion_main}; use std::hint::black_box; diff --git a/crypto/rsa/benches/rsa_1536_benches.rs b/crypto/rsa/benches/rsa_1536_benches.rs index 67045598..7a85fbce 100644 --- a/crypto/rsa/benches/rsa_1536_benches.rs +++ b/crypto/rsa/benches/rsa_1536_benches.rs @@ -3,7 +3,7 @@ //! `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::VerifyingKey; +use bouncycastle_core::signature_key::OneShotVerifyingKey; use criterion::{Criterion, criterion_group, criterion_main}; use std::hint::black_box; diff --git a/crypto/rsa/benches/rsa_2048_benches.rs b/crypto/rsa/benches/rsa_2048_benches.rs index 6a88b74d..e5f6c5b4 100644 --- a/crypto/rsa/benches/rsa_2048_benches.rs +++ b/crypto/rsa/benches/rsa_2048_benches.rs @@ -5,7 +5,9 @@ //! `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::{DeterministicSigningKey, SigningKey, VerifyingKey}; +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}; diff --git a/crypto/rsa/benches/rsa_3072_benches.rs b/crypto/rsa/benches/rsa_3072_benches.rs index 6e364021..56e3dd56 100644 --- a/crypto/rsa/benches/rsa_3072_benches.rs +++ b/crypto/rsa/benches/rsa_3072_benches.rs @@ -3,7 +3,9 @@ //! `rsa_pkcs1_3072_sig_gen_test.json`. use bouncycastle_core::kem_key::{DecapsulatingKey, EncapsulatingKey}; -use bouncycastle_core::signature_key::{DeterministicSigningKey, SigningKey, VerifyingKey}; +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}; diff --git a/crypto/rsa/benches/rsa_4096_benches.rs b/crypto/rsa/benches/rsa_4096_benches.rs index 463cd947..a5e3f0fd 100644 --- a/crypto/rsa/benches/rsa_4096_benches.rs +++ b/crypto/rsa/benches/rsa_4096_benches.rs @@ -4,7 +4,9 @@ //! this modulus size (RFC 8702 SS5). use bouncycastle_core::kem_key::{DecapsulatingKey, EncapsulatingKey}; -use bouncycastle_core::signature_key::{DeterministicSigningKey, SigningKey, VerifyingKey}; +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}; diff --git a/crypto/rsa/benches/rsa_8192_benches.rs b/crypto/rsa/benches/rsa_8192_benches.rs index a7c97e3a..1c1df9d4 100644 --- a/crypto/rsa/benches/rsa_8192_benches.rs +++ b/crypto/rsa/benches/rsa_8192_benches.rs @@ -4,7 +4,9 @@ //! 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::{DeterministicSigningKey, SigningKey, VerifyingKey}; +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}; diff --git a/crypto/rsa/src/lib.rs b/crypto/rsa/src/lib.rs index bd1587be..6429088f 100644 --- a/crypto/rsa/src/lib.rs +++ b/crypto/rsa/src/lib.rs @@ -75,7 +75,7 @@ //! uses every signature scheme. The key names its scheme, so the calls name nothing: //! //! ``` -//! use bouncycastle_core::signature_key::{DeterministicSigningKey, SigningKey, VerifyingKey}; +//! 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}; @@ -153,7 +153,7 @@ //! signatures (`tests/rsa_1024_tests.rs` has the full, sourced provenance): //! //! ``` -//! use bouncycastle_core::signature_key::VerifyingKey; +//! 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]; diff --git a/crypto/rsa/src/rsassa.rs b/crypto/rsa/src/rsassa.rs index e9c37713..ca33291a 100644 --- a/crypto/rsa/src/rsassa.rs +++ b/crypto/rsa/src/rsassa.rs @@ -17,7 +17,9 @@ use crate::size::{RsaSigningSize, RsaSize}; use bouncycastle_core::errors::SignatureError; use bouncycastle_core::security_strength::SecurityStrength; use bouncycastle_core::signature_key::{ - DeterministicSigningKey, SignatureAlgorithm, SigningKey, VerifyingKey, + 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, @@ -117,6 +119,23 @@ where } } +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, @@ -136,6 +155,22 @@ where } } +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, @@ -155,6 +190,17 @@ where } } +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 diff --git a/crypto/rsa/tests/keygen_tests.rs b/crypto/rsa/tests/keygen_tests.rs index c8404aa9..c8e6ec0d 100644 --- a/crypto/rsa/tests/keygen_tests.rs +++ b/crypto/rsa/tests/keygen_tests.rs @@ -21,7 +21,9 @@ use bouncycastle_core::errors::{RNGError, SignatureError}; use bouncycastle_core::security_strength::SecurityStrength; -use bouncycastle_core::signature_key::{DeterministicSigningKey, SigningKey, VerifyingKey}; +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; diff --git a/crypto/rsa/tests/rsa_1024_tests.rs b/crypto/rsa/tests/rsa_1024_tests.rs index 3a3774dd..85a9b890 100644 --- a/crypto/rsa/tests/rsa_1024_tests.rs +++ b/crypto/rsa/tests/rsa_1024_tests.rs @@ -7,7 +7,7 @@ //! differently-shaped file because Wycheproof has no dedicated `rsa_signature_1024_*.json`. use bouncycastle_core::errors::{KeyDecodingError, SignatureError}; -use bouncycastle_core::signature_key::VerifyingKey; +use bouncycastle_core::signature_key::OneShotVerifyingKey; use bouncycastle_core::traits::PublicKey; use bouncycastle_hex::decode as hex_decode; use bouncycastle_rsa::RSA1024; diff --git a/crypto/rsa/tests/rsa_1536_tests.rs b/crypto/rsa/tests/rsa_1536_tests.rs index 7559bcc1..8cb8d815 100644 --- a/crypto/rsa/tests/rsa_1536_tests.rs +++ b/crypto/rsa/tests/rsa_1536_tests.rs @@ -5,7 +5,7 @@ //! material and this crate never constructs an RSA-1536 private key at all. use bouncycastle_core::errors::{KeyDecodingError, SignatureError}; -use bouncycastle_core::signature_key::VerifyingKey; +use bouncycastle_core::signature_key::OneShotVerifyingKey; use bouncycastle_core::traits::PublicKey; use bouncycastle_hex::decode as hex_decode; use bouncycastle_rsa::RSA1536; 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 index a48fc9f9..2fc1fa1c 100644 --- 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 @@ -14,7 +14,7 @@ //! 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::{DeterministicSigningKey, VerifyingKey}; +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; diff --git a/crypto/rsa/tests/rsa_2048_pkcs1_v1_5_tests.rs b/crypto/rsa/tests/rsa_2048_pkcs1_v1_5_tests.rs index e913d373..e9642868 100644 --- a/crypto/rsa/tests/rsa_2048_pkcs1_v1_5_tests.rs +++ b/crypto/rsa/tests/rsa_2048_pkcs1_v1_5_tests.rs @@ -32,7 +32,9 @@ //! constructed edge case. use bouncycastle_core::errors::SignatureError; -use bouncycastle_core::signature_key::{DeterministicSigningKey, VerifyingKey}; +use bouncycastle_core::signature_key::{ + DeterministicOneShotSigningKey, DeterministicSigningKey, OneShotVerifyingKey, +}; use bouncycastle_core::traits::{HashOneShot, SignatureSigner}; use bouncycastle_core_test_framework::signature::{ TestFrameworkSignature, TestFrameworkSignatureKeys, diff --git a/crypto/rsa/tests/rsa_2048_pss_params_tests.rs b/crypto/rsa/tests/rsa_2048_pss_params_tests.rs index 3e3d1973..bb17a0db 100644 --- a/crypto/rsa/tests/rsa_2048_pss_params_tests.rs +++ b/crypto/rsa/tests/rsa_2048_pss_params_tests.rs @@ -6,7 +6,10 @@ //! parameters, so the other set's signatures are invalid under it. use bouncycastle_core::security_strength::SecurityStrength; -use bouncycastle_core::signature_key::{DeterministicSigningKey, SigningKey, VerifyingKey}; +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; diff --git a/crypto/rsa/tests/rsa_2048_pss_sha384_sha512_tests.rs b/crypto/rsa/tests/rsa_2048_pss_sha384_sha512_tests.rs index 07f14deb..cc4f72b9 100644 --- a/crypto/rsa/tests/rsa_2048_pss_sha384_sha512_tests.rs +++ b/crypto/rsa/tests/rsa_2048_pss_sha384_sha512_tests.rs @@ -7,7 +7,7 @@ //! sig-gen key here (rather than factoring a fresh one) is the right tradeoff. use bouncycastle_core::errors::SignatureError; -use bouncycastle_core::signature_key::{SigningKey, VerifyingKey}; +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; diff --git a/crypto/rsa/tests/rsa_2048_pss_shake128_tests.rs b/crypto/rsa/tests/rsa_2048_pss_shake128_tests.rs index 772e1c58..4a1ec48b 100644 --- a/crypto/rsa/tests/rsa_2048_pss_shake128_tests.rs +++ b/crypto/rsa/tests/rsa_2048_pss_shake128_tests.rs @@ -6,7 +6,9 @@ //! checked against all of Wycheproof's real vectors. use bouncycastle_core::errors::SignatureError; -use bouncycastle_core::signature_key::{SigningKey, VerifyingKey}; +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; diff --git a/crypto/rsa/tests/rsa_2048_pss_tests.rs b/crypto/rsa/tests/rsa_2048_pss_tests.rs index 8f3513b9..5924e35f 100644 --- a/crypto/rsa/tests/rsa_2048_pss_tests.rs +++ b/crypto/rsa/tests/rsa_2048_pss_tests.rs @@ -11,7 +11,9 @@ //! by comparing moduli in Python before writing this file). use bouncycastle_core::errors::SignatureError; -use bouncycastle_core::signature_key::{SigningKey, VerifyingKey}; +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; diff --git a/crypto/rsa/tests/rsa_3072_pss_shake128_tests.rs b/crypto/rsa/tests/rsa_3072_pss_shake128_tests.rs index 986821b0..482ecb6a 100644 --- a/crypto/rsa/tests/rsa_3072_pss_shake128_tests.rs +++ b/crypto/rsa/tests/rsa_3072_pss_shake128_tests.rs @@ -4,7 +4,7 @@ //! `rsa_3072_tests.rs` recovered), and all of Wycheproof's real vectors for verification. use bouncycastle_core::errors::SignatureError; -use bouncycastle_core::signature_key::{SigningKey, VerifyingKey}; +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; diff --git a/crypto/rsa/tests/rsa_3072_tests.rs b/crypto/rsa/tests/rsa_3072_tests.rs index 733cd93d..006163c3 100644 --- a/crypto/rsa/tests/rsa_3072_tests.rs +++ b/crypto/rsa/tests/rsa_3072_tests.rs @@ -11,7 +11,9 @@ //! before being pasted here. use bouncycastle_core::errors::SignatureError; -use bouncycastle_core::signature_key::{DeterministicSigningKey, SigningKey, VerifyingKey}; +use bouncycastle_core::signature_key::{ + DeterministicOneShotSigningKey, OneShotSigningKey, OneShotVerifyingKey, SigningKey, +}; use bouncycastle_core::traits::SignatureSigner; use bouncycastle_core_test_framework::signature::{ TestFrameworkSignature, TestFrameworkSignatureKeys, diff --git a/crypto/rsa/tests/rsa_4096_pss_shake256_tests.rs b/crypto/rsa/tests/rsa_4096_pss_shake256_tests.rs index 5e70f5be..2708fbe3 100644 --- a/crypto/rsa/tests/rsa_4096_pss_shake256_tests.rs +++ b/crypto/rsa/tests/rsa_4096_pss_shake256_tests.rs @@ -3,7 +3,7 @@ //! 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::{SigningKey, VerifyingKey}; +use bouncycastle_core::signature_key::{OneShotSigningKey, OneShotVerifyingKey, SigningKey}; use bouncycastle_core::traits::SignatureSigner; use bouncycastle_hex::decode as hex_decode; use bouncycastle_rng::DefaultRNG; diff --git a/crypto/rsa/tests/rsa_4096_tests.rs b/crypto/rsa/tests/rsa_4096_tests.rs index 3e8617f7..bc749b8f 100644 --- a/crypto/rsa/tests/rsa_4096_tests.rs +++ b/crypto/rsa/tests/rsa_4096_tests.rs @@ -12,7 +12,10 @@ //! against all 8 of that group's real signatures before being pasted here. use bouncycastle_core::errors::SignatureError; -use bouncycastle_core::signature_key::{DeterministicSigningKey, SigningKey, VerifyingKey}; +use bouncycastle_core::signature_key::{ + DeterministicOneShotSigningKey, DeterministicSigningKey, OneShotSigningKey, + OneShotVerifyingKey, SigningKey, +}; use bouncycastle_core::traits::SignatureSigner; use bouncycastle_core_test_framework::signature::{ TestFrameworkSignature, TestFrameworkSignatureKeys, diff --git a/crypto/rsa/tests/rsa_8192_tests.rs b/crypto/rsa/tests/rsa_8192_tests.rs index b6083678..55060cb3 100644 --- a/crypto/rsa/tests/rsa_8192_tests.rs +++ b/crypto/rsa/tests/rsa_8192_tests.rs @@ -21,7 +21,10 @@ //! Wycheproof encodes for this hash is checked -- just not every repetition of it. use bouncycastle_core::errors::SignatureError; -use bouncycastle_core::signature_key::{DeterministicSigningKey, SigningKey, VerifyingKey}; +use bouncycastle_core::signature_key::{ + DeterministicOneShotSigningKey, DeterministicSigningKey, OneShotSigningKey, + OneShotVerifyingKey, SigningKey, +}; use bouncycastle_core::traits::SignatureSigner; use bouncycastle_core_test_framework::signature::{ TestFrameworkSignature, TestFrameworkSignatureKeys, diff --git a/mem_usage_benches/src/bench_rsa_mem_usage.rs b/mem_usage_benches/src/bench_rsa_mem_usage.rs index 84c4b82e..b4a0ccba 100644 --- a/mem_usage_benches/src/bench_rsa_mem_usage.rs +++ b/mem_usage_benches/src/bench_rsa_mem_usage.rs @@ -32,7 +32,10 @@ use bouncycastle::core::kem_key::{DecapsulatingKey, EncapsulatingKey}; use bouncycastle::core::key_material::KeyMaterialTrait; -use bouncycastle::core::signature_key::{DeterministicSigningKey, SigningKey, VerifyingKey}; +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::{