Skip to content

rsa: RSASSA-PKCS1-v1_5, RSASSA-PSS, PSS-SHAKE, RSASVE and RSAES-OAEP across RSA-1024 through 8192, with a SHA-1 crate - #146

Closed
dghgit wants to merge 144 commits into
release/0.1.4alphafrom
feature/rsa-sig
Closed

dghgit wants to merge 144 commits into
release/0.1.4alphafrom
feature/rsa-sig

Conversation

@dghgit

@dghgit dghgit commented Sep 20, 2026 •

Copy link
Copy Markdown
Contributor

Summary

RSA digital signatures, plus the RSASVE KEM, across a limited range of modulus sizes up to the maximum originally requested, 8192 bits: RSASSA-PKCS1-v1_5 and RSASSA-PSS (RFC 8017 §8), the latter with its parameters as a type, the conventional MGF1 pairing, PSS-SHAKE128/256 (RFC 8702 §3.2.1), another MGF1 hash or salt length (§8.1, Appendix A.2.3) and the zero salt (§9.1 note 4, deterministic), over RSA-1024/1536 (verify-only) through RSA-2048/3072/4096/8192 (sign+verify), on bouncycastle_core's key roles. The size is a marker type (RSA2048), a scheme is one generic marker over the size, the hash and its parameters (RSASSA_PSS<RSA2048, SHA256>, RSASSA_PSS<RSA2048, SHAKE128>, RSASSA_PSS<RSA2048, SHA512, Mgf1<SHA256, 32>>), and a key is a key for one of them: RsaPrivateKey<A> implements SigningKey or DeterministicSigningKey by what the scheme draws and RsaPublicKey<A> VerifyingKey, handing out SignatureSigner / SignatureVerifier workers, with the material behind them as RsaPrivateComponents<K> / RsaPublicComponents<K>. RSASVE (SP 800-56B Rev. 2 §7.2.1) is the KEM roles EncapsulatingKey / DecapsulatingKey over () on KEM-only key types at 2048/3072/4096/8192, and RSASVE_HKDF<K, H> the same roles over a KdfParams<HkdfDescription> for a derived secret. Key pair generation is FIPS 186-5 Appendix A.1.3, from the size marker for one scheme (RSA2048::generate_pss_signature_key_pair::<SHA256>(&mut rng)). A new crate, bouncycastle-rsa, with its CLI subcommands, criterion benches and stack-usage harness.

Since 9360265 the branch also carries RSAES-OAEP (RFC 8017 §7.1) on the same key-establishment keys, as a KEM that draws the key (KTS-OAEP-basic, SP 800-56B Rev. 2 §9.2.3) and as key transport for a key the caller holds, through new core::key_transport_key roles; and a second new crate, bouncycastle-sha1 (FIPS 180-4), for the label hash or MGF1 an older peer chose.

Description

  • Reuses bouncycastle_ec's constant-time fixed-width limb arithmetic (bouncycastle_ec::nat, bouncycastle_ec::montgomery) rather than a dedicated BigInteger type, for the same constant-time-on-secret-exponent 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 fixed-width operands. modexp is Montgomery exponentiation over a runtime modulus (f7f2f12); keys holds the CRT key types and rsa_core the CRT-based RSASP1/RSAVP1 (182eb3c).
  • 2048-8192 bit moduli support both signing and verification; 1024- and 1536-bit moduli are verification-only, enforced at compile time: the size markers implement size::RsaSize, and only those from 2048 up size::RsaSigningSize, on which the private key's constructors and encoder, the signing roles, RSASP1, key generation and the KEM private key are all written, so no private key value and no private-key arithmetic exists at the two legacy sizes (a compile_fail doctest in rsa_1024.rs pins it).
  • API shape: the EMSA/RSASSA layers take the message hash rather than the message (2c0166e), so the streaming workers share one encoding path; the crate is written once per scheme over the size marker (eb4aefd), the key types carry their algorithm (010cf1a) and RSASSA-PSS its parameters (5c31875). RSASSA_PKCS1_v1_5<K, H> and RSASSA_PSS<K, H, P = Conventional> (spec spelling per QUALITY_AND_STYLE) are the markers; P is rsassa_pss::PssParams<H>, the mask and the salt length: Conventional reads the hash's conventional pairing off PssHash (MGF1 over the hash with a salt one output long for SHA-2 and SHA-3, the XOF itself as the mask for SHAKE), Mgf1<M, SALT_LEN> spells another, NoSalt<M> is the zero salt and puts the key on the deterministic role. A key is RsaPrivateKey<A> / RsaPublicKey<A> over the components, so sk.sign(..) and pk.verify(..) resolve from the key, a PSS key cannot sign PKCS#1 v1.5 (SP 800-57 Part 1 Rev. 5's one scheme per key pair), and the components become a key for a scheme through key::<A>(); the roles are implemented once in rsassa over three algorithm traits, with three workers (RsaSigner with set_salt, RsaDeterministicSigner, RsaVerifier) and the *_from_hash entry points. Per-size alias modules (rsa_2048::RSASSA_PSS_SHA256, SIG_LEN) serve code at one size. The schemes were first wired as Signer / SignatureVerifier types (a996164), the per-size free functions dropped once the traits covered them (c84e7a6), and the whole ported onto the key role traits when those landed on the release (c6ea90d).
  • Key pair generation (db9c026): FIPS 186-5 Appendix A.1.3 (probable primes: trial division against the primes below 2^10, then Appendix B.3.1 Miller-Rabin with Table B.1's round counts; e = 65537; |p - q| and d > 2^(nlen/2) criteria from A.1.1), structured after BC Java's RSAKeyPairGenerator, on the crate's own limb arithmetic, no bignum dependency. Exposed on the signing sizes as size::SignatureKeyPair (RSA2048::generate_pkcs1_v1_5_signature_key_pair::<SHA256>(&mut rng), generate_pss_signature_key_pair::<H>, generate_pss_signature_key_pair_with::<H, P>, a pair for one algorithm, the hash spelled and never defaulted) and size::KemKeyPair, with RsaSigningSize::keygen giving the components; the RNG must be at least the modulus's strength. The private-key paths scrub what they derive from the primes (57c5c09).
  • RSASVE (b539612, e075ea6, c3129a3): the scheme BC FIPS Java 2.0 exposes as FipsRSA.KTS_SVE (JCA "RSA-KAS-KEM") and OpenSSL 3 as its "RSASVE" KEM operation. b539612 is a behaviour-preserving refactor that splits the exponentiation out of rsavp1/rsasp1 into crate-private public_exp/crt_exp, so RSASVE can reuse it under SP 800-56B's 1 < x < n - 1 range checks instead of RFC 8017's. The KEM-only key types RsaKEMPublicKey / RsaKEMPrivateKey keep key establishment and signing apart (§6.1 item 5) and add the §6.2.1 checks (e >= 65537, n of exactly nlen bits). After the squash of PR KEM encapsulation and decapsulation move onto the key objects (EncapsulatingKey / DecapsulatingKey, ML-KEM ported, KeyType::SharedSecret) #192 they implement the KEM roles over (), naming RSASVE as the algorithm, with RsasveEncapsulator::encaps_out as RSASVE.GENERATE and RsasveDecapsulator::decaps_out as RSASVE.RECOVER into the caller's buffers; the ciphertext is a [u8; CT_LEN], so a wrong length is a type error. The shared secret is the raw Z at the modulus's full length, typed CryptographicRandom at the modulus's strength, for the caller's KDF; RSASVE_HKDF<K, H> (rsasve_kdf, in eb4aefd) gives the same key types the KEM roles over KdfParams<HkdfDescription<H>>, SP 800-56B Rev. 2 Section 5.5's derivation of the secret from Z, the parameters being the library's HSM-readable description.
  • RSAES-OAEP (365c2f6, 6bdf390, 738ee9b, review fixes 1de17cd): RSAES_OAEP<K, H, M = H> over the size, the label hash and the MGF1 hash, with OaepParams<H, M, LEN> carrying the label and, for the KEM, the key length. RsaKEMPublicKey<K> / RsaKEMPrivateKey<K> implement the KEM roles over those parameters (encapsulation draws the key and encrypts it; SP 800-56B Rev. 2 §7.2.2 RSA-OAEP, §9.2.3 KTS-OAEP-basic) and the new core roles KeyTransportEncryptingKey / KeyTransportDecryptingKey (transport_out, recover_out, max_key_len, with KeyTransportError), for a key the caller already holds. H and M are bound on a sealed OaepHash, RFC 8017 Appendix A.2.1's seven digest algorithms (SHA-1, SHA-224, SHA-256, SHA-384, SHA-512, SHA-512/224, SHA-512/256); the algorithm's strength is the modulus's, capped by each hash's. A ciphertext is refused outside 1 < c < n - 1 (SP 800-56B Rev. 2 §7.2.2.4). The decoding (eme_oaep::decode_out, RFC 8017 §7.1.2 step 3) folds the three checks of step 3.g and the length checks into one mask, reads all of DB whatever it holds, and moves the message out by one conditional shift per bit of its offset, so no branch or address depends on the encoded message; the masks are built with utils::ct::value_barrier after each step, as that module builds its own. An independent review of the OAEP commits found no functional defect and no secret-dependent branch; its hardening, specification and test findings are 1de17cd.
  • A constant-time check of that decoding (a1d124e): dev_scripts/check_oaep_ct.sh over dev_scripts/oaep_ct_harness, which includes eme_oaep.rs by path. It runs decode_out under valgrind memcheck with the encoded message undefined, on both paths, and requires a variable-time control to be reported; and for thumbv6m and riscv32i it requires the assembly to hold no multiply, divide or unexpected call. A new workflow, oaep-ct.yml, runs it on pull requests. Before it was written the assembly was read by hand on seven targets (x86-64, aarch64, thumbv6m, thumbv7em, riscv32i, riscv64gc, i686): every branch is on a length or on whether an exact length was asked for.
  • SHA-1 (e34e4e1, b77923f, 4bddf06, 09e0768): bouncycastle-sha1, SHA1 on Hash, HashOneShot and Suspendable, written against FIPS 180-4 and laid out as the SHA-256 code is. Its MAX_SECURITY_STRENGTH is SecurityStrength::None, and the crate docs' Security Considerations say what it must not be used for. HashFactory knows it by name and the CLI has a sha1 command. There is no HMAC-SHA1 or HKDF-SHA1.
  • CLI subcommands rsa-<size>, rsasve-<size> and rsa-oaep-<size> (keygen, encaps, decaps, transport, recover, with --hash, --mgf-hash and --label), which stream stdin through the workers in this CLI's usual 1 KB chunks; the rsasve and rsa-oaep commands write private keys and secrets through the wiped writers (b97f976); criterion benches (including keygen at 2048/3072 and OAEP at every size); a stack-usage harness for RSA and one for SHA-1.

Scope and Risk

Two new crates (bouncycastle-rsa, bouncycastle-sha1) plus their factory and CLI wiring and mem_usage_benches harnesses, based on release/0.1.4alpha. Changes outside those: core gains the key-transport roles and KeyTransportError (additive), with a suite for them in core-test-framework; core-test-framework's Wycheproof loader falls back to the copies in bc-test-data/crypto/wycheproof when there is no Wycheproof checkout (7661f53), and bc-test-data gains the 22 rsa_oaep_* files and the SHA-1 CAVP files; a new CI workflow, oaep-ct.yml, which installs valgrind and nightly rust-src; utils::const_str::ConstStr::decimal, the digits of a number for an algorithm name (-MGF1-SHA256-32), with its tests; and core-test-framework's KEM suite (dce5490): its fixed 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; it is a 4096-byte hashed pattern now. The branch has taken each release tip by merge, most recently 8efc5bc (HPKE, the DHKEM crate and its follow-ups), as ee71323.

Validation

  • cargo test --workspace passes at the head a1d124e (3470 tests), all targets build with no warnings, rustdoc with warnings denied is clean, rustfmt is clean, and the rsa-* / rsasve-* / rsa-oaep-* CLI tests pass. For the crate: Wycheproof PKCS1-v1.5/PSS/PSS-SHAKE vectors per size and hash, its rsa_pss_2048_sha512_mgf1sha256_32_params and rsa_pss_2048_sha256_mgf1_0 files for the spelled parameters (178 and 103 vectors), BC Java cross-check vectors at 8192, core-test-framework's signature conformance suite for every pairing at every size, and its KEM conformance and key suites for RSASVE at every size.
  • RSASVE (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 recovering Z from C and an encapsulation fed the vector's Z reproducing its C, with the failChangedZ cases not matching; ACVP-Server RSA-DecryptionPrimitive-Sp800-56Br2, CRT groups at 2048/3072/4096 including the out-of-range ciphertexts; OpenSSL 3.0's "RSASVE" KEM operation at every size, 8192 included.
  • RSAES-OAEP (tests/rsaes_oaep_tests.rs): every Wycheproof rsa_oaep_* group at 2048, 3072, 4096 and 8192 bits, 569 valid and 389 invalid cases, each valid group also round-tripped through encryption (the 140 cases of rsa_oaep_misc at sizes with no key type here are skipped); three Wycheproof cases printed in the file, so known answers run without the checkout; BC Java 1.84 in both directions for five hash pairings; core-test-framework's KEM suite and the new key-transport suite; c = 1 refused, a failing RNG, the zero-length and all-zero keys' typing, and the strength rules. ./dev_scripts/check_oaep_ct.sh passes locally; the workflow itself has not run yet.
  • SHA-1: NIST CAVP SHAVS vectors, byte- and bit-oriented, short, long and Monte Carlo (bc-test-data/crypto/sha1); RFC 3174 §7.3's four results; the shared hash and suspended-state frameworks.
  • ./dev_scripts/quality_stats.sh at the head: crypto/rsa 3683 code lines, 1470 docstring lines, test ratio 1.39, 6 unwraps and 47 Err() sites in core code (3208, 1309, 1.45, 5 and 36 at 9360265); crypto/sha1 218 code lines, 124 docstring lines, test ratio 1.63, 4 unwraps and 4 Err() sites.
  • cargo mutants, as reported in the comments below (the hashes there belong to the pre-rebase history): the full-crate run of the pre-trait-wiring state, 646 mutants, 446 caught, 6 missed (documented OR/XOR and boundary equivalents), 3 timeouts, 191 unviable; the scoped run over the 14 trait-wiring and keygen files, 751 mutants, 476 caught, 0 missed, 180 unviable, 95 timeouts, of which the --iterate --timeout 7200 re-run left 14 genuine infinite loops, all itemised; RSASVE's rsasve.rs and the KEM code of the four size modules, 168 mutants, 72 caught, 0 missed, 95 unviable, one real hang (attempts += 1 to *= 1 removes the draw cap). Since then, each squash carries its own scoped run in its message: the size markers and RSASVE-HKDF (eb4aefd), 1168 mutants, 639 caught, 362 unviable, 25 timeouts, 142 missed and itemised, keygen.rs's slow nondeterministic ones among them; the scheme keys (010cf1a), 505 mutants, 162 caught, 330 unviable, 2 timeouts, 11 missed; the PSS parameters (5c31875), 481 mutants, 187 caught, 264 unviable, no timeouts, 27 missed after the targeted re-runs, plus utils const_str.rs, 39 mutants, 19 caught, 19 unviable, 1 build-time hang. Each squash message itemises its misses. For the work since 9360265: SHA-1 138 mutants, 128 caught, 5 unviable, 5 missed (the or/xor swaps in Ch and Maj and two in the padding, all equivalent); the OAEP modules after the review fixes 143, 115 caught, 21 unviable, 2 timeouts (the decode's shift loop made endless), 5 missed and equivalent (| to ^ on disjoint masks and in the not-zero identity, two boundary swaps that change nothing), itemised in 1de17cd; the core key-transport defaults 4, 2 caught, 2 unviable.

AI Usage Statement

  • Yes, non-trivial code changes were generated by AI

Assisted-by: Claude:claude-sonnet-5
Assisted-by: Claude:claude-fable-5-1
Assisted-by: Claude:claude-opus-5-5
Assisted-by: Claude:claude-mythos-5-1
Assisted-by: Claude:claude-mythos-5-2

🤖 Generated with Claude Code

@dghgit

dghgit commented Sep 21, 2026

Copy link
Copy Markdown
Contributor Author

cargo mutants -- full-crate confirmation run, pre-trait-wiring state (61aa840)

Completed on separate hardware (mirroring PR #143's approach): 646/646 mutants, 446 caught, 6 missed, 3 timeout, 191 unviable.

All 9 non-caught findings are already-documented equivalents/artifacts, consistent with the two-pass investigation described in the PR body:

Missed (6), all documented OR/XOR or boundary equivalents:

  • emsa_pkcs1_v1_5.rs:124:18, :151:28, :192:20 (decode_digest_info/emsa_pkcs1_v1_5_verify) -- boundary-condition and short-circuit equivalents already covered by the crate's own vector-driven tests.
  • modexp.rs:109:54, :185:36, :193:54 (redc_normalize/ct_shift_in_bit_mod) -- disjoint-bit-range OR/XOR equivalences (the two operands never overlap by construction, so | and ^ agree).

Timeout (3), genuine infinite loops, not coverage gaps:

  • emsa_pkcs1_v1_5.rs:182:11 (emsa_pkcs1_v1_5_verify) -- a +=→*= mutation stalls a length-tracking loop forever.
  • mgf1.rs:24:18, :34:16 -- similarly stall MGF1's output-generation loop.

This confirms the pre-trait-wiring baseline (everything through commit 61aa840) is clean: no silent gaps, every non-caught mutant independently verified via code reasoning to be either a strict semantic equivalent or a loud (non-hanging-forever-undetected) infinite loop.

The later trait-wiring and key-generation commits (f1a87e2..1efdd64) have their own scoped mutants run in progress, covering the 14 files those commits touch; that result will follow as a separate comment once complete.

@dghgit

dghgit commented Sep 22, 2026

Copy link
Copy Markdown
Contributor Author

cargo mutants -- scoped run over the trait-wiring + keygen commits (f1a87e2..1efdd64)

Scoped to the 14 files those commits touch (emsa_pkcs1_v1_5.rs, emsa_pss.rs, emsa_pss_shake.rs, keygen.rs, keys.rs, rsa_1024/1536/2048/3072/4096/8192.rs, rsassa_pkcs1_v1_5.rs, rsassa_pss.rs, rsassa_pss_shake.rs), --jobs 3 --timeout 3000, single-threaded tests.

Result: 751/751 mutants -- 476 caught, 0 missed, 180 unviable, 95 timeout. Every timeout was individually investigated (not just left as "presumably fine"); none is a silent gap. They break down as:

  • 2 build timeouts -- cold scratch-copy compile time exceeding the auto-set cap, unrelated to the mutation.
  • ~14 genuine infinite loops -- real hangs, i.e. legitimate kills, just slow ones. All in keygen.rs's retry/gate logic (see below) or has_small_factor's prime-sieve loop.
  • ~79 equivalent-at-cap -- the mutated code runs to completion correctly (confirmed by watching many full test binaries pass in the log) but the single-threaded suite's wall-clock is close enough to the 3000s cap that the run gets cut off deep in the 8192-bit tests before finishing everything. Not equivalents in the strict sense for all of these -- see the structural notes below -- but none change the outcome the tests check.

Why so many timeouts turn out harmless

  • gcd/div/shl/shr/trailing_zeros/mask_to_bits/inverse_of_e_mod in keygen.rs feed only the FIPS 186-5 criterion-3 "d > 2^(nlen/2)" gate check, never the actual signing exponents (dP/dQ/qInv, computed independently via Fermat's theorem). Breaking these helpers can make the gate wrongly retry (a real infinite loop, ~14 of the above) or wrongly skip a redundant margin check (harmless, since the key is still correct) -- but it can never produce a broken key.
  • has_small_factor's prime-batching loop has three distinct ways its index bookkeeping can be broken into a genuine, deterministic infinite loop (confirmed by tracing the fixed batching structure by hand, not just observing the hang).
  • is_probable_prime's parity and small-value fast paths are redundant shortcuts whose fallback (full trial division / Miller-Rabin) independently reaches the same correct answer, so breaking the shortcut is invisible.
  • candidate()'s odd-forcing bit (out[0] |= 1 mutated to &=) degrades the low-order entropy of generated primes without ever producing an invalid one -- rejected-if-even candidates are simply retried. Functionally harmless, but a real (if narrow) reduction in randomness quality that no functional test could ever catch.

Four things worth your attention (none are silent mutants -- all found by manually reasoning through the timeout set, not something cargo-mutants itself flagged as missed)

  1. primes_too_close's rejection mechanism is never tested against a deliberately close p/q pair. keygen_tests.rs independently re-derives |p-q| > 2^(nlen/2-100) on whatever real key came out, rather than checking the rejection fired -- and two random ~1024-bit primes landing within that (astronomically small) distance essentially never happens by chance, so the check's disablement is invisible either way.
  2. keygen_from_rng's RNG-security-strength gate is only ever tested strictly above the required strength, never exactly at it. The suite's two RNG scenarios are None (must fail) and _256bit (must succeed) -- nothing tests an RNG at exactly the strength a given modulus size requires, which is the ordinary real-world case, not an edge case.
  3. Highest-leverage one: core-test-framework's test_boundary_conditions (used by every RSA size's test_keys call) never asserts a real PK::from_bytes(&pk.encode()) == pk round trip -- only that the encoded array has the declared (compile-time-fixed) length and that malformed-length buffers get rejected. Confirmed exhaustively: encode/encode_out are untested for every RSA size and both key-type flavors except RSA-2048 (which alone has an extra, independent round-trip test in keys_tests.rs). A single added assertion in the shared helper would close this for every algorithm using it, not just RSA.
  4. rsassa_pss's and rsassa_pss_shake's public sign_from_hash functions appear to be dead code. The actual Signer::sign_final path calls sign_from_hash_with_salt directly; a crate-wide grep turns up no call site for the plain sign_from_hash anywhere but its own definition and doc comments. (PKCS#1-v1.5's equivalent sign_from_hash is called from its own sign_final -- this is PSS/PSS-SHAKE specific.) Flagging as an open question rather than a bug: could be intentional public API for one-shot, non-streaming callers, or a refactor leftover that should be wired in or removed.

A --iterate --timeout 7200 --build-timeout 900 re-run over just the 95 timeout mutants is in progress to positively confirm the genuine-infinite-loop ones don't terminate even given much more time; a follow-up comment will report that once it completes.

AI Usage Statement

  • Yes, this analysis was performed by AI

Assisted-by: Claude:claude-sonnet-5

🤖 Generated with Claude Code

@dghgit

dghgit commented Sep 23, 2026

Copy link
Copy Markdown
Contributor Author

Follow-up: --iterate --timeout 7200 re-confirmation of the 95 timeout mutants

Re-ran just the 95 timeout mutants from the scoped trait-wiring/keygen run above with a much longer cap (7200s test / 900s build) to positively confirm the genuine-infinite-loop classifications rather than relying on "didn't finish in 3000s."

Final result: 95/95 -- 76 missed, 5 caught, 14 timeout. All 14 remaining timeouts are the genuine infinite loops already itemized above, and every one of them ran the full 7200s (or hit the 900s build-timeout, for the one const-eval compile-time hang) without resolving -- confirming non-termination rather than a slow pass.

One worth flagging precisely because it's the interesting case: keygen.rs:162:5 (lt stubbed to always return true) was originally observed hanging under the 3000s cap and was provisionally grouped with the other infinite loops, but flagged at the time as behaving differently from truly deterministic hangs like is_zero's -- its corruption causes a wrapping-underflow subtraction that's genuinely input-dependent, since gcd() is fed a fresh random p/q on every run. This time it resolved to caught instead: a fast, clean panic (mod_pow needs base < modulus) within a second, on different random primes than the earlier run drew. That's not a contradiction -- it's the input-dependent behavior playing out the other way this time, and either outcome (hang or fast panic) is a legitimate kill, never a silent pass. So the final count is 14 confirmed genuine infinite loops rather than 15, with 162:5 moving to the caught column.

This closes out the mutation-testing investigation for f1a87e2..1efdd64.

@dghgit
dghgit force-pushed the feature/rsa-sig branch 2 times, most recently from 007ec12 to 1d4ea0b Compare September 28, 2026 10:11
@hubot
hubot deleted the branch release/0.1.4alpha September 28, 2026 15:21
@hubot
hubot deleted the feature/rsa-sig branch September 28, 2026 15:21
@hubot
hubot deleted the branch feature/ecdsa November 3, 2026 13:16
@hubot
hubot restored the feature/rsa-sig branch November 3, 2026 14:53
@dghgit

dghgit commented Nov 4, 2026

Copy link
Copy Markdown
Contributor Author

Merged feature/ecdsa at a42ce74 (which carries release/0.1.3alpha 029a17b, the squash of PR #190) into this branch as b5e25d7. The RSA and RSA-SVE CLI commands moved onto the release's input rule from #190: private keys through the zeroized secret readers, public keys, signatures and ciphertexts as raw bytes or hex under the global --hex-input; the RSA CLI tests write raw key files. Workspace suite passes (2408 tests).

@dghgit

dghgit commented Nov 4, 2026

Copy link
Copy Markdown
Contributor Author

Replayed onto feature/ecdsa as rebased onto release/0.1.4alpha (69df164): feature/rsa-sig is now 7bb63e9, 26 commits on that tip, replayed from b5e25d7 with the ecdsa merges dropped and the tree restored to the old tip plus the 0.1.4 line's setup (version bump and notes file). The base stays feature/ecdsa. Workspace suite passes (2408 tests).

@hubot
hubot deleted the branch feature/ecdsa November 4, 2026 22:43
@hubot
hubot deleted the feature/rsa-sig branch November 4, 2026 22:43
@hubot
hubot restored the feature/rsa-sig branch November 5, 2026 00:20
@hubot
hubot force-pushed the feature/rsa-sig branch 2 times, most recently from a582209 to de882ed Compare November 5, 2026 16:32
dghgit and others added 2 commits November 6, 2026 20:51
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 <noreply@anthropic.com>
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 <noreply@anthropic.com>
rsa_8192_tests ran one vector per distinct (result, flags) pair of
rsa_signature_8192_sha{256,384,512}_test.json, on the stated ground
that a full run would take on the order of an hour. Public
exponentiation has since been made to run over e's bits, and the full
776 vectors measure 43 seconds of test time in a debug build (15
seconds elapsed, the three files in parallel) and 3.8 seconds in a
release build. The files are now run whole, with the runner and the
expected counts of the RSA-4096 tests: 7 valid, 250 or 251 invalid and
one MissingNull per file. The module docs lose the reason for sampling.

Assisted-by: Claude:claude-mythos-5-2
…TYLE.md fixes

The crate docs and modexp's module docs headed the section
"# Security Considerations"; the style guide gives one exact heading
for it wherever it appears, the one rsaes_oaep and the sha1 crate
already use. Both headings now match. bouncycastle-sha1 needed no
change.

Assisted-by: Claude:claude-mythos-5-2
…arts do not belong together

The variant's docs said "No input causes it". RSA returns it when the
result of the CRT is not taken back to its input by the public
exponent, which is what a fault gives and also what a private key
gives whose components or e do not belong together, and such a key can
be imported. The docs now name both causes and keep what was meant: no
message causes it.

Documentation only.

Assisted-by: Claude:claude-mythos-5-2
The variant's docs listed "(ECDSA, RSA)" as the algorithms that accept
a context and ignore it. RSA refuses one on this branch, so the list
was false; it is dropped rather than corrected, the one-line change
this file can carry into its coming merge.

Assisted-by: Claude:claude-mythos-5-2
The doctest that shows a transported key too long for the modulus
failing to build was a bare compile_fail, which any error satisfies,
an import that has gone included. It fails as E0080, the const
assertion on LEN, and is pinned to that, as the crate's other
compile_fail doctests are. The doctests pass on rustc 1.88 and on the
nightly that checks the code.

Assisted-by: Claude:claude-mythos-5-2
The crate docs' memory table and RsaPrivateComponents's own docs
pointed at an "# Encoding" section on RsaPublicKey and RsaPrivateKey.
The sections are on RsaPublicComponents and RsaPrivateComponents, the
key types being wrappers over those; the references now name them.

Assisted-by: Claude:claude-mythos-5-2
…nents types

rsa_cmd.rs and the rsa-2048 command's help pointed at an "# Encoding"
section on RsaPrivateKey and RsaPublicKey; the sections are on
RsaPrivateComponents and RsaPublicComponents. Comments and help text
only.

Assisted-by: Claude:claude-mythos-5-2
…y undefined

check_rsa_ct.sh builds dev_scripts/rsa_ct_harness, a crate in a
workspace of its own that reaches bouncycastle-rsa through its public
API, and runs it under valgrind memcheck in four modes:

- context: MontgomeryContext::for_secret_modulus over an undefined
  modulus;
- crt: RsaSigningSize::crt_exp at RSA-2048 with p, q, dP, dQ and qInv
  undefined, which is the two exponentiations, the recombination, the
  check of the result against e and the masked write of the output;
- control-context: for_public_modulus, which is variable time, over the
  same modulus;
- control-crt: crt, then a branch on what it returns.

The first two must be clean and the controls must be reported, so that
a memcheck that reports nothing is noticed. A secret is made undefined
without changing its value, by XOR with fresh heap memory under
--malloc-fill=0x00; the key type gives no mutable access to its
components, so the harness finds them in the key's bytes, and asserts
the key's size so that a field added to it is not left defined
unnoticed. That is the harness's unsafe; the library is not touched.

It exits 0 when all four behave, 1 when one does not, and 2 with a
FAIL line when valgrind is not installed, as check_oaep_ct.sh does.
It takes 6 seconds. It is not in any workflow.

Not covered, and said so in the script: key generation and the
validation and decoding of an imported key, which are not constant
time; the padding schemes above the CRT; and what memcheck cannot see,
an instruction whose time depends on its operands or a target other
than the host.

Shown to fail: with for_secret_modulus put back on the branching
doubling (a local edit, since restored), context and crt both exit 9
with reports in double_mod_n_vartime, and the script exits 1. Passes
on rustc 1.88 and 1.97.

for_secret_modulus's docs and the release notes' RSA entry name the
script.

Assisted-by: Claude:claude-mythos-5-2
check_rsa_stack.sh builds dev_scripts/rsa_stack_harness, a crate in a
workspace of its own over bouncycastle-rsa's public API, and runs it at
RSA-2048, or at the sizes given as arguments. The harness generates a
key and, for each operation, paints the stack below the call, runs the
operation with its results going to the heap or to a live frame above,
copies the dead stack out and searches the copy, at every byte offset,
for the 8-byte words of every secret the operation handled: the key's
components as limbs and as encoded bytes, R mod m and R^2 mod m for p
and q, the CRT's intermediates (x mod p, x mod q, s1, s2, h and the
low half of q*h), and what a decryption recovers and derives (Z, the
encoded message, HKDF's pseudorandom key, the derived or transported
key, the last three also in SHA-256's word order). It computes those
values with the crate's public arithmetic and asserts that its CRT
gives the operation's own output before searching for them.

The operations are the rows the wipes were measured over: the three
key generators; from_crt_components and from_bytes for each key type,
encode_out, encode, key() and both clones; PKCS#1 v1.5 and PSS
signing, one-shot, streaming and from a hash; RSASVE decapsulation raw
and through HKDF; RSAES-OAEP decapsulation, recovery and a refused
ciphertext; RSASVE encapsulation through HKDF; and
keygen::is_probable_prime over p. Two controls: nothing run must leave
nothing, and a copy of p left in a frame must be found in full. It
prints one ok or FAIL line per operation and exits 1 if any failed.
The harness's one unsafe is the read of the dead stack.

The script's header says what a pass shows: a release build for
x86-64 by the installed toolchain, and so nothing of another target,
another compiler or a debug build; and that it does not look at
registers, the heap, or what a caller does with a key it was returned.

Time: 5 seconds at RSA-2048 with the build; the harness alone takes
0.5 seconds at RSA-2048, 1.8 at 3072, 4.1 at 4096 and 2 minutes 10 at
8192, nearly all of that the three key generations. 28 lines pass at
each of the four sizes on rustc 1.97, and at 2048, 3072 and 4096 on
1.88. It is not in any workflow.

Shown to fail, each with a local edit since restored: without the
wipe after the checked CRT the six signing lines fail (one word of p
and nine of h found); without the wipe after encapsulation with HKDF
that line fails (3 of the 4 words of the pseudorandom key); without
the wipe in is_probable_prime that line fails (all of p and R^2 mod p,
15 of 16 words of R mod p).

The Security Considerations bullet on the wipes and the release notes'
RSA entry name the script.

Assisted-by: Claude:claude-mythos-5-2
Takes local release 3fb12d5: the crates marked publish = false, EdDSA
keys naming one algorithm with as_prehash(), ECDSA refusing a context,
CtxBehaviour::Ignored removed from the test framework, and the ML-KEM
test fix.

One conflict, in core-test-framework's signature suites: this branch had
picked the "streaming suites take an algorithm that refuses a context"
commit and still carried Ignored; release's file is taken whole. The RSA
suites already named CtxBehaviour::Refused, so nothing in the RSA crate
changes.

Workspace: 4044 passed, 0 failed, 17 ignored.

Assisted-by: Claude:claude-mythos-5-2
check_rsa_ct.sh and check_rsa_stack.sh guard the constant-time Montgomery
setup and the stack wipes, which no in-tree test can see. Neither is in a
workflow, unlike check_oaep_ct.sh, so the CI section says so and what
each does.

Assisted-by: Claude:claude-mythos-5-2
rsa-ct-stack.yml, on the model of oaep-ct.yml: check_rsa_ct.sh under
valgrind and check_rsa_stack.sh, on the runner's stable toolchain. The
stack search is sized by measurement on x86-64 release (rustc 1.88 and a
1.97 nightly here), so a compiler that lays frames out deeper will fail
it; CLAUDE.md says that is the check working, and what to do.

CLAUDE.md lists the workflow where it said CI does not run the two, and
the release note says they run in CI as well as by hand. Not yet seen to
pass on a hosted runner.

Assisted-by: Claude:claude-mythos-5-2
The mutation run over the review-fix commits (24 mutants: 13 caught, 8
unviable, 2 missed, 1 timeout) left two survivors, both in EMSA-PSS step
3: `<` as `<=`, and the `+ 2` as `* 2`. The test had a pairing well over
the limit and ones well under. It now has the exact fit (RSA-1024,
SHA-512, a 62-byte salt: 64 + 62 + 2 = 128), which encodes and verifies,
and one byte more, which is refused; either mutant fails it. The timeout
is random_prime returning without a prime, which is a kill.

Assisted-by: Claude:claude-mythos-5-2
Takes local release 8a62b1a: HashML-DSA as a key view with
PreHashAlgorithm, utils confining unsafe code to two modules,
bouncycastle-hybrid (hpke as a module), sm3, ripemd and blake2 as no_std,
and bouncycastle-pqc (the six ML-DSA and ML-KEM crates as modules).

One conflict, in the release notes, where release reworded the
bouncycastle-dhkem entry beside this branch's SHA-1 and RSA entries: both
kept. Nothing in the RSA or SHA-1 crates changes.

Workspace: 4073 passed, 0 failed, 17 ignored; the CLI suites pass (41),
and check_rsa_ct.sh (4 ok) and check_rsa_stack.sh (28 ok) pass.

Assisted-by: Claude:claude-mythos-5-2
exit runs no destructors, so the signing paths now end the key's scope
before looking at the result, as rsa_oaep_cmd does (mwcw re-review N2).

Assisted-by: Claude:claude-opus-5-5
…the caller's to wipe

mwcw re-review N1.

Assisted-by: Claude:claude-opus-5-5
…branch

mwcw re-review N3.

Assisted-by: Claude:claude-opus-5-5
Under the same name, as the other digest crates did: every item at the
path it had below the module, tests and bench prefixed sha1_. rsa uses
it through bouncycastle-digest; the umbrella keeps bouncycastle::sha1.

Assisted-by: Claude:claude-opus-5-5
…igest::sha1

The CLI's sha1 and rsa-oaep commands and the SHA-1 stack bench use the
family path.

Assisted-by: Claude:claude-opus-5-5
…ory tests only

Since the digest crate took in the vector suites, the step ran tests that
need bc-test-data, which the Build job does not check out, and the
concatenation KDF's ACVP suite failed on the missing data.

Assisted-by: Claude:claude-opus-5-5
After the release merge that moved hex into core: the RSA tests, benches
and crate docs, and the SHA-1 tests, use the new path.

Assisted-by: Claude:claude-opus-5-5
…ey-pair validation on request

Key generation runs 25 Miller-Rabin rounds on each prime at every size,
the count FIPS 140-3 IG C.F strongly recommends (its option 2) in place
of FIPS 186-5 Table B.1's minimum of 5, 4, 4 and 4. RSA-2048 key
generation measured 129 ms before and 162 ms after, over 385 key pairs
each.

A private key's constructor and decoder check RFC 8017 Section 3.2's
three congruences, e * dP == 1 (mod (p - 1)), e * dQ == 1 (mod (q - 1))
and q * qInv == 1 (mod p), through RsaSigningSize::crt_congruences, in
constant time in the components. A key whose components or exponent do
not belong together is refused with the component named; before, it was
built and failed the result check at first use. The wipe after
construction and decoding is resized: decoding now uses up to 24104
bytes at RSA-8192 under rustc 1.88, past the 23872 the old constants
covered.

RsaPrivateComponents::validate is SP 800-56B Rev. 2 Section 6.4.1.4.3
(crt_pkv) for a key from elsewhere: e at least 65537, each prime at
least sqrt(2) * 2^(nBits/2 - 1), the two more than 2^(nBits/2 - 100)
apart and probably prime at strength / 2 Miller-Rabin rounds, and the
private exponent above 2^(nBits/2). Key generation's check of the
private exponent is shared with it, and the inverse of e modulo a word
is by the extended Euclidean algorithm, so that it serves any e.

Tests. The result-check tests built their damaged keys through the
constructor, which refuses them now: they are unit tests in rsa_core.rs
over a constructor that exists in test builds only. Four tests that
used made-up components use genuine keys. New: each congruence refused
by name, through both constructors and on decoding; validation on a
sound key, a generated key and one key pair per criterion, the keys by
Python.

Checks: the workspace suite passes (4077, 0 failed);
check_rsa_ct.sh, with an import mode and its control, and
check_rsa_stack.sh, with validation added, pass under rustc 1.88 and
1.97. The result check of every private-key operation is unchanged.

Assisted-by: Claude:claude-fable-5-2
RsaKEMPrivateKey::validate forwards to RsaPrivateComponents::validate,
with the errors as KEMError: the KEM key gives no access to its
components, so SP 800-56B Rev. 2 Section 6.4.1.4.3 had no way to it.
Tested at every size through the size's forwarder (the RNG held to the
size's strength; a stream of zeros stopping the primality test), and at
RSA-2048 on a sound key and on one with a composite prime.

Assisted-by: Claude:claude-fable-5-2
Three independent reviews of the branch (the two newest commits, the
rsa crate, everything else) found no defect in a result; these are
their hardening items and stale documentation.

rsa. Key-pair validation runs half of ES(nBits) Miller-Rabin rounds,
SP 800-56B Rev. 2 Appendix D Table 4's strength for the modulus length:
56, 64, 76 and 100 (RsaSigningSize::VALIDATION_MR_ROUNDS), where it ran
half of the SP 800-57 strength, 64 and 96 at RSA-4096 and RSA-8192. A
key with a composite factor passes the constructor and is stopped by
the result check: tested from tests/, and the comments that said no
such key exists are corrected. The round count is pinned by a counting
RNG. Docs: step numbers in rsasve.rs and emsa_pkcs1_v1_5.rs corrected
against the texts, the statement that p and q may differ in length
removed (the full-length modulus makes them equal), the Status section
no longer claims PSS at RSA-1024 and RSA-1536, and a dozen passages
describing code that is no longer there.

cli. The rsa and rsasve commands drop the private key and the key
file's bytes before a failure exits, as the rsa-oaep command does.

ci. The no-std step builds every digest target before its targeted
run. CLAUDE.md says the two RSA checks have no gitea copy.

Left open, for a decision: the raw exponentiations on the public size
traits, the Wycheproof loader's fallback to unpinned copies, gitea
copies and a pinned toolchain for the RSA checks, CLI tests for rsasve
and for the larger sizes, and the unwiped stack of the public-key side.

Checks: the workspace suite passes (4083, 0 failed), rustdoc with
warnings denied, check_rsa_ct.sh and check_rsa_stack.sh under rustc
1.88 and 1.97. Mutants on apollo over the lines of the two commits
before this one: 160, 64 caught, 86 unviable, 9 timeouts, 1 missed
(d equal to 2^(nBits/2) exactly, which no key reaches).

Assisted-by: Claude:claude-fable-5-2
RsaSigningSize::crt_exp was a public method of a public trait, so
RSA2048::crt_exp(sk.components(), ..) was textbook m^d mod n on any
signing key. It moves, with the two routing methods added for the
import congruences and for validation, onto size::sealed::
PrivateKeyEngine, a supertrait of RsaSigningSize in a module private to
the crate: code generic over a size still reaches it, and code outside
the crate cannot name it. A compile_fail doctest on RsaSigningSize pins
that. RsaSize::public_exp and the other routing methods are as they
were.

check_rsa_ct.sh runs crt_exp and the congruences under memcheck without
branching on their verdicts, which no public operation does, so it
builds the crate with --cfg bouncycastle_rsa_ct_harness; that adds a
ct_harness module naming the trait and changes nothing else. The one
test in tests/ that signed with the raw operation carries its signature
as a known answer, checked with the public exponentiation.

From the pre-merge review. Checks: the workspace suite passes (4085, 0
failed), all targets and features build, rustdoc with warnings denied,
the crate builds on 1.88, and check_rsa_ct.sh and check_rsa_stack.sh
pass under rustc 1.88 and 1.97.

Assisted-by: Claude:claude-fable-5-2
@dghgit

dghgit commented Nov 23, 2026

Copy link
Copy Markdown
Contributor Author

Merged.

@dghgit dghgit closed this Nov 23, 2026
@hubot
hubot restored the feature/rsa-sig branch November 23, 2026 05:00
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant