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

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

dghgit wants to merge 76 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>
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
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
… key encoding traits as one PrivateKey / PublicKey pair) into feature/rsa-sig

No conflicts. One adaptation: the RSA signature keys and the RSASVE KEM keys implement PrivateKey<N> / PublicKey<N>, with from_bytes returning KeyDecodingError. Four decoders delegate to the crate's raw component decoders and to the KEM keys' from_rsa_key, which return a role error; they convert through two private helpers that keep a decoding failure's message, the only kind those produce. The tests that asserted SignatureError::DecodingError or KEMError::DecodingError on a key's from_bytes assert KeyDecodingError; the CLI, the benches and the stack harness follow the rename. No decoder accepts or refuses different input. Workspace tests 3383 passed, the all-targets build has no warnings, rustdoc with warnings denied over the workspace and nightly rustfmt are clean. No mutants run for the decoder changes.

Assisted-by: Claude:claude-mythos-5-2
…writer

The key is encoded into a Secret by helpers::write_private_key, as the other keygen commands do since d9143c8, 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
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
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
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
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
Assisted-by: Claude:claude-mythos-5-2
core::key_transport_key is the pair of roles for transporting a key the sender already holds under a public key: KeyTransportEncryptingKey<Params, CT_LEN> (transport_out, transport, max_key_len) and KeyTransportDecryptingKey<Params, CT_LEN> (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
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
…2 Sections 7.2.2 and 9.2.3)

The key-establishment keys RsaKEMPublicKey and RsaKEMPrivateKey run RSAES_OAEP<K, H, M> 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
…rough the wiped writers

As the other key-generating and KEM commands do. Output is unchanged.

Assisted-by: Claude:claude-mythos-5-2
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
…ack 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
Assisted-by: Claude:claude-mythos-5-2
# Conflicts:
#	alpha_0.1.4_release_notes.md
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
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
…-data

Without a Wycheproof checkout beside the repository, the loader reads bc-test-data/crypto/wycheproof/<file>, 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
…ull 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
@dghgit dghgit changed the title rsa: RSASSA-PKCS1-v1_5, RSASSA-PSS and PSS-SHAKE across RSA-1024 through 8192 rsa: RSASSA-PKCS1-v1_5, RSASSA-PSS, PSS-SHAKE, RSASVE and RSAES-OAEP across RSA-1024 through 8192, with a SHA-1 crate Nov 17, 2026
# Conflicts:
#	cli/src/main.rs
#	crypto/factory/Cargo.toml
#	crypto/factory/src/hash_factory.rs
#	crypto/factory/tests/hash_factory_tests.rs
#	mem_usage_benches/Cargo.toml
#	mem_usage_benches/src/lib.rs
# Conflicts:
#	cli/src/main.rs
#	mem_usage_benches/Cargo.toml
#	mem_usage_benches/src/lib.rs
#	src/lib.rs

This branch has not been deployed

No deployments
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