quantum_crypto/
quantum_crypto.rs

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