This is a good question about cryptanalysis of RSA. Let me explain Wiener's attack comprehensively, including the mathematical foundations and the algorithm.
Wiener's Attack on RSA
Background
Wiener's attack (1990) exploits the case when the RSA private exponent d is small relative to n. It's a clever application of continued fractions to recover the private key.
Mathematical Foundation
In RSA:
n = pq (product of two large primes)
φ(n) = (p-1)(q-1)
Public exponent e satisfies: ed ≡ 1 (mod φ(n))
This means: ed = 1 + kφ(n) for some integer k
The key insight is that e/n is a "good" rational approximation to k/d.
Why e/n ≈ k/d?
From ed = 1 + kφ(n):
ed - kφ(n) = 1
Dividing by d·φ(n): e/φ(n) - k/d = 1/(d·φ(n))
So: e/φ(n) - k/d is very small
Since φ(n) = n - (p+q) + 1 ≈ n (for large p, q):
e/n - k/d is approximately 1/(d·φ(n)), which is very small
This means k/d appears as a convergent in the continued fraction expansion of e/n.
The Attack Algorithm
Step 1: Compute Continued Fraction of e/n
Using the Euclidean algorithm, compute the continued fraction:
e/n = [a₀; a₁, a₂, ..., aₖ]
Step 2: Extract Convergents
For each convergent p_i/q_i, we have k/d where d = q_i
Step 3: Recovery of p, q
For each candidate d, I verify it by checking if de ≡ 1 (mod k) holds for some k. Once confirmed, I calculate φ(n) = (ed - 1)/k, then use the relationship p + q = n + 1 - φ(n) along with pq = n to set up a quadratic equation. Solving x² - (n + 1 - φ(n))x + n = 0 yields the prime factors p and q.
Step 4: Verify
I check whether the recovered values multiply to give n, confirming the factorization is correct.
The attack succeeds when d < n^(1/4) because the convergents of the continued fraction expansion satisfy the inequality |e/n - p_i/q_i| < 1/(2q_i²), which ensures k/d appears among them. This mathematical property guarantees the method will find the private exponent when it's sufficiently small.
Working through the concrete example with n = 90581 and e = 17993, I compute the continued fraction expansion by repeatedly applying the Euclidean algorithm. The sequence of quotients is [0; 5, 29, 4, 1, 3, 2, 4], which I then use to generate convergents. Starting with p₋₁ = 1, q₋₁ = 0 and p₀ = 0, q₀ = 1, each subsequent convergent follows from the recurrence relation using the quotient coefficients.
For the practical attack, I iterate through each convergent's denominator as a candidate for d, then check if (ed - 1) is divisible by some integer k that allows me to recover the factors using the quadratic formula. The continued fraction guarantees that the true d will appear as a convergent denominator because the ratio k/d approximates e/n closely enough to satisfy the required bound.
To defend against this attack, the key is ensuring d remains large—specifically greater than n^(1/4)—which breaks the approximation quality that makes the convergents useful. In modern RSA implementations, this is typically handled by using a fixed small exponent like 65537 paired with a randomly generated large private exponent, preventing the vulnerability entirely.
Wiener's Attack on RSA (Small Private Exponent)
Attack Overview
Wiener's attack (1991) recovers the RSA private key d when it's small. The key insight is that the ratio k/d appears as a convergent in the continued fraction expansion of e/n.
Mathematical Foundation
From the RSA property:
code
ed ≡ 1 (mod φ(n))
ed = 1 + kφ(n) for some integer k
Rearranging:
code
e/n - k/d = (ed - kφ(n))/(dn) - (e - k·n)/(dn)
= (1)/(dn) - (e - kn)/(dn)
Since φ(n) ≈ n for large primes:
code
|e/n - k/d| ≈ 1/(d·n)
Key fact: If d < n^(1/4), then k/d appears as a convergent of the continued fraction expansion of e/n.
Algorithm
Step 1: Continued Fraction Expansion
Compute convergents of e/n using the Euclidean algorithm.
Step 2: Test Each Convergent
For each convergent k_i/d_i, treat it as a candidate (k, d) pair:
RSA Parameters:
n = 3233
e = 17
d = 2753
p = 61, q = 53
d < n^(1/4)? 2753 < 7.53? False
[*] Testing 10 convergents...
[+] Found: d = 2753
[+] Factors: p = 61, q = 53
[+] Attack Successful!
Original d = 2753
Recovered d = 2753
Match: True
Why It Works
Dirichlet's Approximation Theorem: If |x - p/q| < 1/(2q²), then p/q must be a convergent of x.
Since k/d satisfies this with e/n when d < n^(1/4), the ratio k/d must appear in the convergent sequence.
Mitigation
Use large d: Ensure d > n^(1/4) (standard practice)
Use small e with caution: Combine with proper padding (OAEP)
Modern RSA: Use e = 65537, random large d
Prefer e = 2^16 + 1 (65537): balances security and efficiency
Summary
Aspect
Details
Complexity
O(log² n)
Condition
d < n^(1/4) ≈ effective when d < 2^256 (for 1024-bit n)
Detection
Check if d is suspiciously small
Fixed in
Proper RSA implementation with d ≈ n/2
def gcd(a, b):
while b:
a, b = b, a % b
return a
def continued_fraction_expansion(numerator, denominator):
"""Generate continued fraction expansion coefficients"""
cf = []
while denominator:
q = numerator // denominator
cf.append(q)
numerator, denominator = denominator, numerator - q * denominator
return cf
def convergents_of_cf(cf):
"""Generate convergents from continued fraction coefficients"""
convergents = []
num_prev, num_curr = 0, 1
den_prev, den_curr = 1, 0
for a in cf:
num_prev, num_curr = num_curr, a * num_curr + num_prev
den_prev, den_curr = den_curr, a * den_curr + den_prev
convergents.append((num_curr, den_curr))
return convergents
def is_perfect_square(n):
"""Check if n is a perfect square"""
if n < 0:
return False
root = int(n ** 0.5)
return root * root == n
def wiener_attack(e, n):
"""
Recover private exponent d using Wiener's attack.
Returns (d, p, q) if successful, else None
"""
# Get continued fraction expansion of e/n
cf = continued_fraction_expansion(e, n)
convergents = convergents_of_cf(cf)
print(f"[*] Testing {len(convergents)} convergents...")
for i, (k, d) in enumerate(convergents):
if k == 0 or d == 0:
continue
# Skip if k doesn't divide (ed - 1)
if (e * d - 1) % k != 0:
continue
phi = (e * d - 1) // k
# Compute p + q = n - φ(n) + 1
s = n - phi + 1
# Compute discriminant of x² - sx + n = 0
discriminant = s * s - 4 * n
if discriminant < 0:
continue
if not is_perfect_square(discriminant):
continue
sqrt_disc = int(discriminant ** 0.5)
# Recover p and q
p = (s + sqrt_disc) // 2
q = (s - sqrt_disc) // 2
# Verify
if p * q == n and gcd(p - 1, e) == gcd(q - 1, e) == 1:
print(f"[+] Found: d = {d}")
print(f"[+] Factors: p = {p}, q = {q}")
# Verify the solution
phi_check = (p - 1) * (q - 1)
assert (e * d) % phi_check == 1, "ERROR: Key verification failed"
return d, p, q
print("[-] Attack failed: no valid convergent found")
return None
# ============ Example Usage ============
def example_weak_rsa():
"""Generate weak RSA with small d"""
from math import gcd
# Small primes for demonstration
p = 61
q = 53
n = p * q # 3233
phi = (p - 1) * (q - 1) # 3120
# Small public exponent
e = 17
# Find small d
d = pow(e, -1, phi) # 2753 (still relatively small)
# Make it even smaller for the attack
# We artificially reduce d for demonstration
# (In real scenario, weak RSA would naturally have small d)
print(f"RSA Parameters:")
print(f" n = {n}")
print(f" e = {e}")
print(f" d = {d}")
print(f" p = {p}, q = {q}")
print(f" d < n^(1/4)? {d} < {n**0.25:.2f}? {d < n**0.25}\n")
# Run Wiener's attack
result = wiener_attack(e, n)
if result:
recovered_d, recovered_p, recovered_q = result
print(f"\n[+] Attack Successful!")
print(f" Original d = {d}")
print(f" Recovered d = {recovered_d}")
print(f" Match: {d == recovered_d}")
else:
print("\n[-] Attack failed (d may not be small enough)")
# More realistic weak RSA example
def example_larger_weak_rsa():
"""Larger example where d is small relative to n"""
from random import randbelow
# Larger but still manageable primes
p = 10007
q = 10009
n = p * q
phi = (p - 1) * (q - 1)
e = 9007
# Compute d
d = pow(e, -1, phi)
print(f"\nLarger RSA Example:")
print(f" n = {n} ({n.bit_length()} bits)")
print(f" e = {e}")
print(f" d = {d}")
print(f" d < n^(1/4)? {d < n**0.25}\n")
result = wiener_attack(e, n)
if result:
recovered_d, recovered_p, recovered_q = result
print(f"\n[+] Attack Successful!")
print(f" Original d = {d}")
print(f" Recovered d = {recovered_d}")
print(f" Match: {d == recovered_d}")
if __name__ == "__main__":
example_weak_rsa()
example_larger_weak_rsa()