TExcelTAD
Home › Number Theory & Cryptography › RSA Padding: PKCS #1 and OAEP

RSA Padding: PKCS #1 and OAEP

Padding turns the RSA trapdoor permutation into an encryption scheme: it fills the message out to the size of the modulus with randomness and structure. The old PKCS #1 v1.5 format did this with a fixed layout and fell to Bleichenbacher's "million message attack"; OAEP adds a hash-based mixing step and is provably secure against chosen-ciphertext attacks in the random-oracle model.

PKCS #1 v1.5 encryption

For a kk-byte modulus, the encoded message is

text
00 || 02 || PS (at least 8 random nonzero bytes) || 00 || M

The random bytes PS make encryption randomized, and the length leaves no room for the small-message attacks of the previous lesson.

python · try it yourself
def pkcs1_v15_pad(msg, k, rand_bytes):
    ps_len = k - 3 - len(msg)
    assert ps_len >= 8, "message too long"
    ps = bytes(b or 1 for b in rand_bytes[:ps_len])      # nonzero filler (teaching shortcut)
    return b"\x00\x02" + ps + b"\x00" + msg

def pkcs1_v15_unpad(em):
    if em[:2] != b"\x00\x02":
        raise ValueError("bad padding")
    sep = em.index(b"\x00", 2)
    if sep < 10:
        raise ValueError("bad padding")
    return em[sep + 1:]

k = 32
filler = bytes((37 * i + 11) % 256 for i in range(64))     # stands in for unpredictable bytes
em = pkcs1_v15_pad(b"secret key", k, filler)
print(em.hex())
print(pkcs1_v15_unpad(em))
00020b30557a9fc4e90e33587da2c7ec11365b80a500736563726574206b6579
b'secret key'

Bleichenbacher's attack (1998)

Suppose a server decrypts a ciphertext and reveals, by an error message or by its timing, whether the result starts with 00 02. That one bit is an oracle. Because RSA is malleable, the attacker can submit c⋅sec \cdot s^e for chosen ss and learn whether ms mod nms \bmod n lies in the interval [2B,3B)[2B, 3B), where B=28(k−2)B = 2^{8(k-2)}. Each "yes" narrows the possible range of mm; after roughly a million queries, mm is known exactly.

python · try it yourself
from sympy import nextprime
from math import lcm

p, q = nextprime(2**256 + 12345), nextprime(2**256 + 2**200 + 6789)
n, e = p * q, 65537
d = pow(e, -1, lcm(p - 1, q - 1))
k = (n.bit_length() + 7) // 8
B = 2 ** (8 * (k - 2))

def oracle(c):                              # the leaky server: "is the padding OK?"
    return 2 * B <= pow(c, d, n) < 3 * B

m = int.from_bytes(b"\x00\x02" + bytes(range(1, k - 13)) + b"\x00" + b"hello world", "big")
c = pow(m, e, n)
hits = sum(oracle(c * pow(s, e, n) % n) for s in range(2, 5002))
print("modulus bytes:", k, " conforming multipliers among 5000:", hits)
modulus bytes: 65  conforming multipliers among 5000: 19

A handful of "yes" answers per few thousand queries is all the attack needs: each one is an interval constraint on mm. (Here nn is only slightly above 25122^{512}, so the hit rate is about B/n≈2−8B/n \approx 2^{-8}; for typical moduli it is lower, hence the million queries.) It has resurfaced repeatedly: ROBOT (2017) found 27 of the top 100 web domains vulnerable through TLS servers' RSA key exchange. TLS 1.3 removed RSA key transport entirely.

OAEP

Optimal Asymmetric Encryption Padding (Bellare and Rogaway, 1994; PKCS #1 v2) mixes the message with a random seed through a mask generation function built from a hash:

text
DB        = lHash || 00...00 || 01 || M
maskedDB  = DB   XOR MGF(seed, len(DB))
maskedSeed = seed XOR MGF(maskedDB, hLen)
EM        = 00 || maskedSeed || maskedDB

Changing a single bit of the ciphertext scrambles the whole decrypted block, so the decryption check fails for every forged ciphertext and the malleability attacks stop working.

python · try it yourself
import hashlib

def mgf1(seed, length):
    out = b""
    for counter in range((length + 31) // 32):
        out += hashlib.sha256(seed + counter.to_bytes(4, "big")).digest()
    return out[:length]

def xor(a, b):
    return bytes(x ^ y for x, y in zip(a, b))

def oaep_encode(msg, k, seed, label=b""):
    h = hashlib.sha256(label).digest()
    ps = b"\x00" * (k - len(msg) - 2 * 32 - 2)
    db = h + ps + b"\x01" + msg
    masked_db = xor(db, mgf1(seed, len(db)))
    masked_seed = xor(seed, mgf1(masked_db, 32))
    return b"\x00" + masked_seed + masked_db

def oaep_decode(em, k, label=b""):
    masked_seed, masked_db = em[1:33], em[33:]
    seed = xor(masked_seed, mgf1(masked_db, 32))
    db = xor(masked_db, mgf1(seed, len(masked_db)))
    if em[0] != 0 or db[:32] != hashlib.sha256(label).digest():
        raise ValueError("decryption error")
    return db[db.index(b"\x01", 32) + 1:]

k = 128
seed = hashlib.sha256(b"stand-in for 32 random bytes").digest()
em = oaep_encode(b"attack at dawn", k, seed)
print(em[:16].hex(), "...")
print(oaep_decode(em, k))
tampered = em[:-1] + bytes([em[-1] ^ 1])
try:
    oaep_decode(tampered, k)
except ValueError as err:
    print("tampered:", err)
003dd11444c54bbe7d3bc9ff171e5ca6 ...
b'attack at dawn'
tampered: decryption error

Implementation pitfalls

Even OAEP leaks if the code reports why decryption failed (Manger's 2001 attack used the difference between "leading byte not zero" and "hash mismatch"). Correct implementations compute everything, compare in constant time, and return one generic error.

In software

  • Python: public_key.encrypt(m, padding.OAEP(mgf=padding.MGF1(hashes.SHA256()), algorithm=hashes.SHA256(), label=None)).
  • PKCS #1 v1.5 encryption is still accepted by many libraries for compatibility; they mitigate Bleichenbacher by returning a random fake plaintext instead of an error ("implicit rejection").

Exercises

Exercise 1: Capacity

With a 2048-bit modulus and SHA-256, how many bytes can OAEP encrypt? How many with PKCS #1 v1.5?

Answer

190 bytes with OAEP-SHA-256; 245 bytes with v1.5.

Solution

k=256k = 256 bytes. OAEP needs 2⋅32+2=662 \cdot 32 + 2 = 66 bytes of overhead: 256−66=190256 - 66 = 190. PKCS #1 v1.5 needs 11 bytes (00 02, at least 8 filler bytes, 00): 256−11=245256 - 11 = 245. Either way RSA encrypts a short symmetric key, never bulk data.

Exercise 2: Why nonzero filler?

In PKCS #1 v1.5, why must the padding bytes PS be nonzero?

Answer

The first zero byte marks where the message starts.

Solution

The decoder scans for the first 00 after 00 02. A zero inside PS would cut the filler short and return part of it as the message.

Exercise 3: Randomized encryption (code)

Encode the same message twice with OAEP using two different seeds and show the encoded blocks differ but decode to the same message.

Answer

Different blocks, same message.

Solution
python · try it yourself
import hashlib
def mgf1(seed, length):
    return b"".join(hashlib.sha256(seed + i.to_bytes(4, "big")).digest() for i in range((length + 31) // 32))[:length]
xor = lambda a, b: bytes(x ^ y for x, y in zip(a, b))
def enc(msg, k, seed):
    db = hashlib.sha256(b"").digest() + b"\x00" * (k - len(msg) - 66) + b"\x01" + msg
    mdb = xor(db, mgf1(seed, len(db)))
    return b"\x00" + xor(seed, mgf1(mdb, 32)) + mdb
def dec(em):
    mdb = em[33:]
    db = xor(mdb, mgf1(xor(em[1:33], mgf1(mdb, 32)), len(mdb)))
    return db[db.index(b"\x01", 32) + 1:]
a = enc(b"yes", 128, hashlib.sha256(b"seed 1").digest())
b = enc(b"yes", 128, hashlib.sha256(b"seed 2").digest())
print(a == b, dec(a), dec(b))
False b'yes' b'yes'

Go further: RSA Done Right: OAEP and PSS uses OAEP and PSS through the cryptography library and tells the PKCS#1 v1.5 story.

Test yourself

PKCS #1 v1.5 encrypted blocks start with the bytes…

  1. 00 01
  2. 00 02
  3. FF FF
  4. 01 00

Bleichenbacher's attack needs…

  1. the private key
  2. an oracle revealing whether decrypted padding is valid
  3. a quantum computer
  4. the factorization of nn

What does OAEP add compared with textbook RSA?

  1. a larger exponent
  2. randomness mixed through hash-based masks
  3. a second modulus
  4. compression