This BB84 tutorial builds a small, reusable simulation of quantum key distribution, then uses it to measure sifting, estimate the quantum bit error rate (QBER), and compare an honest exchange with an intercept-resend eavesdropping attack. The example is deliberately SDK-neutral, so you can run it without a quantum backend and later port the same experiment to Qiskit, Cirq, or another framework.
Overview
BB84 is a prepare-and-measure protocol in which a sender, commonly called Alice, encodes random bits using one of two measurement bases. The receiver, Bob, independently chooses a basis for every incoming qubit. After transmission, Alice and Bob publicly compare bases—not the encoded bit values—and keep only the positions where their bases match. This process is called sifting.
The protocol is useful for teaching an important quantum cryptography principle: measuring a qubit in the wrong basis can produce a random result, and an attacker cannot reliably measure and resend every qubit without introducing detectable errors. In a practical system, BB84 also requires authenticated classical communication, error correction, privacy amplification, carefully characterized hardware, and a security analysis. A simulator demonstrates protocol behavior; it does not create a deployable cryptographic system.
Our experiment will generate random data, simulate quantum measurements, optionally insert an intercept-resend attacker, sift the results, reveal a test subset, and estimate QBER. The same structure is useful when you later add device noise, biased basis selection, finite-key effects, or a real circuit simulator.
Educational simulation versus deployable QKD
| Educational experiment | Deployable cryptographic system |
|---|---|
| Uses a software model of preparation and measurement | Uses characterized optical or other quantum hardware and a defined threat model |
| May use an ordinary pseudorandom generator | Requires appropriate randomness, authenticated classical communication, and key-management controls |
| Estimates errors from simulated samples | Needs finite-key analysis, error correction, privacy amplification, and implementation security |
| Illustrates BB84 behavior | Must be independently reviewed and tested before any security claim |
What to track
Track the variables that explain both the protocol outcome and the reason for any change. In this tutorial, a bit is represented by 0 or 1, while a basis is represented by Z or X. The Z basis corresponds to computational-basis preparation and measurement. The X basis corresponds to Hadamard-basis preparation and measurement.
- Raw length: the number of qubits prepared and transmitted.
- Matching bases: the positions where Alice and Bob selected the same basis.
- Sifted length: the number of positions retained after basis comparison.
- Test sample size: the number of sifted bits publicly revealed for error estimation.
- Observed errors: disagreements in the revealed test sample.
- QBER: observed errors divided by the number of revealed test bits.
- Attack model: no attacker, intercept-resend, or a deliberately added channel-noise model.
Here is a compact Python model. It does not pretend to simulate a physical statevector; instead, it implements the BB84 measurement rules directly. That makes the protocol logic easy to inspect and gives you a stable reference for testing an SDK-based circuit later.
import random
def measure(bit, prepared_basis, measured_basis, rng):
# Same basis: measurement returns the encoded bit.
if prepared_basis == measured_basis:
return bit
# Different bases: the result is uniformly random.
return rng.randrange(2)
def bb84_rounds(n=1000, intercept_resend=False, seed=7):
rng = random.Random(seed)
alice_bits = [rng.randrange(2) for _ in range(n)]
alice_bases = [rng.choice(("Z", "X")) for _ in range(n)]
bob_bases = [rng.choice(("Z", "X")) for _ in range(n)]
bob_results = []
for bit, basis, bob_basis in zip(alice_bits, alice_bases, bob_bases):
if intercept_resend:
eve_basis = rng.choice(("Z", "X"))
eve_bit = measure(bit, basis, eve_basis, rng)
# Eve resends the state she measured, in her chosen basis.
result = measure(eve_bit, eve_basis, bob_basis, rng)
else:
result = measure(bit, basis, bob_basis, rng)
bob_results.append(result)
matching = [i for i in range(n) if alice_bases[i] == bob_bases[i]]
sifted_alice = [alice_bits[i] for i in matching]
sifted_bob = [bob_results[i] for i in matching]
# Reveal a test subset; never use these revealed bits as key material.
test_count = max(1, len(matching) // 5)
test_positions = set(rng.sample(range(len(matching)), test_count))
errors = sum(sifted_alice[i] != sifted_bob[i] for i in test_positions)
qber = errors / test_count
remaining_alice = [b for i, b in enumerate(sifted_alice)
if i not in test_positions]
remaining_bob = [b for i, b in enumerate(sifted_bob)
if i not in test_positions]
return {
"raw_length": n,
"matching_bases": len(matching),
"sifted_length": len(sifted_alice),
"test_count": test_count,
"errors": errors,
"qber": qber,
"alice_key_candidate": remaining_alice,
"bob_key_candidate": remaining_bob,
}
for attack in (False, True):
result = bb84_rounds(n=10_000, intercept_resend=attack, seed=11)
print("intercept-resend:", attack)
print({k: result[k] for k in
("raw_length", "sifted_length", "test_count", "errors", "qber")})
Run several seeds rather than relying on one output. In the honest case, the estimated QBER should usually be close to zero in this ideal model. With intercept-resend enabled, mismatched Eve and Alice bases can create errors that survive sifting. The exact value varies because the experiment is sampled randomly.
Cadence and checkpoints
Use a short checkpoint after each stage instead of debugging only the final key. First, verify that Alice and Bob each generated exactly n bits and bases. Next, confirm that every retained position satisfies alice_basis == bob_basis. Then check that the test positions are removed from both key candidates.
- Preparation checkpoint: confirm the raw arrays have equal length and contain only valid bits and bases.
- Measurement checkpoint: test the
measurefunction directly. Equal bases must return the input bit; different bases must produce both outcomes over repeated trials. - Sifting checkpoint: verify that the sifted length equals the number of matching basis positions.
- Estimation checkpoint: calculate QBER only from the revealed test subset.
- Key checkpoint: verify that the unrevealed Alice and Bob candidates match in an ideal, no-attack run.
For a stronger experiment, repeat each configuration across many seeds and record the mean and spread of QBER. Then vary the raw length, test fraction, and attack probability. Larger samples generally make the estimated error rate less sensitive to a single random run, while very small samples can conceal or exaggerate an attack.
If you port this workflow to Qiskit or Cirq, retain the same checkpoints. Build one circuit per transmitted qubit, apply an X gate for bit one, apply an H gate for the X basis, measure in Bob's selected basis, and collect many shots. Keep basis selection and classical post-processing outside the circuit so the protocol stages remain visible. SDK APIs and measurement-result formats change, so pin and record the framework version when saving an experiment.
How to interpret changes
A sifted key is not expected to retain every transmitted bit. When Alice and Bob choose two bases uniformly, only the matching-basis positions are eligible in the simplest model. A lower-than-expected sifted fraction may indicate biased basis selection, an indexing error, or a changed experiment definition—not automatically a security problem.
QBER is an observed diagnostic, not a universal pass-or-fail threshold. In an ideal no-attack simulation it should be near zero. An intercept-resend attack introduces errors because Eve sometimes measures in a basis different from Alice's and then sends a state inconsistent with the original preparation. Added channel noise can produce a similar symptom, so compare attack and noise models rather than attributing every error to an adversary.
Three implementation mistakes are especially common:
- Comparing bit values before sifting: mismatched bases are not supposed to agree reliably, so those positions should be discarded first.
- Using revealed test bits as key bits: remove every publicly disclosed test position from both candidates.
- Calling the remaining string a secure key: real protocols require reconciliation and privacy amplification, and the classical channel must be authenticated.
For related simulator choices, see Quantum Simulators Compared. If you add realistic noise, the workflow in Quantum Error Mitigation Explained can help you separate measurement artifacts from protocol behavior.
When to revisit
Re-run this experiment whenever you change the SDK, simulator, circuit construction, measurement convention, or random-number handling. A monthly or quarterly review is useful for a maintained tutorial: execute the baseline and intercept-resend cases, compare sifted length and QBER with prior runs, and confirm that the code still produces the documented diagnostics.
Revisit sooner when a framework changes its circuit or sampler API, when measurement bit ordering is revised, or when you add a new noise or attack model. Record the framework version, Python version, seed policy, number of shots or rounds, basis distribution, test fraction, and model assumptions alongside each result. This turns the article into a reproducible experiment rather than a screenshot of one run.
For the next step, save the script as a small regression test. Assert that equal-basis measurements preserve the bit, that sifting uses only matching bases, and that an ideal no-attack run produces identical unrevealed candidates. Then port the same assertions to your preferred quantum SDK. The goal is not to claim a production QKD implementation; it is to maintain a clear, testable BB84 reference as your quantum programming tools evolve.