quantum_crypto/
quantum_crypto.rs

1#![allow(clippy::pedantic, clippy::unnecessary_wraps)]
2use quantrs2_ml::crypto::{ProtocolType, QuantumKeyDistribution, QuantumSignature, QSDC};
3use quantrs2_ml::prelude::*;
4use std::time::Instant;
5
6fn main() -> Result<()> {
7    println!("Quantum Cryptography Examples");
8    println!("============================");
9
10    // BB84 Quantum Key Distribution
11    run_bb84_example()?;
12
13    // E91 Protocol
14    run_e91_example()?;
15
16    // Quantum Digital Signatures
17    run_signature_example()?;
18
19    // Quantum Secure Direct Communication
20    run_qsdc_example()?;
21
22    // Quantum Blockchain Example
23    run_blockchain_example()?;
24
25    Ok(())
26}
27
28fn run_bb84_example() -> Result<()> {
29    println!("\nBB84 Quantum Key Distribution");
30    println!("----------------------------");
31
32    // Create BB84 QKD with 1000 qubits
33    let num_qubits = 1000;
34    println!("Creating BB84 protocol with {num_qubits} qubits");
35    let mut qkd = QuantumKeyDistribution::new(ProtocolType::BB84, num_qubits);
36
37    // Optional: set error rate
38    qkd = qkd.with_error_rate(0.03);
39    println!("Simulated error rate: {:.1}%", qkd.error_rate * 100.0);
40
41    // Distribute key
42    println!("Performing quantum key distribution...");
43    let start = Instant::now();
44    let key_length = qkd.distribute_key()?;
45    println!("Key distribution completed in {:.2?}", start.elapsed());
46    println!("Final key length: {key_length} bits");
47
48    // Verify keys match
49    println!("Verifying Alice and Bob have identical keys...");
50    if qkd.verify_keys() {
51        println!("✓ Key verification successful!");
52
53        // Display part of the key (first 8 bytes)
54        if let Some(key) = qkd.get_alice_key() {
55            println!("First 8 bytes of key: {:?}", &key[0..8.min(key.len())]);
56        }
57    } else {
58        println!("✗ Key verification failed!");
59    }
60
61    // Use the key for encryption
62    if let Some(key) = qkd.get_alice_key() {
63        let message = b"Hello, quantum world!";
64
65        println!(
66            "Encrypting message: '{}'",
67            std::str::from_utf8(message).unwrap()
68        );
69        let encrypted = quantrs2_ml::crypto::encrypt_with_qkd(message, key);
70
71        println!("Encrypted data: {:?}", &encrypted);
72
73        // Decrypt with Bob's key
74        if let Some(bob_key) = qkd.get_bob_key() {
75            let decrypted = quantrs2_ml::crypto::decrypt_with_qkd(&encrypted, bob_key);
76            println!(
77                "Decrypted message: '{}'",
78                std::str::from_utf8(&decrypted).unwrap()
79            );
80        }
81    }
82
83    Ok(())
84}
85
86fn run_e91_example() -> Result<()> {
87    println!("\nE91 Entanglement-Based Protocol");
88    println!("------------------------------");
89
90    // Create E91 QKD with 800 qubits
91    let num_qubits = 800;
92    println!("Creating E91 protocol with {num_qubits} qubits");
93    let mut qkd = QuantumKeyDistribution::new(ProtocolType::E91, num_qubits);
94
95    // Set error rate
96    qkd = qkd.with_error_rate(0.02);
97    println!("Simulated error rate: {:.1}%", qkd.error_rate * 100.0);
98
99    // Distribute key
100    println!("Performing quantum key distribution with entangled pairs...");
101    let start = Instant::now();
102    let key_length = qkd.distribute_key()?;
103    println!("Key distribution completed in {:.2?}", start.elapsed());
104    println!("Final key length: {key_length} bits");
105
106    // Verify keys match
107    println!("Verifying Alice and Bob have identical keys...");
108    if qkd.verify_keys() {
109        println!("✓ Key verification successful!");
110
111        // Display part of the key
112        if let Some(key) = qkd.get_alice_key() {
113            println!("First 8 bytes of key: {:?}", &key[0..8.min(key.len())]);
114        }
115    } else {
116        println!("✗ Key verification failed!");
117    }
118
119    Ok(())
120}
121
122fn run_signature_example() -> Result<()> {
123    println!("\nQuantum Digital Signatures");
124    println!("-------------------------");
125
126    // Create quantum signature with 256 qubits
127    let num_qubits = 256;
128    println!("Creating quantum signature scheme with {num_qubits} qubits");
129
130    // Choose a quantum-resistant algorithm
131    let algorithm = "Dilithium";
132    println!("Using algorithm: {algorithm}");
133
134    let signature = QuantumSignature::new(num_qubits, algorithm)?;
135    println!("Quantum signature scheme created");
136
137    // Sign a message
138    let message = b"This message is quantum-signed";
139    println!(
140        "Signing message: '{}'",
141        std::str::from_utf8(message).unwrap()
142    );
143
144    let start = Instant::now();
145    let sig = signature.sign(message)?;
146    println!("Signature generated in {:.2?}", start.elapsed());
147    println!("Signature size: {} bytes", sig.len());
148
149    // Verify signature
150    println!("Verifying signature...");
151    let start = Instant::now();
152    let is_valid = signature.verify(message, &sig)?;
153    println!("Verification completed in {:.2?}", start.elapsed());
154
155    if is_valid {
156        println!("✓ Signature verification successful!");
157    } else {
158        println!("✗ Signature verification failed!");
159    }
160
161    // Try with tampered message
162    let tampered = b"This message has been modified";
163    println!("Verifying signature with tampered message...");
164    let is_valid = signature.verify(tampered, &sig)?;
165
166    if is_valid {
167        println!("✗ Signature incorrectly verified on tampered message!");
168    } else {
169        println!("✓ Signature correctly rejected tampered message!");
170    }
171
172    Ok(())
173}
174
175fn run_qsdc_example() -> Result<()> {
176    println!("\nQuantum Secure Direct Communication");
177    println!("---------------------------------");
178
179    // Create QSDC protocol with 1000 qubits
180    let num_qubits = 1000;
181    println!("Creating QSDC protocol with {num_qubits} qubits");
182    let qsdc = QSDC::new(num_qubits);
183
184    // Transmit message directly
185    let message = b"This message is sent directly using quantum channel";
186    println!(
187        "Message to transmit: '{}'",
188        std::str::from_utf8(message).unwrap()
189    );
190
191    let start = Instant::now();
192    let received = qsdc.transmit_message(message)?;
193    println!("Transmission completed in {:.2?}", start.elapsed());
194
195    println!(
196        "Received message: '{}'",
197        std::str::from_utf8(&received).unwrap()
198    );
199
200    // Check for errors
201    let errors = message
202        .iter()
203        .zip(received.iter())
204        .filter(|(&a, &b)| a != b)
205        .count();
206
207    println!(
208        "Bit error rate: {:.2}%",
209        (errors as f64) / (message.len() as f64) * 100.0
210    );
211
212    Ok(())
213}
214
215fn run_blockchain_example() -> Result<()> {
216    println!("\nQuantum Blockchain Example");
217    println!("-------------------------");
218
219    use quantrs2_ml::blockchain::{ConsensusType, QuantumBlockchain, Transaction};
220
221    // Create a quantum blockchain
222    let difficulty = 2; // 2 leading zeros required for mining
223    println!("Creating quantum blockchain with difficulty {difficulty}");
224    let mut blockchain = QuantumBlockchain::new(ConsensusType::QuantumProofOfWork, difficulty);
225
226    // Create a transaction
227    let sender = vec![1, 2, 3, 4];
228    let recipient = vec![5, 6, 7, 8];
229    let amount = 100.0;
230
231    println!(
232        "Creating transaction: {} sends {} units to recipient",
233        sender.iter().map(|&b| b.to_string()).collect::<String>(),
234        amount
235    );
236
237    let transaction = Transaction::new(sender, recipient, amount, Vec::new());
238
239    // Add transaction
240    println!("Adding transaction to blockchain...");
241    blockchain.add_transaction(transaction)?;
242
243    // Mine a block
244    println!("Mining new block...");
245    let start = Instant::now();
246    let block = blockchain.mine_block()?;
247    println!("Block mined in {:.2?}", start.elapsed());
248
249    println!(
250        "Block hash: {:02x?}",
251        &block.hash[0..8.min(block.hash.len())]
252    );
253    println!("Blockchain length: {}", blockchain.chain.len());
254
255    // Verify blockchain
256    println!("Verifying blockchain integrity...");
257    let is_valid = blockchain.verify_chain()?;
258
259    if is_valid {
260        println!("✓ Blockchain verification successful!");
261    } else {
262        println!("✗ Blockchain verification failed!");
263    }
264
265    Ok(())
266}