Learning With Errors for Programmers: One Bit by Hand
Encrypt and decrypt a bit with modular arithmetic, then change the noise until decoding fails.
Background reading Learning With Errors
Build the public key
Work modulo 17. Keep the secret vector s = (3, 5) private. Publish the three rows of A and the three values of b. Each value of b is the corresponding row dotted with s, plus a small error.
A = [(2, 1), (4, 3), (1, 6)] As = [11, 27, 33] e = [1, 0, −1] b = (As + e) mod 17 = [12, 10, 15]
Encrypt and decrypt
Encode 0 as 0 and 1 as 8. Choose the first two public rows using r = (1, 1, 0). Their sum is u = (6, 4). To encrypt 1, add 8 to their two b values. This gives v = (12 + 10 + 8) mod 17 = 13. Send (u, v).
The receiver computes u·s = 38 and subtracts it. The residual (13 − 38) mod 17 is 9. On the circle of 17 residues, 9 is one step from 8 and eight steps from 0. Decode it as 1. The shared algebra cancels the contribution from the secret and leaves the encoded bit plus the sum of selected errors.
Change the error
q = 17
rows = [(2, 1), (4, 3), (1, 6)]
secret = (3, 5)
selected = (0, 1)
def dot(left, right):
return sum(a * b for a, b in zip(left, right))
def round_trip(bit, errors):
public = [(dot(row, secret) + e) % q for row, e in zip(rows, errors)]
u = tuple(sum(rows[i][j] for i in selected) % q for j in range(2))
v = (sum(public[i] for i in selected) + 8 * bit) % q
residual = (v - dot(u, secret)) % q
decoded = min((0, 1), key=lambda m: min((residual - 8*m) % q, (8*m - residual) % q))
return public, (u, v), residual, decoded
for errors in [(0, 0, 0), (1, 0, -1), (3, 2, -1)]:
print(round_trip(1, errors))
# The residuals are 8, 9, 13. The decoded bits are 1, 1, 0.With selected errors totaling 5, the residual wraps toward 0. Try encrypting 0 with the original errors. You should get v = 5, residual 1, and decoded bit 0. These deliberately tiny parameters and fixed choices are for hand calculation.
Next, plot a noisy modular equation as a lattice decoding problem.