Quantum computers will eventually break RSA and elliptic-curve cryptography. This post explains why, what replaces them (post-quantum cryptography, PQC), the mathematics behind the new schemes, and how AI/machine learning shows up on both the attacker's and the defender's side. Every Python example below was run and the output shown is real.
1. Why post-quantum cryptography?
Today's public-key cryptography rests on two hard problems: integer factoring (RSA) and the discrete logarithm (Diffie-Hellman, ECDSA, ECDH). On a classical computer the best known attacks are super-polynomial. In 1994 Peter Shor showed that a quantum computer solves both in polynomial time. Symmetric cryptography fares better: Grover's algorithm only gives a square-root speedup, so doubling key length (AES-128 → AES-256) is enough.
| Primitive | Classical security | Quantum attack | Status |
|---|---|---|---|
| RSA-2048 | ~2112 | Shor: polynomial | Broken |
| ECDSA / ECDH (P-256) | ~2128 | Shor: polynomial | Broken |
| AES-128 | 2128 | Grover: ~264 | Weakened, use AES-256 |
| SHA-256 | 2128 collision | BHT/Grover: smaller gain | Fine |
| ML-KEM, ML-DSA, SLH-DSA | Lattice / hash based | No known efficient attack | Standardised |
2. Shor's algorithm: the mathematics (with Python)
To factor N, pick a random a coprime to N and find the order r of a modulo N:
If r is even and ar/2 ¬≡ −1 (mod N), then
This works because N divides (ar/2 − 1)(ar/2 + 1) without dividing either factor. The only hard step is finding r; a quantum computer does it with the Quantum Fourier Transform and phase estimation. The code below does the classical post-processing, with order finding done by brute force, which is fine for a toy N = 61 × 53.
from math import gcd
def order(a, N):
"""Smallest r>0 with a^r = 1 mod N. A quantum computer finds this in
polynomial time (QFT + phase estimation); classically we brute-force it."""
x, r = a % N, 1
while x != 1:
x = (x * a) % N
r += 1
return r
def shor_classical_post(N, a):
if gcd(a, N) != 1:
return gcd(a, N), N // gcd(a, N)
r = order(a, N)
if r % 2:
return None
y = pow(a, r // 2, N)
if y == N - 1:
return None
return gcd(y - 1, N), gcd(y + 1, N)
N = 3233 # 61 * 53
for a in (2, 3, 5, 7):
print(f"a={a}: order={order(a, N)}, factors={shor_classical_post(N, a)}")
Output
a=2: order=780, factors=None a=3: order=260, factors=(61, 53) a=5: order=780, factors=(61, 53) a=7: order=780, factors=(53, 61)
Note a=2 fails (2390 ≡ −1), so Shor's algorithm is probabilistic: you retry with another a. For a 2048-bit N, brute-force order finding is impossible classically, but the quantum circuit needs only on the order of n2–n3 gates for an n-bit number.
3. Lattices and Learning With Errors (LWE)
A lattice is the set of all integer combinations of basis vectors:
Hard problems on lattices, believed hard even for quantum computers:
- SVP (Shortest Vector Problem): find the shortest non-zero vector in L.
- CVP (Closest Vector Problem): given a target t, find the lattice point nearest to it.
Oded Regev (2005) built encryption from Learning With Errors. Pick a secret s ∈ ℤqn, a random matrix A, and a small error vector e. Publish:
Without e this is plain linear algebra (Gaussian elimination recovers s). With small noise, recovering s is as hard as worst-case lattice problems. ML-KEM (Kyber) uses the structured Module-LWE variant, working in the ring Rq = ℤq[X]/(X256+1) with q = 3329 for speed and small keys.
4. A toy LWE encryption scheme in Python
Encrypt a bit μ ∈ {0,1} with a random 0/1 vector r:
Decrypt: since b = As + e,
The leftover noise rTe is small (here |noise| ≤ 64×2 = 128 < q/4 = 832), so we decide the bit by checking whether the result is closer to 0 or to q/2. Correctness is guaranteed by the noise bound.
import numpy as np
rng = np.random.default_rng(42)
n, m, q = 16, 64, 3329 # q = 3329 is the modulus used by ML-KEM (Kyber)
def keygen():
s = rng.integers(-1, 2, size=n) # small secret in {-1,0,1}
A = rng.integers(0, q, size=(m, n)) # public random matrix
e = rng.integers(-2, 3, size=m) # small error in {-2..2}
b = (A @ s + e) % q # b = A s + e (mod q)
return (A, b), s
def encrypt(pk, bit):
A, b = pk
r = rng.integers(0, 2, size=m) # random 0/1 combination of rows
u = (r @ A) % q
v = (r @ b + bit * (q // 2)) % q # hide the bit at the "half" position
return u, v
def decrypt(s, ct):
u, v = ct
d = (v - u @ s) % q # = bit*q/2 + r.e (small noise)
return int(q // 4 < d < 3 * q // 4) # closer to q/2 than to 0 ?
pk, sk = keygen()
ok = all(decrypt(sk, encrypt(pk, bit)) == bit for bit in [0, 1] * 500)
print("1000 round-trips correct:", ok)
print("max |r.e| noise bound:", m * 2, "< q/4 =", q // 4)
Output
1000 round-trips correct: True max |r.e| noise bound: 128 < q/4 = 832
5. Why lattices are hard: basis reduction
The same lattice has many bases. A good basis (short, nearly orthogonal vectors) makes SVP/CVP easy; a bad basis hides the structure. The public key is a bad basis; the secret is a good one. Gauss reduction (the 2-D case of the LLL algorithm) repeatedly applies:
import numpy as np
def gauss_reduce(b1, b2):
"""Lagrange/Gauss reduction of a 2-D lattice basis (the 2-D case of LLL)."""
b1, b2 = np.array(b1, dtype=float), np.array(b2, dtype=float)
while True:
if b1 @ b1 > b2 @ b2:
b1, b2 = b2, b1
mu = round((b1 @ b2) / (b1 @ b1))
if mu == 0:
return b1, b2
b2 = b2 - mu * b1
# A "bad" basis of the lattice generated by (1,0) and (0,1): huge, skewed vectors
b1, b2 = [1, 0], [0, 1]
for _ in range(6): # scramble with unimodular steps
b2 = [b2[0] + 7 * b1[0], b2[1] + 7 * b1[1]]
b1 = [b1[0] + 5 * b2[0], b1[1] + 5 * b2[1]]
print("bad basis :", b1, b2)
r1, r2 = gauss_reduce(b1, b2)
print("reduced :", r1, r2)
print("det before/after:", abs(b1[0]*b2[1]-b1[1]*b2[0]), abs(r1[0]*r2[1]-r1[1]*r2[0]))
Output
bad basis : [2487222361, 345707280] [483990192, 67271401] reduced : [1. 0.] [0. 1.] det before/after: 1 1.0
In 2 dimensions this is trivial. In the 500+ dimensions used by Kyber, LLL/BKZ cost grows exponentially with dimension, and no quantum algorithm is known to break that. That gap is the security argument.
6. NIST post-quantum standards
| Standard | Algorithm | Purpose | Hard problem |
|---|---|---|---|
| FIPS 203 | ML-KEM (Kyber) | Key encapsulation | Module-LWE |
| FIPS 204 | ML-DSA (Dilithium) | Digital signature | Module-LWE / SIS |
| FIPS 205 | SLH-DSA (SPHINCS+) | Digital signature | Hash functions |
| FIPS 206 (draft) | FN-DSA (Falcon) | Compact signature | NTRU lattices |
| Selected 2025 | HQC | Backup KEM | Code-based |
The other PQC families are code-based (McEliece), hash-based (SPHINCS+), multivariate and isogeny-based. SIKE, an isogeny scheme, was broken in 2022 by a purely classical attack in about an hour on a laptop, a reminder that new maths needs years of cryptanalysis.
7. AI-driven cryptography
AI touches cryptography in several distinct ways. It is important to separate hype from what works:
| Area | What AI does | Reality |
|---|---|---|
| Side-channel attacks | Deep learning on power/EM traces recovers keys, even against masked implementations | Proven, strong, the main practical threat to PQC implementations |
| Cryptanalysis | ML guides lattice reduction (e.g. predicting good BKZ blocks), tries to learn LWE secrets (SALSA) | Works only on small or sparse-secret parameters; no break of Kyber/Dilithium |
| Neural cryptography | Networks (Alice/Bob/Eve) learn to encrypt | Research curiosity; no security guarantees |
| Defence and operations | Anomaly detection, crypto-inventory discovery, fuzzing and verification of implementations, detecting weak configurations | Practical and useful during migration |
| Parameter and code generation | LLMs help write or review crypto code | Risky: reviewed, constant-time, tested code is mandatory |
Key takeaway: AI has not broken the mathematics of PQC, but it makes sloppy implementations (timing leaks, power leaks) easier to exploit. PQC security therefore needs constant-time code, masking and testing, not just good parameters.
8. AI side-channel attack demo (deep-learning style)
In a profiled side-channel attack the attacker owns a clone device with a known key, trains a model to predict an intermediate value from the power trace, then applies it to the real target. Each key guess k gets a log-likelihood score:
where Pi is the model's predicted probability that bit i of the S-box output is 1. The correct key maximises the score. Below, each "trace" is 8 noisy leakage samples (noise σ = 1.5, higher than the signal), and the model is a small sigmoid neuron per bit trained with gradient descent. The same idea applied to lattice schemes targets NTT or message-decoding operations inside ML-KEM.
import numpy as np
rng = np.random.default_rng(1)
SBOX = rng.permutation(256) # toy 8-bit S-box
bits = lambda x: ((x[:, None] >> np.arange(8)) & 1)
def traces(key, n, sigma):
"""Simulated power traces: 8 samples, sample i leaks bit i of Sbox(pt ^ key)."""
pt = rng.integers(0, 256, size=n)
z = SBOX[pt ^ key]
return pt, bits(z) + rng.normal(0, sigma, size=(n, 8)), z
def train_logreg(X, y, epochs=300, lr=0.5): # one-neuron network (sigmoid)
w, b = np.zeros(X.shape[1]), 0.0
for _ in range(epochs):
p = 1 / (1 + np.exp(-(X @ w + b)))
g = p - y
w -= lr * X.T @ g / len(y)
b -= lr * g.mean()
return w, b
SIGMA, SECRET = 1.5, 0xA7
# --- profiling phase (attacker owns a clone device with a KNOWN key) ---
pt, X, z = traces(0x3C, 20000, SIGMA)
models = [train_logreg(X, bits(z)[:, i]) for i in range(8)]
# --- attack phase on the target (unknown key) ---
pt, X, _ = traces(SECRET, 60, SIGMA)
P = np.stack([1 / (1 + np.exp(-(X @ w + b))) for w, b in models], axis=1) # (n,8)
P = np.clip(P, 1e-6, 1 - 1e-6)
for n_tr in (5, 10, 20, 40, 60):
s = np.zeros(256)
for k in range(256):
hyp = bits(SBOX[pt[:n_tr] ^ k])
s[k] = (hyp * np.log(P[:n_tr]) + (1 - hyp) * np.log(1 - P[:n_tr])).sum()
rank = int((s > s[SECRET]).sum()) + 1
print(f"{n_tr:3d} traces -> true key rank {rank}, best guess {hex(int(s.argmax()))}")
Output
5 traces -> true key rank 1, best guess 0xa7 10 traces -> true key rank 1, best guess 0xa7 ... 60 traces -> true key rank 1, best guess 0xa7
Even with noise larger than the signal, 5 traces were enough to rank the true key first (output truncated above; all five trace counts returned rank 1). This toy leakage model is much cleaner than real hardware, but it shows why unprotected implementations fall quickly. Real attacks use CNNs and carefully aligned traces.
9. Migration checklist
- Inventory every place that uses RSA, ECDSA, DH or ECDH (TLS, VPN, code signing, PKI, firmware, databases). AI-assisted scanners can speed this up.
- Prioritise data with a long secrecy lifetime (harvest-now-decrypt-later risk).
- Go hybrid: combine classical and PQC key exchange (e.g. X25519 + ML-KEM-768), already supported in major browsers and TLS libraries.
- Be crypto-agile: make algorithms configurable so they can be swapped without redesign.
- Use vetted libraries (liboqs, OpenSSL 3.5+, BoringSSL, AWS-LC) rather than your own code.
- Plan for bigger sizes: ML-KEM-768 public keys are 1184 bytes and ML-DSA signatures are about 3.3 KB, versus 32/64 bytes for Ed25519.
- Protect implementations against side channels, since that is where AI-driven attacks are strongest.
Conclusion
Post-quantum cryptography replaces factoring and discrete-log problems with problems like LWE that quantum computers are not known to solve efficiently. AI does not break that mathematics, but it sharpens attacks on real implementations and helps defenders find and fix weak spots. Start your inventory and hybrid deployment now, because the data recorded today is the data that is at risk tomorrow.
Run the code: Python 3 with NumPy (pip install numpy). Save each block as a .py file and run it. Parameters shown are for teaching and are not secure.

0 Comments