Breaking Merkle-Hellman: Recovering the Key from the Public Key
Shamir broke the basic Merkle-Hellman knapsack in 1982 without seeing a single ciphertext. This guide rebuilds his key-recovery attack with a small LLL lattice, finds a working private key for the guide's 32-bit key in milliseconds, and measures it on keys of up to 256 bits.
Pashalis Laoutaris 21 min read
Try it
Interactive Merkle-Hellman Key Recovery
🔐 Merkle-Hellman Key Recovery
Breaking Merkle-Hellman: Recovering the Key from the Public Key
Introduction
The Merkle-Hellman knapsack cryptosystem hides an easy subset sum behind one modular multiplication. The guide on this site already breaks it one message at a time. That attack builds a big lattice from the public key and a ciphertext, and LLL pulls out the message bits. It works, but it starts over for every new ciphertext.
Adi Shamir’s attack from 1982 goes further. It looks only at the public key, and it returns a private key that works. It may not be the real one, but it decrypts every message just as well. After that, the attacker reads all traffic with the same fast greedy method that the owner uses. This guide rebuilds that attack in a short Python program, with a small LLL lattice in place of the integer programming that Shamir used.
Table of Contents
- Introduction
- Merkle-Hellman in One Paragraph
- The Leak: Small Weights Make Close Fractions
- Finding k1 with a Small Lattice
- From k1 to a Working Key
- Interactive Visualizer
- A Worked Example
- How Fast Is It?
- Python Implementation
- Limitations
- Security Status
- FAQ
- References
Merkle-Hellman in One Paragraph
The private key is a superincreasing list W = (w_1, ..., w_n), where each number is larger than the sum of all the numbers before it. It also has a modulus q above the sum of W, and a multiplier r with no common factor with q. The public key is B, with b_i = r * w_i mod q. To encrypt n bits, add up the b_i whose bit is 1. To decrypt, multiply the ciphertext by u = r^-1 mod q. That gives a sum of some w_i, and a greedy pass from the largest number down reads off the bits.
The Leak: Small Weights Make Close Fractions
Write the decryption step for a single public number. Since u * b_i mod q = w_i, there is a whole number k_i with:
u * b_i = w_i + k_i * q so u / q - k_i / b_i = w_i / (b_i * q)
The first few weights are tiny. In the guide’s key generator, w_1 is below 2^n, while q has about 2n bits. So for the first few i, the fraction k_i / b_i is extremely close to u / q. All of them are close to the same number, so they are also close to each other. Multiply out the difference of the first two and you get a whole number that is unusually small:
q * (k_1 * b_i - k_i * b_1) = w_i * b_1 - w_1 * b_i
The right side is at most about w_i * q, so k_1 * b_i - k_i * b_1 is roughly as small as w_i. That is about n + i bits, while k_1 * b_i alone has about 4n bits. Andrew Odlyzko’s survey makes this point. Products of two such large numbers almost never cancel this well by chance. So the public key alone pins down k_1, a number the attacker was never told.
Finding k1 with a Small Lattice
Shamir found k_1 with H. W. Lenstra’s integer programming algorithm in a fixed number of variables. It runs in polynomial time but is far too slow to use. Odlyzko’s survey says it has never been implemented. The LLL algorithm, which came out of the same line of work, does the job in practice.
Take the first t public numbers, with t between 4 and 12, and a scale S = 2^s. Build a lattice with these t rows:
row 1: (1, S*b_2, S*b_3, ..., S*b_t)
row i: (0, ..., -S*b_1 in place i, ..., 0) for i = 2 .. t
Take k_1 times the first row plus k_i times row i. The result is the vector (k_1, S*(k_1*b_2 - k_2*b_1), ..., S*(k_1*b_t - k_t*b_1)). Its first entry has about 2n bits and the others are small, so the whole vector is short. The scale makes both kinds of entries about the same size, which makes the vector stand out. For keys like the guide’s, a good first scale is 2^(bits/2 - t), where bits is the size of the largest public number.
One detail took some testing. LLL often returns the vector we want as the sum or difference of its first two or three rows, not as a row by itself. The code therefore tries every combination of the first three reduced rows with coefficients from -2 to 2, shortest first. Without it, k_1 never showed up as a single row for 4 of the first 8 test keys with n = 32, at any lattice size or scale. With it, all 100 keys of that size worked.
From k1 to a Working Key
Knowing k_1 gives the fraction x0 = k_1 / b_1, and u / q sits just above it. Now look for any ratio x = U / M near x0 that works as a key. For such a pair, each new weight is w'_i = U * b_i mod M. Divide by M and this is the fractional part of x * b_i.
Two facts make the search easy. First, a superincreasing list with sum below M has w'_1 < M / 2^(n-1), because each partial sum at least doubles. So x must lie between x0 and x0 + 1 / (2^(n-1) * b_1), a very narrow window. Second, inside that window, x * b_i crosses a whole number only at a few points. Between two such points, each w'_i / M is just x * b_i - k_i for a fixed k_i. Every condition, from “each w'_i is larger than the sum before it” to “the sum stays below M”, becomes a linear inequality in x.
So the code cuts the window at those points and solves the inequalities on each piece. A piece with a solution is an open interval of good ratios. From it, the code picks the fraction with the smallest denominator, using the Stern-Brocot method. That fraction is U / M. As Odlyzko notes, infinitely many pairs work, and this attack does not find the designer’s own u and q. In my tests it never did. In 100 keys with n = 32 and 100 with n = 64, the recovered M was always smaller than the real q.
Interactive Visualizer
The visualizer above runs the whole attack in your browser. Choose the Wikipedia example, the 32-bit key of the Merkle-Hellman guide, or a random key of 16 to 64 bits made by the guide’s key generator. You can also paste any public key. Click the button and the five cards fill in turn. You see the public key, the lattice and its short vector, the search window, the recovered key, and a decryption.
The bars show the size of each number in bits. The public key looks like noise, and the recovered W' climbs like a staircase, one bit per step. Edit the message bits after the key is found to decrypt other messages. The visualizer uses the same lattice, the same order of tries, and the same search as the Python code below. On 210 random keys, both returned exactly the same U and M.
A Worked Example
The Merkle-Hellman guide uses the example from Wikipedia: W = (2, 7, 11, 21, 42, 89, 180, 354), q = 881 and r = 588. The public key is:
B = (295, 592, 301, 14, 28, 353, 120, 236)
The attacker sees only B. The largest number has 10 bits, so the first try uses t = 4 rows and the scale 2^(5 - 4) = 2:
(1, 1184, 602, 28)
(0, -590, 0, 0)
(0, 0, -590, 0)
(0, 0, 0, -590)
LLL needs 9 swaps. The first two reduced rows are (1, 4, 12, 28) and (147, -2, -6, -14). Neither works alone, but their sum is (148, 2, 6, 14). Divide out the scale, and the differences are 1, 3 and 7. So k_1 = 148, and indeed 148 * 592 - 297 * 295 = 1. The real numbers confirm it: 881 * 1 = 7 * 295 - 2 * 592.
The ratio x0 = 148 / 295 is about 0.5016949. The window has width 1 / (2^7 * 295), which is about 0.0000265, and no breakpoint falls inside it. The inequalities cut it down to the interval from 148/295 to 589/1174, which is about 0.5016949 to 0.5017036. The real u / q = 442 / 881 is about 0.5017026, inside that interval. The fraction with the smallest denominator in it is 295 / 588:
W' = 295 * B mod 588 = (1, 4, 7, 14, 28, 59, 120, 236) sum 469 < 588
This list is superincreasing, so it is a working private key. The ciphertext from the guide is 1129, and multiplying by U gives 295 * 1129 mod 588 = 247. The greedy pass takes 236, then 7, then 4, and reaches 0. Those are places 8, 3 and 2, so the bits are 01100001, the letter “a”. That is the message the guide encrypted, read with a key its owner never made.
How Fast Is It?
The attack ran on random keys from the guide’s key generator, 100 keys per size up to 128 bits. Each recovered key was checked by decrypting 50 random messages. The times are for pure Python on the machine that built this page:
| Key size n | Keys recovered | Mean time per key | Slowest key |
|---|---|---|---|
| 8 | 74 of 100 | 0.009 s | 0.06 s |
| 16 | 100 of 100 | 0.001 s | 0.01 s |
| 32 | 100 of 100 | 0.003 s | 0.07 s |
| 64 | 100 of 100 | 0.005 s | 0.03 s |
| 100 | 100 of 100 | 0.009 s | 0.07 s |
| 128 | 100 of 100 | 0.025 s | 0.28 s |
| 200 | 20 of 20 | 0.035 s | 0.06 s |
| 256 | 20 of 20 | 0.075 s | 0.41 s |
The misses at n = 8 happen because the lattice has too few rows to single out k_1 among numbers this small. Those keys are easy anyway. The first public number is below 2^17, so the attacker can simply try every k_1. That brute force recovered all 26 missed keys, after at most 35,941 tries.
For contrast, the message attack in the Merkle-Hellman guide needs an (n + 1)-row lattice for every ciphertext. It took under a second per message at n = 100, and it missed some messages. The key attack reduces a lattice of at most 12 rows, once. After that, each message costs one multiplication and one greedy pass.
Python Implementation
This program needs lll.py from the Merkle-Hellman guide, the integral LLL of Cohen, saved in the same folder. It recovers the key for the Wikipedia example and for the guide’s 32-bit key. Run it with --bench 100 to repeat the measurements above.
# mh_key_recovery.py
#
# Recovers a working private key for the basic Merkle-Hellman cryptosystem from the public key alone.
# This is Shamir's idea (1982). Shamir found k1 with Lenstra's integer programming algorithm; this code
# uses LLL on a small lattice instead, which is the practical route. After the key is found, every
# ciphertext decrypts with the fast greedy method, with no more lattice work. It needs lll.py from the
# Merkle-Hellman guide in the same folder.
import itertools
import math
import random
from fractions import Fraction
from math import gcd
from lll import lll_reduce
def random_private_key(n, rng):
"""The key generator of the Merkle-Hellman guide: W superincreasing, q above its sum, r coprime to q."""
w, total = [], 0
for _ in range(n):
x = total + rng.randrange(1, 2**n)
w.append(x)
total += x
q = total + rng.randrange(1, 2**n)
r = rng.randrange(2, q - 1)
while gcd(r, q) != 1:
r = rng.randrange(2, q - 1)
return w, q, r
def is_superincreasing(w):
total = 0
for x in w:
if x <= total:
return False
total += x
return True
def candidates_for_k1(b, t, s):
"""LLL on t rows. A short vector is (k1, 2^s (k1 b_i - k_i b_1) for i = 2..t), and k1 is its first entry.
k1 is the whole number with u * b_1 = w_1 + k1 * q, for the true multiplier u = r^-1 mod q.
Because w_1, ..., w_t are small, k1 * b_i - k_i * b_1 is small for every i <= t. The lattice often
has a few short vectors of about the same length, so LLL may return the one we want as a sum of
its first rows. The candidates are small combinations of the first three rows, shortest first.
"""
scale = 2**s
basis = [[1] + [scale * x for x in b[1:t]]]
for i in range(1, t):
row = [0] * t
row[i] = -scale * b[0]
basis.append(row)
reduced, swaps = lll_reduce(basis)
rows = reduced[:3]
combos = []
for coefs in itertools.product(range(-2, 3), repeat=len(rows)):
v = [sum(c * row[j] for c, row in zip(coefs, rows)) for j in range(t)]
if 0 < abs(v[0]) < b[0]:
combos.append((sum(x * x for x in v), abs(v[0])))
ks = []
for _, k in sorted(combos):
if k not in ks:
ks.append(k)
return ks, swaps
def simplest_between(lo, hi):
"""The fraction with the smallest denominator strictly between lo and hi (lo < hi, both may be fractions)."""
fl = math.floor(lo)
if fl + 1 < hi:
return Fraction(fl + 1)
if lo == fl: # find 1/m below hi - fl
return fl + Fraction(1, math.floor(1 / (hi - fl)) + 1)
return fl + 1 / simplest_between(1 / (hi - fl), 1 / (lo - fl))
def key_from_k1(b, k1):
"""Search near x0 = k1 / b_1 for a ratio x = U / M that turns B into a superincreasing W' with sum below M.
Near x, every u * b_i mod M is M * (x * b_i - k_i) with fixed k_i, so each condition is linear in x.
The sum of a superincreasing W' is above 2^(n-1) w'_1, so w'_1 < M / 2^(n-1) and x lies in (x0, x0 + 1 / (2^(n-1) b_1)).
"""
n = len(b)
x0 = Fraction(k1, b[0])
end = x0 + Fraction(1, 2**(n - 1) * b[0])
cuts = {x0, end}
for bi in b:
for j in range(math.floor(x0 * bi) + 1, math.floor(end * bi) + 1):
cuts.add(Fraction(j, bi))
cuts = sorted(cuts)
for lo, hi in zip(cuts, cuts[1:]):
mid = (lo + hi) / 2
k = [math.floor(mid * bi) for bi in b]
# each condition is x * coef > rhs; the last one, sum below 1, is written as x * (-sum b) > 1 - sum k
conds, sb, sk = [], 0, 0
for bi, ki in zip(b, k):
conds.append((bi - sb, ki - sk))
sb, sk = sb + bi, sk + ki
conds.append((-sb, -sk - 1))
left, right = lo, hi
for coef, rhs in conds:
if coef > 0:
left = max(left, Fraction(rhs, coef))
elif coef < 0:
right = min(right, Fraction(rhs, coef))
elif rhs >= 0:
right = left
if left < right:
x = simplest_between(left, right)
u, m = x.numerator, x.denominator
w = [u * bi % m for bi in b]
assert is_superincreasing(w) and sum(w) < m
return u, m, w
return None
def recover_key(b):
"""Try lattice sizes t and scales 2^s until a k1 gives a working key. Returns (u, m, w', tries, swaps).
The scale balances the two kinds of entries in the short vector: k1, which is about as large as q,
and the differences, which are about as large as w_t. For keys made like the guide's, w_1 is near
the square root of q, so the scale 2^(bits/2 - t) is tried first for every t, and the others after.
"""
n = len(b)
bits = max(b).bit_length()
sizes = range(min(n, 4), min(n, 12) + 1)
first = [(t, max(bits // 2 - t, 0)) for t in sizes]
rest = [(t, s) for t in sizes for s in range(max(bits // 2 - t, 0) - 1, -1, -1)]
tries = swaps = 0
for t, s in first + rest:
tries += 1
ks, sw = candidates_for_k1(b, t, s)
swaps += sw
for k1 in ks:
key = key_from_k1(b, k1)
if key:
return key + (tries, swaps)
return None
def decrypt(c, u, m, w):
"""Greedy decryption with any working key: c' = u * c mod m is a sum of some w'_i."""
rest = u * c % m
bits = [0] * len(w)
for i in range(len(w) - 1, -1, -1):
if w[i] <= rest:
bits[i], rest = 1, rest - w[i]
return bits if rest == 0 else None
def bits_of(x, n):
return [(x >> (n - 1 - i)) & 1 for i in range(n)]
def encrypt(bits, b):
return sum(x * y for x, y in zip(bits, b))
def show(name, b, c, true_u, true_q):
u, m, w, tries, swaps = recover_key(b)
print(name)
print(" true key: u = r^-1 mod q = %d, q = %d" % (true_u, true_q))
print(" recovered: u = %d, m = %d (lattice tries: %d, LLL swaps: %d)" % (u, m, tries, swaps))
print(" w' =", w if len(w) <= 8 else str(w[:5])[:-1] + ", ...]", "superincreasing:", is_superincreasing(w), "sum < m:", sum(w) < m)
print(" c = %d decrypts to %s" % (c, "".join(map(str, decrypt(c, u, m, w)))))
if __name__ == "__main__":
import sys
import time
# the example of the Wikipedia article, as in the Merkle-Hellman guide
w, q, r = [2, 7, 11, 21, 42, 89, 180, 354], 881, 588
b = [r * x % q for x in w]
show("Wikipedia key, B = %s" % b, b, 1129, pow(r, -1, q), q)
# the n = 32 key of the guide (seed 1978) and its ciphertext
rng = random.Random(1978)
w, q, r = random_private_key(32, rng)
b = [r * x % q for x in w]
message = rng.getrandbits(32)
show("The n = 32 key of the guide, message %s" % format(message, "032b"), b, encrypt(bits_of(message, 32), b), pow(r, -1, q), q)
if "--bench" in sys.argv:
runs = int(sys.argv[sys.argv.index("--bench") + 1])
for n in (8, 16, 32, 64, 100, 128):
ok, t0, worst = 0, time.time(), 0
for seed in range(runs):
g = random.Random(seed * 1000 + n)
w, q, r = random_private_key(n, g)
b = [r * x % q for x in w]
t1 = time.time()
key = recover_key(b)
worst = max(worst, time.time() - t1)
if key:
msgs = [bits_of(g.getrandbits(n), n) for _ in range(50)]
ok += all(decrypt(encrypt(x, b), *key[:3]) == x for x in msgs)
print("n = %3d: %d of %d keys, mean %.3f s, worst %.2f s" % (n, ok, runs, (time.time() - t0) / runs, worst), flush=True)
Running the program prints this:
Wikipedia key, B = [295, 592, 301, 14, 28, 353, 120, 236]
true key: u = r^-1 mod q = 442, q = 881
recovered: u = 295, m = 588 (lattice tries: 1, LLL swaps: 9)
w' = [1, 4, 7, 14, 28, 59, 120, 236] superincreasing: True sum < m: True
c = 1129 decrypts to 01100001
The n = 32 key of the guide, message 01100010010101001100100110011011
true key: u = r^-1 mod q = 696996703453556129, q = 4879308755416376181
recovered: u = 83293457492519, m = 583093857400476 (lattice tries: 1, LLL swaps: 59)
w' = [7003, 211188, 402808, 1009134, 2222971, ...] superincreasing: True sum < m: True
c = 35495693987428791407 decrypts to 01100010010101001100100110011011
I checked the code in several ways. Every recovered key is tested for being superincreasing with a sum below M, and the code asserts it. The benchmark decrypts 50 random messages per key and compares them with the originals. The JavaScript in the visualizer was run on the same 210 public keys as the Python, and both returned the same U, M, number of tries and number of swaps for every key.
Limitations
No shuffle. The code assumes that b_1 comes from the smallest secret weight, and that the first few public numbers come from small weights. That holds for the cryptosystem as the guide builds it, without a shuffle. If the public key is shuffled, the attacker must guess which public numbers came from the smallest weights. Odlyzko’s survey describes the answer: try every choice of about five indices, which is still polynomial. Practical versions use more numbers but drop the need to hit the five smallest. This code does not do either.
Key shape. The key generator here makes w_1 about the square root of q. That gap is what makes k_1 stand out. Odlyzko notes that a simpler continued fraction method works for the standard parameters but fails when the weights are larger. The lattice method copes better, but this code was only measured on keys made like the guide’s.
Basic system only. This attack breaks the single-multiplication system. Merkle and Hellman also proposed iterating the multiplication several times. Those variants need more work and are not covered here.
Teaching code. The program uses exact fractions everywhere, which keeps it simple and correct but slow for huge keys. It does not try to be the fastest or most general attack.
Security Status
The basic Merkle-Hellman cryptosystem has been broken since Shamir’s 1982 attack, published in full in 1984. Here a working private key came out of the public key alone for every size tested, up to 256 bits, in under half a second. Do not use it, or any knapsack scheme built on a disguised superincreasing sequence, to protect anything.
The attack is still worth studying. It is one of the first public-key breaks, and it shows a pattern that returns often. A secret structure leaves a trace that is small compared with the numbers around it, and lattice reduction finds small things. The same tools now attack and help design lattice-based schemes, including today’s post-quantum standards.
FAQ
Why does the attack find a different key from the real one?
Many pairs (U, M) turn the public key into a superincreasing list with a small enough sum. The real pair is one of them, and the attack picks the one with the smallest denominator in the interval it finds. Any of them decrypts every message correctly, because the greedy method has only one answer for a superincreasing list.
Does the attacker need a ciphertext?
It does not, because the attack uses only the public key. Once the key is found, the attacker decrypts any ciphertext the owner receives. The message attack in the Merkle-Hellman guide is the opposite, since it needs a ciphertext and recovers only that one message.
Why only the first few numbers of the public key?
The leak comes from weights that are tiny compared with q. Only the first few weights are that small, because each one at least doubles the sum before it. Four to twelve numbers are enough to pin down k_1, and after that the search uses all n numbers.
Would shuffling the public key stop the attack?
Shuffling would not stop it. According to Odlyzko’s survey, the attacker tries every choice of a few indices. There are only about n^5 choices, so the attack stays polynomial. Shuffling makes it slower, not secure.
How is this related to the lattice attack in the Merkle-Hellman guide?
Both use LLL, but they look for different things. The guide’s attack hides a ciphertext in a large lattice and finds the message bits as a short vector. This attack uses a small lattice built from the public key alone and finds the hidden multiplier. The message attack also works on random low-density knapsacks. The key attack needs the disguised superincreasing structure.
References
-
Shamir, Adi. “A Polynomial-Time Algorithm for Breaking the Basic Merkle-Hellman Cryptosystem,” IEEE Transactions on Information Theory, vol. IT-30, no. 5, September 1984, pp. 699-704. First presented in 1982.
-
Odlyzko, Andrew M. “The Rise and Fall of Knapsack Cryptosystems,” in Cryptology and Computational Number Theory (C. Pomerance, ed.), Proceedings of Symposia in Applied Mathematics, vol. 42, American Mathematical Society, 1990, pp. 75-88.
-
Adleman, Leonard M. “On Breaking Generalized Knapsack Public Key Cryptosystems,” Proceedings of the 15th ACM Symposium on Theory of Computing (STOC), 1983, pp. 402-412.
-
Lagarias, J. C. “Knapsack Public Key Cryptosystems and Diophantine Approximation,” Advances in Cryptology, CRYPTO ’83 (D. Chaum, ed.), Plenum Press, 1984, pp. 3-23.
-
Lenstra, A. K., H. W. Lenstra Jr., and L. Lovász. “Factoring Polynomials with Rational Coefficients,” Mathematische Annalen 261, 1982, pp. 515-534 (the LLL algorithm).
-
The Merkle-Hellman guide on this site, whose key generator, example key and LLL code this attack uses: /blog/mh_guide/