Skip to content

Reject RSA keys whose primes are too close (FIPS 186-5 gap check) - #804

Draft
Portll wants to merge 1 commit into
RustCrypto:masterfrom
Portll:fix/fips-prime-gap
Draft

Portll wants to merge 1 commit into
RustCrypto:masterfrom
Portll:fix/fips-prime-gap

Conversation

@Portll

@Portll Portll commented Dec 3, 2026

Copy link
Copy Markdown

Problem

PrivateKey validation enforces that the prime factors are distinct, but not that they are far enough apart. FIPS 186-5 §A.1.5 and SP 800-56B §6.4.1.2 require, for a two-prime key, that

|p − q| > 2^(nlen/2 − 100)

where nlen is the bit length of the modulus. When |p − q| is small, the modulus is recoverable by Fermat factorization in a handful of steps — Hanno Böck et al., "Fermat Factorization in the Wild" (IACR eprint 2023/026), found real-world keys broken exactly this way.

Today the only prime check in validate_private_key_parts (src/private_key.rs) is the distinctness test (prime.ct_eq(other)), which rejects p == q but accepts, e.g., two consecutive primes. The Go standard library closes this in crypto/rsa's checkPrivateKey (diff.BitLenVarTime() <= N.BitLen()/2-100).

RustCrypto's own key generation forces the top two bits of each prime, so a coincidentally close pair from a healthy RNG is astronomically unlikely — but the import paths (from_p_q, from_primes, from_components, PKCS#1/#8 decode) accept externally supplied factors with no such guarantee, and a FIPS-conformant implementation is expected to reject them.

Change

Adds the minimum prime-distance check to validate_private_key_parts for the two-prime case; a key whose |p − q| has bit length ≤ nlen/2 − 100 is rejected with Error::InvalidPrime.

Why there, and why vartime

  • Validate, not keygen. validate_private_key_parts is the single choke point every key passes through — generation (try_generate_from_rng → from_primes) and every untrusted import. Imported keys are the ones actually at risk, so the check belongs there. This matches Go (bound in checkPrivateKey, not only GenerateKey). src/algorithms/generate.rs is intentionally left untouched.
  • Signed comparison. nlen/2 − 100 is computed in i64 exactly as Go computes it in int; for small moduli the RHS is negative and the comparison is vacuously false, so the crate's small test keys are unaffected.
  • Variable-time is fine here. The bound depends only on the public modulus size, and a passing key reveals only that the gap exceeds a public threshold — so public cmp_vartime/bit_width_vartime on the existing BoxedUint API are acceptable, mirroring Go's BitLenVarTime.
  • Two-prime only. Multiprime RSA has no standardized |pᵢ − pⱼ| bound; len > 2 is unchanged.
  • Error variant. Reuses Error::InvalidPrime to minimize the diff. Error is #[non_exhaustive], so a dedicated PrimesTooClose could be added compatibly if you prefer — happy to.

Tests

Two unit tests in src/private_key.rs:

  • rejects_primes_that_are_too_close — two consecutive 512-bit primes (|p − q| = 20); from_p_q returns Err(Error::InvalidPrime). e = 65537 is coprime to p−1/q−1, so the gap check is the only failing check.
  • accepts_well_separated_primes — two independent 512-bit primes, gap far above the bound; validation succeeds.

cargo test --lib: 70 passed, 0 failed.

Severity (honest)

Medium — conformance / defense-in-depth. Not remotely exploitable against keys from a healthy RNG (forced top-two-bits make a close pair essentially impossible). The value is (1) FIPS 186-5 / SP 800-56B conformance and (2) rejecting imported or weak-RNG keys whose factors are close enough for Fermat factorization. It closes a standards gap and a defensive hole; it does not fix a break in normal operation.

Gap confirmed absent on main HEAD 90fb187.


Opened as a draft for maintainer review. Reported by Portll john@portll.net.

Key validation only enforced that p != q. FIPS 186-5 (A.1.5) and
SP 800-56B (6.4.1.2) additionally require |p - q| > 2^(nlen/2 - 100):
when the factors are close, Fermat factorization recovers the modulus
cheaply (Bock et al., "Fermat Factorization in the Wild", eprint
2023/026). Go's crypto/rsa enforces the same bound in checkPrivateKey
via `diff.BitLenVarTime() <= N.BitLen()/2-100`.

Add the check to validate_private_key_parts for the two-prime case,
mirroring Go's signed comparison so small test keys are unaffected. The
bound is a public property of the modulus size and |p - q| need not be
secret for it, so vartime BoxedUint ops are used. Multiprime keys have
no standardized bound and are left unchanged.
@codecov

codecov Bot commented Dec 3, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 93.37%. Comparing base (90fb187) to head (3d6597a).

Additional details and impacted files
@@            Coverage Diff             @@
##           master     #804      +/-   ##
==========================================
+ Coverage   93.14%   93.37%   +0.23%     
==========================================
  Files          29       29              
  Lines        4097     4209     +112     
==========================================
+ Hits         3816     3930     +114     
+ Misses        281      279       -2     

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

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