Breaking Rabin with a Chosen-Ciphertext Attack
Redundancy lets a Rabin receiver pick the right one of four square roots, and it is often said to stop the chosen-ciphertext attack. It only slows it down. This guide factors a Rabin key from the receiver's answers alone, in about 2^(k-1) queries for k bits of redundancy, and then factors a 64-bit key from the ciphertext alone.
Pashalis Laoutaris 18 min read
Try it
Interactive Rabin Chosen-Ciphertext Breaker
🔐 Rabin Chosen-Ciphertext Breaker
Breaking Rabin with a Chosen-Ciphertext Attack
Introduction
The Rabin cryptosystem encrypts by squaring: c = m^2 mod n. Its famous property is that taking square roots modulo n is exactly as hard as factoring n. The same proof hides a weakness. Anyone who gets a square root back from the receiver, for a number they squared themselves, has a half chance of factoring n on the spot.
The usual answer is redundancy. The sender repeats the last k bits of the message, and the receiver keeps only the root with that pattern. It is often said that this stops the attack, because the receiver then hands back the root the attacker already knows. That is true only when the attacker plays fair. An attacker who sends the square of a random number still gets an answer now and then. Half of those answers use a root the attacker did not send, and that root factors n. This guide runs the attack against the key of the Rabin guide and measures its cost, which is about 2^(k-1) queries.
Table of Contents
- Rabin in One Paragraph
- Why a Second Root Factors n
- The Attack on the Redundant Version
- What It Costs
- The General Break: Factoring
- Interactive Visualizer
- A Worked Example
- Python Implementation
- Limitations
- Security Status
- FAQ
- References
Rabin in One Paragraph
The private key is two primes p and q, both 3 modulo 4. The public key is their product n. Encryption squares the message modulo n. Decryption takes a square root modulo each prime and joins the two with the Chinese remainder theorem. That gives four roots, and the plaintext is one of them. To tell which, the sender pads the message: the last k bits are written again after it. The receiver keeps the one root whose last two k-bit groups match. If no root matches, or more than one does, the receiver refuses to decrypt.
Why a Second Root Factors n
Suppose x and y are both square roots of the same c, and y is neither x nor n - x. Then x^2 - y^2 = (x - y)(x + y) is a multiple of n. But n divides neither factor. So one prime of n divides x - y and the other divides x + y. The greatest common divisor gcd(x - y, n) is therefore p or q.
A receiver who returns square roots is a factoring machine. The attacker picks a random x, sends x^2 mod n, and gets back one of its four roots. The receiver cannot know which root the attacker started from, so the returned root is a different pair with probability one half. This is the proof that square roots are as hard as factoring, run as an attack. The Rabin guide shows it against the textbook version with no redundancy.
The Attack on the Redundant Version
Redundancy changes what the receiver will answer. It decrypts only ciphertexts where exactly one root has the pattern. A fair message passes, because its own root has the pattern and the other three almost never do.
The attacker does not send fair messages. They send x^2 mod n for a random x, with no pattern at all. Each of the four roots of that ciphertext has the pattern by pure chance, with probability 2^-k. So the receiver answers about 4 times in every 2^k queries and refuses the rest. In a test with k = 8 and 200,000 random queries, it answered 1.53 percent of them. The prediction is 4 / 256, or 1.56 percent, and the exact figure is slightly lower, because sometimes two roots match by chance.
When the receiver does answer, it returns the message m. The attacker rebuilds the root it came from by adding the redundancy back, just as the sender would. Call that root r. Now the key question is whether r is x or n - x. The attacker chose x at random among the four roots, and the receiver’s choice depends only on the pattern. So r lies in the other pair half of the time. Then gcd(x - r, n) is a prime factor, and the key is broken.
Notice what the attacker never needs. They do not need to know why a query was refused, or how many roots matched. They need only the answers, and only one useful answer.
What It Costs
Each query is answered with probability close to 4 / 2^k, and each answer is useful with probability one half. On average, the attack needs about 2^k / 4 * 2 = 2^(k-1) queries. The code measured it on the key of the Rabin guide, n = 1000042000117, with a seeded generator for every run:
| Redundancy bits k | Runs | Mean queries | 2^(k-1) |
|---|---|---|---|
| 4 | 1000 | 9 | 8 |
| 8 | 1000 | 133 | 128 |
| 12 | 1000 | 2016 | 2048 |
| 16 | 100 | 29226 | 32768 |
The number of queries is spread out like a geometric distribution, so 100 runs leave the last row noisy. The trend is clear, though. Each extra bit of redundancy doubles the work. The size of n plays no part. A test against a 128-bit modulus with k = 8 factored it in 145 queries.
This is why redundancy is a speed bump, not a wall. With 8 or 16 bits, a server that decrypts on request gives up its key within seconds. With 64 bits the attack would need around 2^63 queries, which no attacker can send. But that only makes this particular attack impractical. It does not prove the scheme secure, as the Security Status section explains.
The General Break: Factoring
The chosen-ciphertext attack needs a receiver willing to decrypt. Without one, the only general break is to factor n. Rabin is exactly as hard as factoring, so there is no clever shortcut. For a toy key, though, factoring is easy.
Pollard’s rho method walks the sequence x -> x^2 + c mod n. Modulo the unknown prime p, the sequence must repeat after about sqrt(p) steps. Floyd’s cycle finding detects the repeat by moving one pointer twice as fast as the other. Then gcd(x - y, n) reveals p. For a 64-bit modulus with 32-bit primes, that means tens of thousands of steps. With the factors, the attacker decrypts any ciphertext exactly as the receiver does. For a 2048-bit key, rho would need around 2^512 steps, and even the best factoring methods are far out of reach.
Interactive Visualizer
The visualizer above attacks a receiver that holds the key of the Rabin guide, with p = 1000003 and q = 1000039. It sends the square of a random number, again and again, from a seeded generator. Most queries are refused. Each answered query appears in the log, with the rebuilt root and whether it helps.
Choose the redundancy bits k and watch the cost change. With k = 4 the attack usually ends within a few dozen queries. With k = 12 it needs thousands. Once a useful answer arrives, the visualizer splits n into its two primes and uses them to decrypt the ciphertext of the worked example of the Rabin guide. The visualizer runs the same generator and the same arithmetic as the Python code below, so every seed gives the same queries in both.
A Worked Example
The receiver uses n = 1000042000117 and k = 8. The attacker starts the generator with the seed 12345 and draws random numbers x from 2 to n - 2.
The first 16 queries are all refused. Query 17 is answered:
query 17: x = 212065897676, answer m = 828382412, root 212065897676 -> x or n - x, no use
The rebuilt root is x itself. This happens half the time, and it teaches the attacker nothing. Then come 73 more refusals, and query 91 is answered:
query 91: x = 522844145180, answer m = 687062907, root 175888104315 -> a different root!
Now the root 175888104315 is neither x nor n - x. The attacker computes gcd(522844145180 - 175888104315, n), which is 1000003. Dividing gives the other prime, 1000039. The receiver answered 2 of 91 queries, and one of them broke the key.
With the factors, the attacker decrypts anything. The ciphertext c = 821466923234 from the worked example of the Rabin guide gives the message 123456.
Python Implementation
The code is self-contained. It copies the decryption of the Rabin guide, wraps it as an oracle that answers or refuses, and runs the attack from a seeded generator. Then it measures the cost for four values of k, and finally factors a 64-bit key with Pollard’s rho.
# rabin_breaker.py
#
# Two breaks of the Rabin cryptosystem of the Rabin guide.
# (1) The chosen-ciphertext attack on the version WITH redundancy. The attacker squares a random x and
# sends x^2 mod n as a ciphertext. The receiver answers only when exactly one of the four roots has
# the redundancy, which happens about 4 times in 2^k. When it answers, the root it used is x or n - x
# only half of the time. The other half, gcd(x - M, n) is a prime factor of n. The attack costs about
# 2^(k-1) queries for k bits of redundancy.
# (2) The general break: factor n with Pollard's rho and decrypt like the receiver.
# Teaching code with toy key sizes.
from math import gcd
def egcd(a, b):
x0, x1, y0, y1 = 1, 0, 0, 1
while b:
qt = a // b
a, b = b, a - qt * b
x0, x1 = x1, x0 - qt * x1
y0, y1 = y1, y0 - qt * y1
return a, x0, y0
def square_roots(c, p, q):
"""The four square roots of c modulo n = p * q, for primes p = q = 3 (mod 4)."""
n = p * q
mp = pow(c, (p + 1) // 4, p)
mq = pow(c, (q + 1) // 4, q)
_, yp, yq = egcd(p, q)
r1 = (yp * p * mq + yq * q * mp) % n
r3 = (yp * p * mq - yq * q * mp) % n
return [r1, (n - r1) % n, r3, (n - r3) % n]
# redundancy: the last k bits of the message are written again after it
def add_redundancy(m, k):
return (m << k) | (m & ((1 << k) - 1))
def has_redundancy(r, k):
return (r & ((1 << k) - 1)) == ((r >> k) & ((1 << k) - 1))
def remove_redundancy(r, k):
return r >> k
def encrypt(m, n):
return m * m % n
def decrypt(c, p, q, k):
"""What the receiver does: keep the one root with the redundancy, or refuse."""
good = [r for r in square_roots(c, p, q) if has_redundancy(r, k)]
if len(good) != 1:
raise ValueError("%d roots have the redundancy" % len(good))
return remove_redundancy(good[0], k)
def mulberry32(seed):
"""A small seeded generator of 32-bit numbers, the same one the visualizer runs in JavaScript."""
a = seed & 0xFFFFFFFF
def rnd():
nonlocal a
a = (a + 0x6D2B79F5) & 0xFFFFFFFF
t = (a ^ (a >> 15)) * (a | 1) & 0xFFFFFFFF
t = ((t + ((t ^ (t >> 7)) * (t | 61) & 0xFFFFFFFF)) & 0xFFFFFFFF) ^ t
return (t ^ (t >> 14)) & 0xFFFFFFFF
return rnd
def random_x(rnd, n):
"""A number from 2 to n - 2, built from two 32-bit outputs."""
return 2 + ((rnd() << 32) | rnd()) % (n - 3)
def cca_attack(n, oracle, k, rnd, log=None):
"""Factor n with nothing but a decryption oracle that checks the redundancy. Returns (p, q, queries)."""
queries = 0
while True:
x = random_x(rnd, n)
queries += 1
if gcd(x, n) != 1: # a lucky x shares a factor: never happens in practice
p = gcd(x, n)
return p, n // p, queries
try:
m = oracle(x * x % n) # most queries are refused
except ValueError:
continue
root = add_redundancy(m, k) # the root the receiver picked, rebuilt
useful = root not in (x, n - x)
if log is not None:
log.append((queries, x, m, root, useful))
if useful: # x^2 = root^2 (mod n) with root != +-x
p = gcd(x - root, n)
return p, n // p, queries
def pollard_rho(n, c):
"""Floyd's cycle finding on x -> x^2 + c. Returns (d, steps); d == n means try another c."""
x = y = 2
d, steps = 1, 0
while d == 1:
x = (x * x + c) % n
y = (y * y + c) % n
y = (y * y + c) % n
d = gcd(x - y, n)
steps += 1
return d, steps
def factor(n):
c = 1
while True:
d, steps = pollard_rho(n, c)
if d != n:
return min(d, n // d), max(d, n // d), steps
c += 1
if __name__ == "__main__":
# (1) the key of the Rabin guide, with 8 bits of redundancy
p, q, k = 1000003, 1000039, 8
n = p * q
oracle = lambda c: decrypt(c, p, q, k) # the receiver, seen from outside: an answer or an error
log = []
f1, f2, queries = cca_attack(n, oracle, k, mulberry32(12345), log)
f1, f2 = min(f1, f2), max(f1, f2)
print("n = %d, k = %d, seed 12345" % (n, k))
for i, x, m, root, useful in log:
print(" query %3d: x = %d, answer m = %d, root %d -> %s"
% (i, x, m, root, "a different root!" if useful else "x or n - x, no use"))
print("refused: %d of %d queries" % (queries - len(log), queries))
print("gcd(x - root, n) = %d, so n = %d * %d" % (f1, f1, f2))
intercepted = 821466923234 # the ciphertext of the worked example of the Rabin guide
print("the intercepted c = %d decrypts to m = %d" % (intercepted, decrypt(intercepted, f1, f2, k)))
# the cost grows as 2^(k-1)
for kk, seeds in ((4, 1000), (8, 1000), (12, 1000), (16, 100)):
counts = [cca_attack(n, lambda c, kk=kk: decrypt(c, p, q, kk), kk, mulberry32(s))[2] for s in range(seeds)]
print("k = %2d: mean %6.0f queries over %4d seeds, 2^(k-1) = %d" % (kk, sum(counts) / seeds, seeds, 2 ** (kk - 1)))
# (2) ciphertext only: factor a 64-bit modulus with Pollard's rho
P, Q = 3797265611, 3954011107
N = P * Q
c = encrypt(add_redundancy(0x1234567890AB, 8), N)
a, b, steps = factor(N)
print("N = %d (%d bits) = %d * %d after %d rho steps" % (N, N.bit_length(), a, b, steps))
print("c = %d decrypts to m = %#x" % (c, decrypt(c, a, b, 8)))
Running the file prints this output:
n = 1000042000117, k = 8, seed 12345
query 17: x = 212065897676, answer m = 828382412, root 212065897676 -> x or n - x, no use
query 91: x = 522844145180, answer m = 687062907, root 175888104315 -> a different root!
refused: 89 of 91 queries
gcd(x - root, n) = 1000003, so n = 1000003 * 1000039
the intercepted c = 821466923234 decrypts to m = 123456
k = 4: mean 9 queries over 1000 seeds, 2^(k-1) = 8
k = 8: mean 133 queries over 1000 seeds, 2^(k-1) = 128
k = 12: mean 2016 queries over 1000 seeds, 2^(k-1) = 2048
k = 16: mean 29226 queries over 100 seeds, 2^(k-1) = 32768
N = 15014430402123141377 (64 bits) = 3797265611 * 3954011107 after 52668 rho steps
c = 10541769184347719002 decrypts to m = 0x1234567890ab
I checked the attack in several ways. Every factor it returns divides n, and every recovered plaintext matches the message that was encrypted. The visualizer runs a JavaScript copy of the same functions. For the seeds 0 to 999 at each of k = 4, 8 and 12, both versions made the same 2,158,496 queries and got the same 6,002 answers, number for number. The two 32-bit primes pass the Miller-Rabin test with the first twelve primes as bases, which is exact at this size. Pollard’s rho factored the 64-bit modulus in 0.03 seconds.
Limitations
The attack is powerful, but it needs specific conditions:
- It needs a decryption oracle. The attacker must be able to submit their own ciphertexts and see the plaintext that comes back. A receiver that never reveals decryptions of unauthenticated ciphertexts gives the attacker nothing to work with.
- The cost grows with k. The attack needs about
2^(k-1)queries. It is fast for small redundancy, but 64 bits or more puts it out of reach. - The toy keys are tiny. The key
n = 1000042000117keeps the numbers readable. The attack does not care about the size ofn, but the factoring part does. Pollard’s rho is hopeless against a real 2048-bit key. - The redundancy here is simple. Repeating the last
kbits is the scheme of the Rabin guide. Other padding rules change how often the receiver answers, but any rule that is checked after decryption and leaks a root has the same problem.
Security Status
- Plain Rabin is broken by chosen ciphertexts. Without redundancy, a single answered query factors
nwith probability one half. The Rabin guide demonstrates it. - Simple redundancy only slows the attack. As this guide shows, it costs about
2^(k-1)queries. Large redundancy makes this attack impractical, but the proof that breaking Rabin equals factoring no longer covers the padded version. Whether that version is secure has long been an open question. - Proper padding fixes it. Dan Boneh showed in 2001 that a simplified form of OAEP, with a single Feistel round, makes Rabin secure against chosen-ciphertext attacks in the random oracle model. In practice, new systems should use a standard scheme such as RSA-OAEP or elliptic-curve encryption.
FAQ
Doesn’t the redundancy make the receiver return only the root I sent?
Only if you send a ciphertext that has the pattern. A fair ciphertext has one root with the pattern, and that root is your own message. The attacker instead squares a random number with no pattern. Its four roots each match by chance, and when exactly one matches, the receiver returns it. Half the time that is a root the attacker did not know.
Why does a different square root reveal a factor?
If x^2 and y^2 are equal modulo n, then n divides (x - y)(x + y). When y is not x or n - x, n divides neither factor alone. So one prime of n sits in x - y and the other in x + y, and a greatest common divisor pulls it out.
How many bits of redundancy would stop the attack?
The attack costs about 2^(k-1) queries, so 80 bits or more puts it far beyond any attacker. That stops this attack, not every attack. The safer path is a padding scheme with a security proof, such as the simplified OAEP of Boneh, or a different public-key scheme.
Does the attack work against RSA?
Not in this form. RSA encryption is a permutation, so every ciphertext has exactly one plaintext and the receiver never has a choice of roots to leak. RSA has its own chosen-ciphertext attacks, such as Bleichenbacher’s attack on PKCS #1 v1.5 padding, which exploit what the receiver reveals about the padding instead.
Can I break Rabin without asking the receiver anything?
Only by factoring n. For the 64-bit key in this guide, Pollard’s rho does it in a fraction of a second. For a properly sized key, factoring is believed infeasible, and that is the whole security of Rabin.
References
-
Rabin, Michael O. “Digitalized Signatures and Public-Key Functions as Intractable as Factorization,” MIT/LCS/TR-212, 1979.
-
Menezes, Alfred J., Paul C. van Oorschot, and Scott A. Vanstone. Handbook of Applied Cryptography, CRC Press, 1996, Chapter 8 (Rabin public-key encryption and its chosen-ciphertext attack).
-
Boneh, Dan. “Simplified OAEP for the RSA and Rabin Functions,” Advances in Cryptology, CRYPTO 2001, Lecture Notes in Computer Science 2139, pp. 275-291.
-
Pollard, John M. “A Monte Carlo method for factorization,” BIT Numerical Mathematics, 1975 (the rho method).
-
The Rabin guide on this site, whose key and redundancy this attack uses: /blog/rabin_guide/