Fermat factorization for close RSA primes
Factor an RSA modulus whose primes were generated too close together. Fermat’s method finds them in a handful of steps where trial division never would.
Open in ctfpalFermat’s method rests on writing n = a^2 - b^2 = (a+b)(a-b). Start at a = ceil(sqrt(n)) and step upward, checking each time whether a^2 - n is a perfect square. When it is, b falls out and the factors are a+b and a-b.
Why closeness is fatal
The number of steps required is proportional to how far apart p and q are. If they were generated by picking one prime and then searching for the next prime after it - a shortcut that appears in bad key generators and in most CTF challenges that use this attack - the gap is tiny and the search terminates in single-digit iterations, on a 2048-bit modulus, instantly.
from math import isqrt
def fermat(n):
a = isqrt(n)
if a * a < n:
a += 1
while True:
b2 = a * a - n
b = isqrt(b2)
if b * b == b2:
return a - b, a + b
a += 1Part of a module
5. RSA and the parameters that break it
Work the RSA decision tree - small modulus, close primes, tiny exponent, shared modulus - and learn to read a key for its weakness.
Practise on real challenges
Go deeper
- The RSA attack decision treeRSA challenges are not solved by knowing every attack - they are solved by reading the parameters and picking the one attack that matches. A decision tree from e and n to Fermat, Wiener, Hastad, common modulus, and the oracle attacks.
Related tools
RSA decryption and attack runner
Paste n, e, and c and let ctfpal choose the attack: trial division, Fermat, Pollard’s rho, Wiener, common modulus, or Hastad broadcast. Arbitrary-precision, in-browser.
Wiener’s attack on small RSA private exponents
Recover a small private exponent d from n and e using continued fractions. Works whenever d is below roughly the fourth root of n.
Modular arithmetic and number theory toolkit
Modular inverse, Chinese remainder theorem, Tonelli-Shanks square roots, Jacobi symbols, and integer nth roots - arbitrary precision, in the browser.
Hastad broadcast attack on RSA
Recover a message sent to several recipients under a small public exponent, using the Chinese remainder theorem and an exact integer root.