cargocrypt 0.2.2

Zero-config cryptographic operations for Rust projects
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
//! Comprehensive cryptographic benchmarks for CargoCrypt
//! 
//! This benchmark suite tests the performance of ChaCha20-Poly1305 encryption
//! and Argon2 key derivation across different performance profiles and data sizes.

use criterion::{
    black_box, criterion_group, criterion_main, BenchmarkId, Criterion, Throughput,
};
use cargocrypt::crypto::{
    CryptoEngine, PerformanceProfile, EncryptionOptions, PlaintextSecret,
    SecretMetadata, SecretType, DerivedKey, defaults,
};

/// Generate test data of specified size
fn generate_test_data(size: usize) -> Vec<u8> {
    (0..size).map(|i| (i % 256) as u8).collect()
}

/// Benchmark key derivation with different performance profiles
fn bench_key_derivation(c: &mut Criterion) {
    let mut group = c.benchmark_group("key_derivation");
    
    let password = "benchmark_password_with_sufficient_entropy_12345";
    let salt = [42u8; defaults::SALT_LENGTH];
    
    let profiles = [
        ("fast", PerformanceProfile::Fast),
        ("balanced", PerformanceProfile::Balanced),
        ("secure", PerformanceProfile::Secure),
        ("paranoid", PerformanceProfile::Paranoid),
    ];

    for (name, profile) in profiles {
        group.bench_with_input(
            BenchmarkId::new("argon2", name),
            &profile,
            |b, &profile| {
                b.iter(|| {
                    let engine = CryptoEngine::with_performance_profile(profile);
                    // Use internal method through public API
                    let options = EncryptionOptions::new()
                        .with_performance_profile(profile)
                        .with_salt(salt);
                    
                    let plaintext = PlaintextSecret::from_string("test".to_string());
                    black_box(engine.encrypt(plaintext, password, options).unwrap());
                })
            },
        );
    }
    
    group.finish();
}

/// Benchmark encryption/decryption with different data sizes
fn bench_encryption_sizes(c: &mut Criterion) {
    let mut group = c.benchmark_group("encryption_by_size");
    
    let engine = CryptoEngine::new();
    let password = "benchmark_password";
    
    let sizes = [
        ("1KB", 1024),
        ("10KB", 10 * 1024),
        ("100KB", 100 * 1024),
        ("1MB", 1024 * 1024),
        ("10MB", 10 * 1024 * 1024),
    ];

    for (name, size) in sizes {
        let data = generate_test_data(size);
        group.throughput(Throughput::Bytes(size as u64));
        
        // Benchmark encryption
        group.bench_with_input(
            BenchmarkId::new("encrypt", name),
            &data,
            |b, data| {
                b.iter(|| {
                    let options = EncryptionOptions::new();
                    black_box(engine.encrypt_bytes(data, password, options).unwrap());
                })
            },
        );
        
        // Pre-encrypt for decryption benchmark
        let encrypted = engine.encrypt_bytes(&data, password, EncryptionOptions::new()).unwrap();
        
        // Benchmark decryption
        group.bench_with_input(
            BenchmarkId::new("decrypt", name),
            &encrypted,
            |b, encrypted| {
                b.iter(|| {
                    black_box(engine.decrypt(encrypted, password).unwrap());
                })
            },
        );
    }
    
    group.finish();
}

/// Benchmark direct ChaCha20-Poly1305 operations (without key derivation)
fn bench_direct_crypto(c: &mut Criterion) {
    let mut group = c.benchmark_group("direct_crypto");
    
    let engine = CryptoEngine::new();
    let key = CryptoEngine::generate_key().unwrap();
    let nonce = CryptoEngine::generate_nonce().unwrap();
    
    let sizes = [
        ("1KB", 1024),
        ("10KB", 10 * 1024),
        ("100KB", 100 * 1024),
        ("1MB", 1024 * 1024),
    ];

    for (name, size) in sizes {
        let data = generate_test_data(size);
        group.throughput(Throughput::Bytes(size as u64));
        
        // Benchmark direct encryption
        group.bench_with_input(
            BenchmarkId::new("direct_encrypt", name),
            &data,
            |b, data| {
                b.iter(|| {
                    black_box(engine.encrypt_direct(data, &key, &nonce).unwrap());
                })
            },
        );
        
        // Pre-encrypt for decryption benchmark
        let ciphertext = engine.encrypt_direct(&data, &key, &nonce).unwrap();
        
        // Benchmark direct decryption
        group.bench_with_input(
            BenchmarkId::new("direct_decrypt", name),
            &ciphertext,
            |b, ciphertext| {
                b.iter(|| {
                    black_box(engine.decrypt_direct(ciphertext, &key, &nonce).unwrap());
                })
            },
        );
    }
    
    group.finish();
}

/// Benchmark batch operations
fn bench_batch_operations(c: &mut Criterion) {
    let mut group = c.benchmark_group("batch_operations");
    
    let engine = CryptoEngine::new();
    let password = "batch_password";
    
    let batch_sizes = [1, 10, 50, 100, 500];
    
    for &count in &batch_sizes {
        let secrets: Vec<(String, String)> = (0..count)
            .map(|i| (format!("secret_{}", i), format!("secret_data_{}_with_some_content", i)))
            .collect();
        
        group.bench_with_input(
            BenchmarkId::new("encrypt_batch", count),
            &secrets,
            |b, secrets| {
                b.iter(|| {
                    let options = EncryptionOptions::new();
                    black_box(engine.encrypt_batch(secrets.clone(), password, options));
                })
            },
        );
    }
    
    group.finish();
}

/// Benchmark password operations
fn bench_password_operations(c: &mut Criterion) {
    let mut group = c.benchmark_group("password_operations");
    
    let engine = CryptoEngine::new();
    let plaintext = "Test secret data for password operations";
    let password = "original_password";
    let new_password = "new_password";
    
    // Pre-encrypt secret for benchmarks
    let encrypted = engine.encrypt_string(plaintext, password, EncryptionOptions::new()).unwrap();
    
    // Benchmark password verification
    group.bench_function("verify_correct_password", |b| {
        b.iter(|| {
            black_box(engine.verify_password(&encrypted, password));
        })
    });
    
    group.bench_function("verify_wrong_password", |b| {
        b.iter(|| {
            black_box(engine.verify_password(&encrypted, "wrong_password"));
        })
    });
    
    // Benchmark password change
    group.bench_function("change_password", |b| {
        b.iter(|| {
            black_box(engine.change_password(&encrypted, password, new_password).unwrap());
        })
    });
    
    group.finish();
}

/// Benchmark serialization operations
fn bench_serialization(c: &mut Criterion) {
    let mut group = c.benchmark_group("serialization");
    
    let engine = CryptoEngine::new();
    let plaintext = "Test data for serialization benchmarks";
    let password = "serialization_password";
    
    let metadata = SecretMetadata::new()
        .with_description("Benchmark secret")
        .with_type(SecretType::ApiKey);
    
    let options = EncryptionOptions::new().with_metadata(metadata);
    let encrypted = engine.encrypt_string(plaintext, password, options).unwrap();
    
    // Benchmark JSON serialization
    group.bench_function("to_json", |b| {
        b.iter(|| {
            black_box(encrypted.to_json().unwrap());
        })
    });
    
    let json = encrypted.to_json().unwrap();
    group.bench_function("from_json", |b| {
        b.iter(|| {
            black_box(cargocrypt::crypto::EncryptedSecret::from_json(&json).unwrap());
        })
    });
    
    // Benchmark binary serialization
    group.bench_function("to_bytes", |b| {
        b.iter(|| {
            black_box(encrypted.to_bytes().unwrap());
        })
    });
    
    let bytes = encrypted.to_bytes().unwrap();
    group.bench_function("from_bytes", |b| {
        b.iter(|| {
            black_box(cargocrypt::crypto::EncryptedSecret::from_bytes(&bytes).unwrap());
        })
    });
    
    group.finish();
}

/// Benchmark memory-intensive operations to test zeroization overhead
fn bench_memory_operations(c: &mut Criterion) {
    let mut group = c.benchmark_group("memory_operations");
    
    let engine = CryptoEngine::new();
    let password = "memory_test_password";
    
    // Test with large data to see zeroization impact
    let large_data = generate_test_data(1024 * 1024); // 1MB
    
    group.bench_function("large_data_encrypt", |b| {
        b.iter(|| {
            let options = EncryptionOptions::new();
            black_box(engine.encrypt_bytes(&large_data, password, options).unwrap());
        })
    });
    
    let encrypted_large = engine.encrypt_bytes(&large_data, password, EncryptionOptions::new()).unwrap();
    
    group.bench_function("large_data_decrypt", |b| {
        b.iter(|| {
            black_box(engine.decrypt(&encrypted_large, password).unwrap());
        })
    });
    
    // Test many small operations (to test allocation patterns)
    group.bench_function("many_small_encryptions", |b| {
        b.iter(|| {
            for i in 0..100 {
                let data = format!("small_secret_{}", i);
                let options = EncryptionOptions::new();
                black_box(engine.encrypt_string(&data, password, options).unwrap());
            }
        })
    });
    
    group.finish();
}

/// Benchmark concurrent operations
fn bench_concurrent_operations(c: &mut Criterion) {
    let mut group = c.benchmark_group("concurrent_operations");
    
    let engine = CryptoEngine::new();
    let password = "concurrent_password";
    let data = "Concurrent test data";
    
    // Pre-encrypt for concurrent decryption test
    let encrypted = engine.encrypt_string(data, password, EncryptionOptions::new()).unwrap();
    
    group.bench_function("concurrent_encryptions", |b| {
        b.iter(|| {
            use std::thread;
            let handles: Vec<_> = (0..4).map(|_| {
                let engine = engine.clone();
                let data = data.to_string();
                let password = password.to_string();
                thread::spawn(move || {
                    let options = EncryptionOptions::new();
                    engine.encrypt_string(&data, &password, options).unwrap()
                })
            }).collect();
            
            for handle in handles {
                black_box(handle.join().unwrap());
            }
        })
    });
    
    group.bench_function("concurrent_decryptions", |b| {
        b.iter(|| {
            use std::thread;
            let handles: Vec<_> = (0..4).map(|_| {
                let engine = engine.clone();
                let encrypted = encrypted.clone();
                let password = password.to_string();
                thread::spawn(move || {
                    engine.decrypt_to_string(&encrypted, &password).unwrap()
                })
            }).collect();
            
            for handle in handles {
                black_box(handle.join().unwrap());
            }
        })
    });
    
    group.finish();
}

/// Performance regression tests
fn bench_performance_targets(c: &mut Criterion) {
    let mut group = c.benchmark_group("performance_targets");
    group.significance_level(0.1).sample_size(100);
    
    let engine = CryptoEngine::new();
    let password = "target_password";
    let test_data = "Performance target test data";
    
    // Target: <1ms for encryption/decryption of small data
    group.bench_function("target_encrypt_small", |b| {
        b.iter(|| {
            let options = EncryptionOptions::new();
            black_box(engine.encrypt_string(test_data, password, options).unwrap());
        })
    });
    
    let encrypted = engine.encrypt_string(test_data, password, EncryptionOptions::new()).unwrap();
    
    group.bench_function("target_decrypt_small", |b| {
        b.iter(|| {
            black_box(engine.decrypt_to_string(&encrypted, password).unwrap());
        })
    });
    
    // Target: High throughput for large data
    let large_data = generate_test_data(10 * 1024 * 1024); // 10MB
    group.throughput(Throughput::Bytes(large_data.len() as u64));
    
    group.bench_function("target_encrypt_large", |b| {
        b.iter(|| {
            let options = EncryptionOptions::new();
            black_box(engine.encrypt_bytes(&large_data, password, options).unwrap());
        })
    });
    
    let encrypted_large = engine.encrypt_bytes(&large_data, password, EncryptionOptions::new()).unwrap();
    
    group.bench_function("target_decrypt_large", |b| {
        b.iter(|| {
            black_box(engine.decrypt(&encrypted_large, password).unwrap());
        })
    });
    
    group.finish();
}

criterion_group!(
    benches,
    bench_key_derivation,
    bench_encryption_sizes,
    bench_direct_crypto,
    bench_batch_operations,
    bench_password_operations,
    bench_serialization,
    bench_memory_operations,
    bench_concurrent_operations,
    bench_performance_targets,
);

criterion_main!(benches);