Bleichenbacher's Attack: Decrypting RSA with a Padding Oracle
A server that only reveals whether an RSA ciphertext has valid PKCS#1 v1.5 padding leaks enough to decrypt it completely. This guide runs Bleichenbacher's 1998 million-message attack on a toy RSA key, narrowing the plaintext to a single value from one-bit answers, with no access to the private key.
Pashalis Laoutaris 14 min read
Try it
Interactive Bleichenbacher PKCS#1 v1.5 Padding Oracle
š Bleichenbacher PKCS#1 v1.5 Padding Oracle
Bleichenbacherās Attack: Decrypting RSA with a Padding Oracle
Introduction
RSA encryption needs padding. Raw RSA is deterministic and malleable, so real systems wrap the message in a padding scheme before encrypting. The old and still widely deployed one is PKCS#1 v1.5. In 1998 Daniel Bleichenbacher showed that this padding, combined with a server that reveals whether a decrypted message is correctly padded, is a disaster. The server becomes an oracle, and an attacker who can query it enough times decrypts any ciphertext, or forges a signature, without ever learning the private key.
The attack is famous for its cost: it is called the āmillion-message attackā because a 1024-bit key takes on the order of a million queries. It refuses to die. In 2017 the ROBOT research found it still live in TLS stacks from major vendors, nineteen years later. This guide builds it against a toy RSA key and watches the interval of possible plaintexts shrink to a single value.
Table of Contents
- Introduction
- PKCS#1 v1.5 Padding and the Oracle
- The Core Idea: Multiply and Ask
- Narrowing the Interval
- Interactive Visualizer
- A Worked Example
- Python Implementation
- Limitations
- Security Status
- FAQ
- References
PKCS#1 v1.5 Padding and the Oracle
For a modulus of k bytes, PKCS#1 v1.5 encryption padding wraps a message like this:
00 02 || PS || 00 || message
The first two bytes are fixed, 00 02. PS is at least eight nonzero random padding bytes, then a single 00 separator, then the message. When a server receives a ciphertext, it decrypts, checks that the result starts with 00 02 and is otherwise well formed, and only then processes the message. If the padding is wrong, it returns an error.
That error is the leak. If an attacker can tell, from an error message or a timing difference or any other signal, whether a chosen ciphertext decrypted to something starting with 00 02, the server is a padding oracle. In numbers, writing B = 2^(8(k-2)), a plaintext starts with 00 02 exactly when it lies in the interval [2B, 3B). The oracle answers one question: is the decryption of this ciphertext in [2B, 3B)?
The Core Idea: Multiply and Ask
RSA is multiplicatively homomorphic. If c = m^e mod n, then for any s the attacker chooses:
c * s^e mod n decrypts to m * s mod n
So the attacker never has to decrypt. By sending c * s^e and asking the oracle, they learn whether m * s mod n lies in [2B, 3B), that is, whether it starts with 00 02. Each such yes is a linear fact about the secret m: it says 2B <= m*s - r*n < 3B for some integer r. Each fact cuts down the set of possible m.
The attack is a disciplined search over s. The first step looks for the smallest s, starting near n / 3B, that gives a conforming answer. Because only about one value in 65,000 is conforming, this first search alone costs thousands of queries. That is the bulk of the āmillion messages.ā
Narrowing the Interval
After the first hit, the attacker keeps a set of intervals that must contain m. Each new conforming s combines with the known modulus to replace each interval [a, b] with the tighter pieces where the padding condition can hold:
for each r in the valid range:
a' = max(a, ceil((2B + r*n) / s))
b' = min(b, floor((3B - 1 + r*n) / s))
While several intervals remain, the attacker steps s up by one until the next conforming value. Once a single interval is left, it searches s and a counter r together, which makes the interval roughly halve with each hit. The width falls steadily, one bit at a time, until the interval is a single number. That number is m, the padded plaintext. Strip the 00 02 ... 00 header and the message is in the clear.
Interactive Visualizer
The visualizer above runs the whole attack in your browser against a real, if tiny, RSA key. Type a short secret, and the page pads it, encrypts it, and then attacks the ciphertext using only the oracle. The attacker code never touches the private key.
You can watch the query counter climb into the thousands during the first search, then the interval bar shrink round by round until it collapses. The toy key is 16 bytes, so the attack finishes in a few thousand queries rather than a million, but the mechanism is exactly the one that breaks 1024-bit and 2048-bit keys. The same algorithm runs in the Python below, and the two agree on the recovered message and the query count.
A Worked Example
The toy key has a 16-byte modulus. The secret is money. The sender pads it to 00 02 || padding || 00 || money and encrypts, giving the captured ciphertext c0.
Now the attack runs. The first conforming s, found by searching upward from ceil(n / 3B), is 9274. From there the interval that must contain m shrinks by about one bit per conforming answer:
round 1: width ~2^99
round 2: width ~2^98
...
round 98: width ~2^1
round 99: width ~2^0
At round 99 the interval is a single value. It equals the padded plaintext exactly, and stripping the padding gives back money. The whole run took 3,576 oracle queries. A real 1024-bit key needs about a million, which is the attackās nickname, but the number is the only thing that grows; the method is identical.
Python Implementation
This is a complete toy RSA with PKCS#1 v1.5 padding, the one-bit oracle, and Bleichenbacherās interval-narrowing attack.
# bleichenbacher.py
#
# Bleichenbacher's 1998 chosen-ciphertext attack on RSA with PKCS#1 v1.5 encryption padding, the
# "million-message attack". A server that reveals whether a ciphertext decrypts to a well-formed
# padding (first two bytes 0x00 0x02) is a padding oracle. The attacker multiplies the target by
# s^e, asks the oracle, and each "yes" narrows the possible plaintext to a shrinking set of
# intervals, until one interval collapses to the message. The private key is never recovered.
# Small key for a fast demo; teaching code.
import math
# ceil and floor division on integers
def cdiv(a, b):
return -(-a // b)
def fdiv(a, b):
return a // b
# ---- a toy RSA key (128-bit modulus) ----
# two fixed 64-bit primes, so the modulus is exactly 16 bytes. A real key is 2048 bits or more; this
# toy size keeps the demo to a few thousand oracle queries instead of the ~2^20 a 1024-bit key needs.
P = 0x8ef152125425b7db
Q = 0x81ffd99aa654f1f3
N = P * Q
E = 65537
PHI = (P - 1) * (Q - 1)
D = pow(E, -1, PHI)
K = (N.bit_length() + 7) // 8 # modulus length in bytes
def rsa_dec(c):
return pow(c, D, N)
def rsa_enc(m):
return pow(m, E, N)
def pkcs1_pad(message):
"""PKCS#1 v1.5 type-2 padding: 00 02 || PS (>=8 nonzero bytes) || 00 || message."""
ps_len = K - 3 - len(message)
if ps_len < 8:
raise ValueError("message too long for this modulus")
# deterministic non-zero padding so the demo is reproducible (a real sender uses random bytes)
ps = bytes((i % 254) + 1 for i in range(ps_len))
return b"\x00\x02" + ps + b"\x00" + message
def pkcs1_unpad(block):
"""Strip type-2 padding. Returns the message after the 00 02 ... 00 header."""
if len(block) != K or block[0] != 0x00 or block[1] != 0x02:
raise ValueError("bad padding")
sep = block.index(0x00, 2)
return block[sep + 1:]
def i2osp(x, length):
return x.to_bytes(length, "big")
# the oracle the server leaks: "does this ciphertext decrypt to 00 02 ... ?"
oracle_calls = 0
def oracle(c):
global oracle_calls
oracle_calls += 1
m = rsa_dec(c)
b = i2osp(m, K)
return b[0] == 0x00 and b[1] == 0x02
B = 1 << (8 * (K - 2)) # 2B <= m < 3B is exactly "starts with 00 02"
def interval_union(intervals):
"""Merge overlapping [a, b] intervals."""
out = []
for a, b in sorted(intervals):
if out and a <= out[-1][1]:
out[-1] = (out[-1][0], max(out[-1][1], b))
else:
out.append((a, b))
return out
def bleichenbacher(c0):
"""Recover m0 = c0^d mod n using only the padding oracle. c0 must be PKCS-conforming to start."""
# sanity check without spending an oracle query: this simple version skips the blinding step,
# so it needs c0 already conforming (true for a genuine PKCS#1 ciphertext).
assert i2osp(rsa_dec(c0), K)[:2] == b"\x00\x02", "c0 must be PKCS-conforming for this version"
M = [(2 * B, 3 * B - 1)]
s = cdiv(N, 3 * B) # step 2a: first s to try
i = 1
history = []
def find_from(start):
s = start
while not oracle((c0 * pow(s, E, N)) % N):
s += 1
return s
while True:
if i == 1:
s = find_from(cdiv(N, 3 * B))
elif len(M) > 1:
s = find_from(s + 1) # step 2b: several intervals, step s up by one
else: # step 2c: one interval, search r and s together
a, b = M[0]
r = cdiv(2 * (b * s - 2 * B), N)
found = False
while not found:
s_lo = cdiv(2 * B + r * N, b)
s_hi = fdiv(3 * B - 1 + r * N, a)
for cand in range(s_lo, s_hi + 1):
if oracle((c0 * pow(cand, E, N)) % N):
s = cand
found = True
break
r += 1
# step 3: narrow the intervals with the new s
new = []
for a, b in M:
r_lo = cdiv(a * s - 3 * B + 1, N)
r_hi = fdiv(b * s - 2 * B, N)
for r in range(r_lo, r_hi + 1):
na = max(a, cdiv(2 * B + r * N, s))
nb = min(b, fdiv(3 * B - 1 + r * N, s))
if na <= nb:
new.append((na, nb))
M = interval_union(new)
history.append((i, len(M), M[0][1] - M[0][0]))
if len(M) == 1 and M[0][0] == M[0][1]:
return M[0][0], history
i += 1
if __name__ == "__main__":
print("Toy RSA: %d-byte modulus (%d bits), e=%d. A real key is 2048 bits or more." % (K, N.bit_length(), E))
print("The attacker has only the public key and the padding oracle, never the private key.")
secret = b"money"
block = pkcs1_pad(secret)
m0 = int.from_bytes(block, "big")
c0 = rsa_enc(m0)
print("secret message:", secret)
print("c0 (captured ciphertext): %064x..." % (c0 >> (8 * (K - 8))))
oracle_calls = 0
recovered, history = bleichenbacher(c0)
rec_block = i2osp(recovered, K)
print("\noracle queries:", oracle_calls)
print("interval count over time (round: intervals, width-bits):")
for rnd, cnt, width in history[:3] + [("...", "", "")] + history[-3:]:
if rnd == "...":
print(" ...")
else:
print(" round %4d: %d interval(s), width ~2^%d" % (rnd, cnt, width.bit_length()))
print("\nrecovered == original:", recovered == m0)
print("recovered message:", pkcs1_unpad(rec_block))
Running it prints this:
Toy RSA: 16-byte modulus (127 bits), e=65537. A real key is 2048 bits or more.
The attacker has only the public key and the padding oracle, never the private key.
secret message: b'money'
c0 (captured ciphertext): 000000000000000000000000000000000000000000000000284cac175dd3db88...
oracle queries: 3576
interval count over time (round: intervals, width-bits):
round 1: 1 interval(s), width ~2^99
round 2: 1 interval(s), width ~2^98
round 3: 1 interval(s), width ~2^97
...
round 97: 1 interval(s), width ~2^1
round 98: 1 interval(s), width ~2^1
round 99: 1 interval(s), width ~2^0
recovered == original: True
recovered message: b'money'
I checked the code several ways. The two primes are verified prime with Miller-Rabin, and the padding round-trips. The oracle matches a raw decrypt-and-check-prefix on 3,000 random ciphertexts with zero disagreement, using a key reconstructed in the pycryptodome library for the comparison. The attack recovers the exact padded plaintext, which stripping confirms is the original message. The JavaScript in the visualizer runs the same algorithm and agrees with the Python on the recovered value and the query count: money in 3,576 queries, and pay, cash, and hi all match too.
Limitations
A toy key size. The demo uses a 16-byte modulus so the attack finishes in a few thousand queries. A real key is 2048 bits or more, where the first search alone is around 2^16 queries and the full attack is close to a million. The algorithm does not change, only the count.
A simplified start. This version assumes the captured ciphertext is already PKCS-conforming, which a genuine ciphertext is, so it skips Bleichenbacherās optional blinding step. Blinding is what lets the attack also forge signatures and attack non-conforming targets; it is a small addition on top of what is here.
The oracle is handed over. The code plays both sides: it is the server that leaks the one-bit answer and the attacker that uses it. In the real world the hard part is finding the oracle, through an error message, a timing gap, or a connection reset. The cryptanalysis, once the oracle exists, is what this guide shows.
Teaching code. The arithmetic favors clarity. Real attack tools batch queries, parallelize, and use the timing-based oracles that ROBOT rediscovered.
Security Status
PKCS#1 v1.5 encryption padding is broken in the presence of a padding oracle, and oracles keep appearing. The attack is a chosen-ciphertext attack, and PKCS#1 v1.5 has no proof against those. The defenses are well understood and often still done wrong.
The real fix is RSA-OAEP, the modern encryption padding with a security proof against chosen-ciphertext attacks. Where PKCS#1 v1.5 cannot be removed, as in parts of TLS, implementations must make a padding failure indistinguishable from a success, taking the same time and returning the same response, so no oracle exists. That is hard to get right, which is exactly why ROBOT found the attack alive in 2017, and why newer protocol versions drop RSA key exchange entirely in favor of forward-secret Diffie-Hellman.
FAQ
Does the attacker learn the private key?
No, they do not. The attack decrypts one ciphertext, or signs one message, by turning the server into a decryption helper through the oracle. The private exponent is never recovered. The target is confidentiality of a message, not the key itself.
Why is it called the million-message attack?
A 1024-bit key needs on the order of a million oracle queries to finish, because conforming padding is rare and each round needs a fresh conforming s. The toy key here needs only a few thousand, but the count is the only thing that scales with key size.
What exactly does the oracle reveal?
One bit per query: whether a chosen ciphertext decrypts to a plaintext that starts with the bytes 00 02. That is the PKCS#1 v1.5 check. It sounds harmless, and it is enough to decrypt the whole message.
How is this different from the CBC padding oracle?
Both exploit a padding check that leaks. The CBC padding oracle works on a symmetric block-cipher mode and recovers plaintext byte by byte. Bleichenbacher works on RSA and uses its multiplicative structure to narrow a numeric interval. Same idea, different algebra.
Is ROBOT the same attack?
Yes, ROBOT (āReturn Of Bleichenbacherās Oracle Threatā, 2017) is the original attack found still present in modern TLS implementations. The variants mostly differ in how they detect the oracle, often through timing or distinct TLS alerts, rather than in the math, which is unchanged since 1998.
References
-
Bleichenbacher, Daniel. āChosen Ciphertext Attacks Against Protocols Based on the RSA Encryption Standard PKCS #1.ā Advances in Cryptology, CRYPTO ā98, Lecture Notes in Computer Science 1462, Springer, 1998, pp. 1-12.
-
Bƶck, Hanno, Juraj Somorovsky, and Craig Young. āReturn Of Bleichenbacherās Oracle Threat (ROBOT).ā 27th USENIX Security Symposium, 2018.
-
RFC 8017. Moriarty, K., et al. āPKCS #1: RSA Cryptography Specifications Version 2.2,ā 2016 (the v1.5 and OAEP padding schemes).
-
Bardou, Romain, et al. āEfficient Padding Oracle Attacks on Cryptographic Hardware.ā CRYPTO 2012 (faster variants of the attack).
-
The RSA guide on this site, whose cryptosystem and padding this attack targets: /blog/rsa_guide/