Simulates the BB84 Quantum Key Distribution protocol to generate an ephemeral, information-theoretically secure key, then performs fast data encryption using AES-256 GCM — showcasing a practical model for quantum-resistant key management in a microservices environment.
- What is Quantum Key Distribution?
- How BB84 Works
- Project Overview
- Architecture
- Technology Stack
- Core Features & Simulated Steps
- Getting Started
- Docker
- API Endpoints
- Configuration
- Project Structure
- How the Hybrid Model Works
- Security Considerations
- Contributing
- License
Quantum Key Distribution (QKD) is a method of secure communication that uses the principles of quantum mechanics to guarantee the security of cryptographic key exchange. Unlike classical key exchange algorithms (like RSA or Diffie-Hellman) whose security relies on computational assumptions (e.g., the difficulty of factoring large numbers), QKD's security is rooted in the fundamental laws of physics.
| Feature | Classical Key Exchange | Quantum Key Exchange |
|---|---|---|
| Security Basis | Computational hardness assumptions | Laws of quantum physics |
| Vulnerability to Quantum Computers | ✅ Inherently secure | |
| Eavesdropping Detection | ❌ Undetectable in principle | ✅ Detectable via disturbance |
| Information-Theoretic Security | ❌ No | ✅ Yes (provably secure) |
Key Insight: In quantum mechanics, the act of measuring a quantum state inevitably disturbs it. This means any eavesdropper (conventionally named "Eve") intercepting the quantum channel will introduce detectable errors, alerting the legitimate parties (Alice and Bob) to the intrusion.
The BB84 protocol (named after its inventors Bennett and Brassard, 1984) is the first and most well-known QKD protocol. Here's how it operates:
┌───────────┐ Quantum Channel (Photons) ┌───────────┐
│ │ ──────────────────────────────► │ │
│ ALICE │ │ BOB │
│ (Sender) │ ◄────────────────────────────── │ (Receiver)│
└───────────┘ Classical Channel (Bases) └───────────┘
│
┌─────┴─────┐
│ EVE │
│(Eavesdrop)│
└───────────┘
-
🎲 Preparation — Alice randomly generates a sequence of bits (
0or1) and for each bit randomly chooses one of two measurement bases: Rectilinear (+) or Diagonal (×). -
📡 Transmission — Alice encodes each bit as a polarized photon and sends it to Bob over the quantum channel.
-
🔍 Measurement — Bob independently and randomly chooses a basis for each received photon. If Bob's basis matches Alice's, he measures the correct bit. If not, the result is random.
-
🕵️ Eavesdropping (Eve) — If Eve intercepts a photon, she must guess Bob's basis. Wrong guesses introduce ~25% errors in the intercepted qubits — a detectable fingerprint.
-
📢 Sifting — Alice and Bob publicly compare their bases (not bits!) over a classical channel and discard all bits where their bases didn't match, forming the sifted key.
-
📊 QBER Check — They sacrifice a small random sample of the sifted key to estimate the Quantum Bit Error Rate (QBER). If QBER exceeds a threshold (typically ~11% for BB84 in theory, configurable to 5% in this simulator), the key is discarded — Eve has been detected!
-
🔧 Error Correction — Remaining errors (from channel noise) are corrected using classical error-correction techniques.
-
🔒 Privacy Amplification — The key is hashed/compressed to eliminate any partial information Eve might have gained, producing a shorter but perfectly secure key.
This project demonstrates a hybrid cryptographic architecture by combining quantum and classical encryption:
┌──────────────────────────────────────────────────────────┐
│ HYBRID QKD SYSTEM │
│ │
│ ┌────────────────────┐ ┌────────────────────────┐ │
│ │ QUANTUM LAYER │ │ CLASSICAL LAYER │ │
│ │ │ │ │ │
│ │ BB84 Protocol │──►│ AES-256 GCM │ │
│ │ (Key Generation) │ │ (Data Encryption) │ │
│ │ │ │ │ │
│ │ • Random Bits │ │ • Encrypt Message │ │
│ │ • Photon Encoding │ │ • Decrypt Message │ │
│ │ • Eavesdrop Sim │ │ • Self-Test Check │ │
│ │ • Sifting │ │ │ │
│ │ • QBER Check │ │ │ │
│ │ • Error Correction│ │ │ │
│ │ • Privacy Amplif. │ │ │ │
│ └────────────────────┘ └────────────────────────┘ │
│ │
│ ┌──────────────────────────────────────────────────┐ │
│ │ REST API (Spring Boot) │ │
│ │ GET /api/qkd/encrypt?message=... │ │
│ │ POST /api/qkd/decrypt { key, ciphertext } │ │
│ └──────────────────────────────────────────────────┘ │
└──────────────────────────────────────────────────────────┘
- Quantum Channel (Simulated): The
QkdEnginesimulates the BB84 protocol, generating a raw key using quantum mechanics principles (superposition and measurement). - Classical Post-Processing: Error Correction and Privacy Amplification refine the raw key into a usable, secure symmetric key.
- Hybrid Encryption: The QKD-derived key is used with AES-256 GCM for fast, authenticated symmetric encryption.
- Ephemeral Key Management: The key is returned to the client and never stored on the server — the server remains fully stateless.
The application follows a clean, layered Spring Boot architecture:
┌─────────────────────────────────────────────────────────────┐
│ API Layer │
│ QkdController.java │
│ (REST endpoints, request handling) │
├─────────────────────────────────────────────────────────────┤
│ Service Layer │
│ QkdService.java │
│ (Protocol orchestration, business logic) │
├──────────────────────┬──────────────────────────────────────┤
│ Core Layer │ Crypto Layer │
│ QkdEngine.java │ SymmetricCrypto.java │
│ (BB84 simulation) │ (AES-256 GCM operations) │
├──────────────────────┴──────────────────────────────────────┤
│ Model Layer │
│ Photon · SiftedKey · QBERCheckResult · KeyResult │
│ DecryptionRequest │
└─────────────────────────────────────────────────────────────┘
| Category | Technology |
|---|---|
| Language | Java 21+ |
| Framework | Spring Boot 3.5 |
| Build Tool | Maven |
| Key Generation Protocol | BB84 (Simulated) |
| Symmetric Encryption | AES-256 GCM (Java Cryptography Architecture) |
| Privacy Amplification | SHA-256 Hashing |
| Data Serialization | JSON (via Spring Web) |
| Containerization | Docker (OpenJDK base image) |
| CORS | Configured for local dev and production frontend |
The application implements all critical phases of a real-world QKD key exchange:
| # | Phase | Description |
|---|---|---|
| 1 | 🎲 Random Generation | Alice and Bob independently generate random bits and measurement bases using ThreadLocalRandom |
| 2 | 📡 Photon Encoding | Alice encodes her bits as polarized photons based on her chosen bases |
| 3 | 🕵️ Eavesdropping (Eve) | Configurable attack rate where Eve intercepts and re-transmits qubits, introducing detectable errors |
| 4 | 🔍 Measurement | Bob measures incoming photons using his randomly chosen bases |
| 5 | 📢 Sifting | Alice and Bob compare bases publicly and keep only matching-basis bits |
| 6 | 📊 QBER Check | A sample of the sifted key is compared — if error rate exceeds threshold (default: 5%), the key is discarded |
| 7 | 🔧 Error Correction | Simplified parity-check block verification to remove residual errors |
| 8 | 🔒 Privacy Amplification | SHA-256 hashing compresses the key into a uniform, secure 256-bit AES key |
| 9 | 🔐 AES-256 GCM Encryption | The derived key encrypts the message with authenticated encryption |
| 10 | ✅ Self-Test | Automatic encrypt→decrypt verification before returning results |
- Java Development Kit (JDK) 21 or newer
- Maven (or use the included Maven Wrapper
mvnw)
-
Clone the repository:
git clone https://github.com/sshekhar-04/QKD-simulation.git cd QKD-simulation/simulator -
Build the project:
# Using Maven Wrapper (recommended) ./mvnw clean package # Or using system Maven mvn clean package
-
Run the application:
java -jar target/QKD-simulation.jar
-
The API will start on:
http://localhost:8080
Build and run the application in a Docker container:
# Build the JAR first
cd simulator
./mvnw clean package
# Build the Docker image (from project root)
cd ..
docker build -t qkd-simulator .
# Run the container
docker run -p 8080:8080 qkd-simulatorRuns the full BB84 QKD protocol, derives an AES-256 key, encrypts the message, and returns both the key and the ciphertext.
| Property | Value |
|---|---|
| Endpoint | GET /api/qkd/encrypt |
| Query Param | message (String) — defaults to "Default secret message" |
Example Request:
curl "http://localhost:8080/api/qkd/encrypt?message=Launch_sequence_initiated"Example Response:
{
"status": "Successfully generated quantum key and encrypted message.",
"encryptionKey": "L0tN4eS15tJ3+q9uYh8pG/T+T/T/W3rWq9uYh8pG/T+T/T/W3rw==",
"ciphertext": "AAAAAAbW5jK7+KxW6xXW6xXW6xXW6xXW6xXW6xXW6xXW6xXW6xX..."
}
⚠️ Important: Save theencryptionKey— it is ephemeral and not stored on the server. You will need it for decryption.
Decrypts the ciphertext using the ephemeral key provided by the client.
| Property | Value |
|---|---|
| Endpoint | POST /api/qkd/decrypt |
| Content-Type | application/json |
Example Request:
curl -X POST http://localhost:8080/api/qkd/decrypt \
-H "Content-Type: application/json" \
-d '{
"encryptionKey": "L0tN4eS15tJ3+q9uYh8pG/T+T/T/W3rWq9uYh8pG/T+T/T/W3rw==",
"ciphertext": "AAAAAAbW5jK7+KxW6xXW6xXW6xXW6xXW6xXW6xXW6xXW6xXW6xX..."
}'Example Response:
{
"status": "Decryption successful.",
"keyProvided": "L0tN4eS15t...",
"plaintext": "Launch_sequence_initiated"
}| Scenario | HTTP Code | Response |
|---|---|---|
| QBER too high (Eve detected) | 500 |
{"error": "Key discarded due to high QBER: 0.23"} |
| Invalid key length | 400 |
{"error": "Key Error: Invalid key length. Must be 32 bytes."} |
| Decryption failure | 500 |
{"error": "Decryption failed: ..."} |
Tunable parameters can be set in application.properties or via environment variables:
| Property | Default | Description |
|---|---|---|
qkd.qubits.count |
2000 |
Number of qubits Alice generates per key exchange |
qkd.eve.attack.rate |
0.15 |
Probability (0.0–1.0) that Eve intercepts each qubit |
qkd.qber.threshold |
0.05 |
Maximum tolerable QBER before key is discarded |
Example application.properties:
spring.application.name=simulator
# QKD Configuration
qkd.qubits.count=2000
qkd.eve.attack.rate=0.15
qkd.qber.threshold=0.05💡 Tip: With
eveAttackRate = 0.15, the QBER will frequently exceed the threshold, causing intentional key rejection — this demonstrates the eavesdropping detection mechanism. Lower the attack rate (e.g.,0.0) for successful key exchanges.
QKD-simulation/
├── Dockerfile # Container configuration
├── README.md # This file
└── simulator/ # Spring Boot application
├── pom.xml # Maven dependencies
├── mvnw / mvnw.cmd # Maven Wrapper scripts
└── src/
├── main/
│ ├── java/com/qkd/simulator/simulator/
│ │ ├── SimulatorApplication.java # Spring Boot entry point
│ │ ├── api/
│ │ │ ├── QkdController.java # REST controller
│ │ │ └── DecryptionRequest.java # Request DTO
│ │ ├── service/
│ │ │ └── QkdService.java # Protocol orchestration
│ │ ├── core/
│ │ │ └── QkdEngine.java # BB84 simulation engine
│ │ ├── crypto/
│ │ │ └── SymmetricCrypto.java # AES-256 GCM operations
│ │ └── model/
│ │ ├── Photon.java # Qubit representation
│ │ ├── SiftedKey.java # Sifted key pair
│ │ ├── QBERCheckResult.java # QBER analysis result
│ │ └── KeyResult.java # Final key container
│ └── resources/
│ └── application.properties # Configuration
└── test/
└── java/.../SimulatorApplicationTests.java
The system implements a two-phase hybrid encryption strategy:
Phase 1: Quantum Key Generation (BB84) Phase 2: Classical Encryption (AES-256)
───────────────────────────────────── ─────────────────────────────────────────
Alice generates 2000 random qubits Plaintext Message
│ │
▼ ▼
Encode as polarized photons ┌──────────────────────────┐
│ │ AES-256 GCM Encryption │
▼ │ (using QKD-derived key) │
── Quantum Channel ── (Eve may intercept) └──────────────────────────┘
│ │
▼ ▼
Bob measures with random bases Ciphertext (Base64)
│ +
▼ Encryption Key (Base64)
Sifting → QBER Check → Error Correction │
│ ▼
▼ Returned to Client
Privacy Amplification (SHA-256 hash) (Server is stateless)
│
▼
256-bit AES Key ─────────────────────────────────────►
Why Hybrid?
- Quantum layer provides information-theoretically secure key generation immune to quantum computing attacks.
- Classical layer (AES-256 GCM) provides fast, authenticated symmetric encryption for the actual data.
- This mirrors how real-world QKD systems operate — quantum mechanics secures the key exchange, and proven classical algorithms handle bulk data encryption.
⚠️ Disclaimer: This is an educational simulator — it does not use actual quantum hardware or a real quantum optical channel.
| Aspect | Implementation | Notes |
|---|---|---|
| Key Generation | Simulated BB84 using ThreadLocalRandom |
Real QKD uses true quantum randomness via photon polarization |
| Eavesdropping Detection | QBER threshold check | Correctly models Eve's detectable interference |
| Encryption | AES-256 GCM (JCA) | Industry-standard authenticated encryption |
| Key Storage | Ephemeral — never stored server-side | Client must manage key lifecycle |
| IV Generation | Random 12-byte IV per encryption | java.util.Random — production should use SecureRandom |
| CORS | Whitelisted origins only | Configured for localhost:5173 and production frontend |
✅ Complete BB84 protocol lifecycle
✅ Eavesdropping detection through QBER analysis
✅ Classical post-processing (Error Correction + Privacy Amplification)
✅ Hybrid quantum-classical encryption architecture
✅ Stateless, ephemeral key management
✅ RESTful API design for quantum cryptography services
- No actual quantum hardware — randomness comes from classical PRNGs
- Simplified error correction (parity-based block elimination, not CASCADE/LDPC)
- No information reconciliation between Alice and Bob over classical channel
- Privacy amplification uses direct SHA-256 hash rather than universal hash families
Contributions are welcome! Here are some ideas for improvement:
- Implement a frontend visualization of the BB84 protocol steps
- Add the E91 or B92 QKD protocols for comparison
- Replace the simplified error correction with CASCADE or LDPC codes
- Use
SecureRandominstead ofThreadLocalRandomfor cryptographic safety - Add WebSocket support for real-time protocol step visualization
- Implement key rate calculation and channel capacity estimation
- Add unit tests for each protocol step
# Fork the repo, create a feature branch, and submit a PR
git checkout -b feature/your-feature-nameThis project is open source and available under the MIT License.
Built with ☕ Java, 🍃 Spring Boot, and ⚛️ Quantum Mechanics
If you found this project helpful, consider giving it a ⭐!