RSA Attacks
RSA is not broken. Specific keys are, and they are broken by the parameters around the algorithm — primes chosen too close together, an exponent small enough to lose the message, a modulus shared with another host, or a padding scheme that answers questions it should not.
Every attack here is a parameter mistake, not a break
Small exponent, small message
With e = 3 and no
padding, encryption is c = m^3 mod n.
If the message is short enough that
m^3 < n, the
modulus never reduces anything and the ciphertext is an exact cube. The private key is not needed — a cube root is.
The same arithmetic generalises. Encrypt one unpadded message to
e different
recipients with the same exponent and you have
c_i = m^e mod n_i
for i = 1..e. The
Chinese Remainder Theorem reconstructs
m^e mod (n_1 * n_2 * ... * n_e),
which — because m^e
is smaller than that product — is the plain integer
m^e. One cube root
recovers the message. This is Håstad's broadcast attack, and it is why the same message must never be sent to
several recipients without randomised padding.
| Condition | What the attacker does | Is it a finding? |
|---|---|---|
| e = 3, unpadded, m^3 < n | Integer cube root of the ciphertext | Yes — textbook RSA in use |
| e = 3, OAEP padding | Nothing; padding randomises m and fills the modulus | No |
| Same message to e recipients, unpadded | CRT then integer root (Håstad) | Yes — even with e = 65537 if the message is long enough |
| e = 65537, unpadded, long message | Nothing directly; but the scheme has no integrity | Yes — malleable, and a forgery surface |
Wiener: a small private exponent
A small d makes
signing fast, and it is occasionally chosen deliberately by someone who has read about performance. When
d < n^0.25 / 3,
k/d appears among
the continued-fraction convergents of
e/n, so
d can be read off
directly. Boneh and Durfee later raised the bound to
d < n^0.292;
Wiener's bound is the one you can implement in an afternoon.
from fractions import Fraction
def convergents(e, n):
"""Continued-fraction convergents of e/n, as (numerator, denominator) pairs."""
a = []
while n:
a.append(e // n)
e, n = n, e % n
num, den = 0, 1
prev_num, prev_den = 1, 0
for term in a:
num, prev_num = term * num + prev_num, num
den, prev_den = term * den + prev_den, den
yield num, den
def wiener(e, n):
"""Recover d when d < n**0.25 / 3: k/d appears among the convergents of e/n."""
for k, d in convergents(e, n):
if k == 0 or (e * d - 1) % k:
continue
phi = (e * d - 1) // k
# p + q = n - phi + 1, p * q = n -> discriminant must be a perfect square
s = n - phi + 1
disc = s * s - 4 * n
if disc < 0:
continue
root = isqrt_safe(disc)
if root is not None and (s + root) % 2 == 0:
return d
return None
def isqrt_safe(x):
from math import isqrt
r = isqrt(x)
return r if r * r == x else NoneValidate a recovered d before believing it
e * d mod phi and
check it equals 1, then encrypt and decrypt a random block. A candidate that fails either test is not the key.
Common modulus and shared primes
Two distinct mistakes both involve reuse. The first is one modulus with two exponents — two users on the same
n — where the
extended Euclidean algorithm recovers the plaintext without factoring anything, provided the exponents are coprime.
The second is subtler and far more common in reality: two moduli that share a prime factor.
Two moduli with a shared prime look completely ordinary individually. Their GCD is a factor of both, and a batch GCD pass over a population of keys finds the pair instantly. This is the test that exposed the Debian OpenSSL keys and, more recently, large numbers of embedded-device keys generated from a low-entropy boot-time source. Scanning one key will never find it — the defect only exists between keys.
#!/usr/bin/env python3
"""Batch GCD over every RSA modulus in a directory.
A shared prime is invisible when you look at one key: each modulus is a
perfectly ordinary product of two primes. It only appears when two keys
share a factor, which batch GCD finds at once - this is the test that
found the Debian OpenSSL keys and the many embedded-device keys since.
"""
import pathlib
import re
from math import gcd
KEY = pathlib.Path("keys")
moduli = {}
for path in KEY.glob("*"):
text = path.read_text(errors="ignore")
match = re.search(r"modulus\s*[:=]\s*([0-9a-fA-Fx]+)", text)
if match:
moduli[path.name] = int(match.group(1), 16)
names = list(moduli)
found = 0
for i, first in enumerate(names):
for second in names[i + 1:]:
g = gcd(moduli[first], moduli[second])
if 1 < g < moduli[first]:
found += 1
print(f"{first} and {second} share a factor")
p = moduli[first] // g
print(f" p = {p:#x}")
print(f"{found} shared-prime pair(s) across {len(names)} keys")Fermat: primes that are too close
If p and
q are close,
n sits close to a
perfect square. Fermat's method walks upward from
isqrt(n) testing
whether a^2 - n is
a square, and finds the factors when it is. It is useless against properly generated keys and instant against a
generator that picks p
and then searches for the next prime for q.
from math import isqrt
def fermat(n, max_iterations=1_000_000):
"""Factor n when p and q are close: n = a^2 - b^2 = (a-b)(a+b)."""
a = isqrt(n)
if a * a < n:
a += 1
for _ in range(max_iterations):
b2 = a * a - n
b = isqrt(b2)
if b * b == b2: # b is an integer, so n factors
return a - b, a + b
a += 1 # walk a upward until the square matches
return None
if __name__ == "__main__":
n = int.from_bytes(open("modulus.bin", "rb").read(), "big")
factors = fermat(n)
if factors:
p, q = factors
assert p * q == n
print(f"p = {p:#x}")
print(f"q = {q:#x}")
else:
raise SystemExit("p and q are not close enough for this bound")The bound is the finding
Bleichenbacher and the padding oracle
This class does not need a bad key at all. It needs an endpoint that decrypts RSA with PKCS#1 v1.5 and tells the
attacker, in any observable way, whether the decrypted block had valid padding. Each such answer leaks one bit
about the plaintext, and a few thousand queries recover it. The same shape as the CBC padding oracle on page 03,
one layer up: there the oracle is block-cipher padding, here it is the
00 02 prefix.
# The oracle, in the only part that matters: does the server distinguish
# "padding was wrong" from "padding was right, but the plaintext was nonsense"?
#
# A compliant implementation returns a single error for both. An
# implementation that validates padding first and then parses the message
# leaks one bit per query - and one bit per query is enough.
#
# PKCS#1 v1.5 block: 00 02 [ >=8 non-zero padding bytes ] 00 [ message ]
#
# The attack, in outline:
# 1. take a captured ciphertext c0 = m0^e mod n
# 2. submit c = c0 * s^e mod n for chosen s
# 3. the oracle says whether the decryption of c starts with 00 02
# 4. that answer narrows the interval that m0 can occupy
# 5. repeat; the interval collapses after a few thousand queries
#
# It is Bleichenbacher's 1998 attack, it was still producing CVEs in 2024,
# and the fix is OAEP or, better, an AEAD - not a better error message.The reason this keeps returning — ROBOT in 2017, and further variants since — is that the fix is structural. A compliant implementation must take the same time and return the same error whether the padding was invalid or the message was nonsense after valid padding. String comparisons in a log are not enough; the timing has to match too. The durable answer is to stop using PKCS#1 v1.5 for anything an attacker can query.
The key defects that actually ship
In practice you will not find a clever mathematical break. You will find a fleet of devices built from one image, or a certificate generator that ran before the entropy pool was seeded. Both are testable in bulk.
| Defect | How it appears | How it is found |
|---|---|---|
| Shared prime | Two hosts, normal-looking moduli, one common factor | Batch GCD across all keys in scope |
| ROCA (CVE-2017-15361) | Keys from Infineon TPMs and the devices built on them | The ROCA fingerprint test on the modulus |
| Low-entropy generation | Identical keys across units; the boot-time pool was empty | Fingerprint every key and count duplicates |
| Close primes | q chosen as the next prime after p | Fermat, with a bounded iteration count |
| Small d | Signing chosen for speed on a constrained device | Wiener / Boneh-Durfee from the public key alone |
# Install the current way: the repository moved from requirements.txt to a
# pyproject build, and --uncipherfile no longer exists.
git clone https://github.com/RsaCtfTool/RsaCtfTool
cd RsaCtfTool
python -m pip install -e .
# Attacks are selected with --attack, which accepts several names at once.
# "all" is both a valid value and the default, so the flag is only needed to
# narrow the search.
python RsaCtfTool.py --publickey key.pub --attack wiener fermats smallq
# Decrypt a captured ciphertext with the recovered key.
python RsaCtfTool.py --publickey key.pub --decryptfile ciphertext.bin
# Emit the recovered private key when the attack recovers one.
python RsaCtfTool.py --publickey key.pub --privateOne recovered key is usually a fleet
| Check | Expected | Where to look |
|---|---|---|
| The modulus is factorable | Two factors found, and p * q returns the original n | Any script that consumes the key |
| The private exponent recovered from Wiener actually decrypts | pow(pow(m, e, n), d, n) == m for a random m | The recovery script |
| The shared-prime test runs against a corpus, not one key | A GCD pass over every key in scope, because shared primes are only visible pairwise | The batch job |
| The finding names the primitive, not the algorithm | Textbook RSA / PKCS#1 v1.5 / close primes — RSA itself is not the defect | The report |
| The replacement key is generated, not patched | A new modulus of at least 3072 bits for data protected past 2030 | The fix commit |
What to Record
An RSA finding is only useful if it names the primitive that failed. A report that says "weak RSA" cannot be fixed:
The modulus, in full: Not a key ID. The fingerprint resolves to a modulus, but during a retest you will need the value itself to prove the factors multiply back.
The attack that worked, and its cost: Fermat after 40 iterations is a different finding from a shared prime across two certificates. Say which, and how long it took.
Every key affected: A shared prime compromises both keys. A ROCA-generated key compromises every key from that device family. Scope is part of the finding.
The padding scheme: A 2048-bit modulus with textbook RSA or PKCS#1 v1.5 is a different severity from the same modulus with OAEP.
The replacement, not the adjustment: Keys are regenerated. Recommend the size — 3072 bits for data protected past 2030 — and where the randomness must come from.
What Is Not an RSA Finding
Four things get reported as RSA weaknesses and are not:
- A 2048-bit modulus in 2026: Acceptable through 2030 under NIST SP 800-57 Part 1 Rev. 5. Report it as a deprecation horizon, not a vulnerability — unless the data must stay confidential past 2030, in which case 3072 is already the requirement.
- RSA key exchange on a modern server: It is a missing-forward-secrecy finding, not a factoring one. Report the property: a stolen private key decrypts recorded traffic.
- A public exponent of 3: On its own it is fine, and it is not the cause of a broadcast attack. The attack needs the same unpadded message across several moduli.
- A modulus that will not factor: A Fermat run that hits its bound returns nothing, and that means nothing. Absence of a factor is not evidence of a strong key.
RSA Review Checklist
Run this against any key you find during an assessment:
- ☐ Modulus size recorded, with the NIST date that applies to the data lifetime
- ☐ Public exponent is 65537, or 3 with a documented reason and padding in place
- ☐ Key generated on-device, not shipped in firmware or a default image
- ☐ Same modulus not reused across hosts, tenants or environments
- ☐ Batch GCD run across every key in scope, not a sample
- ☐ ROCA detection run if any key came from an Infineon TPM or a device family that used one
- ☐ Close-prime Fermat run with a bounded iteration count
- ☐ Low-entropy keys checked against known weak-key corpora
- ☐ Padding is OAEP for encryption and PSS for signatures
- ☐ No oracle distinguishes padding failure from parse failure
- ☐ Private key operations are not exposed through an endpoint that reports distinct errors
What Actually Fixes It
RSA weaknesses are rarely fixed in place. These are the changes that hold:
Why 3072 bits, and why it is not just a bigger number
NIST SP 800-57 Part 1 Rev. 5 keys its table on security strength rather than modulus size, and the dates follow from that. 2048-bit RSA is 112 bits of security, acceptable through 2030 and disallowed from 2031; 3072-bit is 128 bits, the level required for data that has to stay protected past 2030. The size is not a proxy for quality: a 4096-bit key generated with a shared prime is still broken, and a 2048-bit key generated correctly is still acceptable this year. Test the generation, then read the size against the data lifetime.
RSA Practice
Exercises where the key is the puzzle. Each one is a real generation mistake rather than a theoretical break.
Related Cryptography Guides
Crypto Fundamentals
Key sizes, padding and the primitives these attacks break into.
Padding Oracle
The same oracle primitive, applied to block ciphers rather than to PKCS#1 v1.5.
Key Management
Where the key came from, which is usually how the weakness got there.
Cryptography Remediation
The fix catalogue for the classes this page breaks into.