quantum_crypto/
quantum_crypto.rs

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