Quantum Key Distribution for Developers — BB84 with Qiskit
Quantum Key Distribution (QKD) is the rare quantum protocol that does something classical cryptography genuinely cannot: it lets two parties detect, in real time, whether an eavesdropper was listening to their key exchange. The security doesn't come from computational hardness — it comes from measurement disturbance, one of the few aspects of quantum mechanics that holds up even against an adversary with infinite computing power.
This post walks through the oldest and most practical of these protocols, BB84, from the raw qubits up to a working Qiskit implementation. No math degree required — just circuits, Python, and the willingness to re-sift a key.

The problem BB84 solves
Two parties, Alice and Bob, want to share a secret random bit string. A classic approach — Diffie-Hellman — is secure only if the enemy can't solve a hard math problem. But a future quantum computer (or a patient classic one) could break it. BB84 sidesteps the math entirely: Alice sends information encoded in individual qubits, and Bob measures them. If Eve intercepts and re-sends, she cannot avoid disturbing the state in a way that Alice and Bob can detect.
That last point is the whole trick. Measure a qubit and you force it into a classical outcome; you can't copy it and observe both its "which basis" and "what value" facts. So an attack inevitably leaves a fingerprint.
The protocol in five steps
- Alice picks a random bit (0 or 1) and a random basis — either the computational basis (Z, where |0>/|1> are meaningful) or the Hadamard basis (X, where |+>/|-> live). She encodes the bit and sends the qubit.
- Bob measures each incoming qubit, guessing at random a basis. If he guessed the same basis Alice used, the measurement is reliable; if not, he gets a 50/50 result.
- They repeat for many qubits.
- Sifting: Alice and Bob announce which bases they used (not the bits). They keep only the qubits where bases matched.
- Out of the sifted bits, they spot-check a random subset. Any mismatch signals an eavesdropper.
The genius is that the basis announcement leaks nothing secret, but the bits, when bases agree, are perfectly correlated — and any interference shows up as mismatches in the check.
Building BB84 in Qiskit
We'll encode bits like this:
- Bit
0in the Z basis: the qubit stays in state|0>(no gate). - Bit
1in the Z basis: apply anXgate →|1>. - Bit
0in the X basis: apply anHgate →|+>. - Bit
1in the X basis: applyXthenH→|->. Order matters:HthenXwould giveX|+> = |+>, the same state as bit 0, and Bob could never tell them apart.
On the receiving side, Bob measures in the basis he guessed: no gate for Z, H before measure for X.
from qiskit import QuantumCircuit, ClassicalRegister
from qiskit_aer.primitives import SamplerV2
import numpy as np
rng = np.random.default_rng(42)
def encode_bit(circ, qubit, bit, basis):
"""Encode one bit in the given basis (0 = Z, 1 = X)."""
if bit == 1:
circ.x(qubit) # flip to |1>
if basis == 1:
circ.h(qubit) # rotate to X basis: |0> -> |+>, |1> -> |->
def measure_bit(circ, qubit, basis):
"""Measure in the basis guessed by Bob (0 = Z, 1 = X)."""
if basis == 1:
circ.h(qubit) # rotate back to Z before measuring
circ.measure(qubit, qubit)
A full run with sifting
We'll pick a decision length, encode a circuit with all transmissions, run it on a simulator (and note where real hardware would slot in), then sift.
n = 40 # number of qubits to send
bob_bases = rng.integers(0, 2, size=n) # Bob's random guesses
alice_bits = rng.integers(0, 2, size=n) # Alice's secret bits
alice_bases = rng.integers(0, 2, size=n) # Alice's basis choices
circ = QuantumCircuit(n, n)
for i in range(n):
encode_bit(circ, i, int(alice_bits[i]), int(alice_bases[i]))
measure_bit(circ, i, int(bob_bases[i]))
sampler = SamplerV2()
result = sampler.run([circ], shots=1).result()
counts = result[0].data.c.get_counts()
# Only one shot emitted from this simulator; parse the binary key
raw_bits = list(counts.keys())[0][::-1]
# Sift: keep only where bases matched
sifted_key = []
for i in range(n):
if alice_bases[i] == bob_bases[i]:
sifted_key.append(int(raw_bits[i]))
print(f"Raw length: {n}, sifted length: {len(sifted_key)}")
print("Sifted key (first 16 bits):", ''.join(map(str, sifted_key[:16])))
On a single-shot simulator, Bob measures exactly what Alice sent when the bases agree, because there's no noise or eavesdropping. The sifted key should match Alice's original bits on those positions — run it and check.
Moving to a simulator with shots and noise
Real hardware returns counts over many shots, and noise (or an eavesdropper) will corrupt some of them. To model that, we run each qubit with, say, 1024 shots and take the most frequent outcome as the "measured" bit.
def measured_bit(circ, index, shots=1024):
res = sampler.run([circ], shots=shots).result()
counts = res[0].data.c.get_counts() # one circuit -> result[0]
# majority vote for this qubit (bitstrings are little-endian, so reverse first)
ones = sum(c for bits, c in counts.items() if bits[::-1][index] == '1')
return 1 if ones > shots / 2 else 0
# For the noiseless case this just recovers the exact bit.
With a depolarizing noise model attached to the simulator, you'd start seeing occasional flips. Those flip bits are, from Alice and Bob's point of view, indistinguishable from an eavesdropper — which is why the error threshold check at the end of the protocol is what actually protects the key. If the observed error rate stays under the security threshold, they can safely distill a shorter, perfectly secret key from the sifted bits; if it's too high, they abort.
The protocol logic in one function
Here's a compact, reusable version:
def bb84(n=40, seed=7):
rng = np.random.default_rng(seed)
alice_bits = rng.integers(0, 2, size=n)
alice_bases = rng.integers(0, 2, size=n)
bob_bases = rng.integers(0, 2, size=n)
circ = QuantumCircuit(n, n)
for i in range(n):
encode_bit(circ, i, int(alice_bits[i]), int(alice_bases[i]))
measure_bit(circ, i, int(bob_bases[i]))
sampler = SamplerV2()
counts = sampler.run([circ], shots=1).result()[0].data.c.get_counts()
raw = list(counts.keys())[0][::-1]
key, agree = [], []
for i in range(n):
if alice_bases[i] == bob_bases[i]:
key.append(int(raw[i]))
agree.append((alice_bits[i], int(raw[i])))
# error check: noiseless simulator -> 0 mismatches
errors = sum(1 for a, b in agree if a != b)
print(f"Sifted length {len(key)}, mismatches {errors}")
return key
On the ideal simulator this gives zero mismatches. Introduce a bit-flip noise model and the mismatch count climbs — the protocol then knows something (noise or Eve) disturbed the channel.
Privacy amplification and the real caveat
BB84 as written gives you an informationally secure key, but real deployments add two more layers: error correction (to reconcile the few flipped bits between Alice and Bob using a public protocol) and privacy amplification (hashing the reconciled key down so that any tiny amount of information Eve gained is crushed to nothing). Neither is quantum — they're classical cryptographic tools that finish the job BB84 starts.
The honest caveats, from running this stuff:
- Hardware is noisy. Simulators make BB84 look trivial. On real hardware, readout and gate errors look exactly like eavesdropping, so deployed systems set a mismatch budget above the noise floor.
- Channels matter. The protocol assumes a quantum channel that can't be tapped without detection. Practical free-space and fiber systems depend on careful photon-level engineering.
- It's not a replacement for all keys. QKD exchanges short, high-value keys at low rates; you typically use it to seed a classical session, not to carry bulk traffic.
Why a developer should care
You probably won't run BB84 in production this year. But the protocol is the cleanest on-ramp to thinking in terms of quantum advantage that's fundamentally unbreakable, and it's directly relevant to conversations about post-quantum migration (the discussion of replacing classical key exchange). Understanding BB84 is also what makes the rest of QKD literature — measurement-device-independent QKD, twin-field QKD — click. And if you're running Qiskit on actual hardware, it's one of the few protocols where the "quantum" part produces something with real cryptographic meaning at the end, rather than just a probability distribution.

For the physical-seed angle we care about in generative art, it's also a nice reminder that measurement is not free information: every readout disturbs the system. That's the same principle behind why the seeds in our collection are tied to specific hardware epochs — the measurement is an event with a fingerprint, not a passive read.
Comments
Post a Comment