Skip to content

Commit 2aaf98f

Browse files
committed
Fix CI errors: remove unused imports and fix type annotations
- Remove unused Zeroizing import from keymanagement.rs - Remove unused Mac import from keyderivation.rs - Prefix unused variable with underscore in tests - Add type annotations to fix array size mismatches in examples - Remove unnecessary to_string() and dereference in examples
1 parent 0706aa0 commit 2aaf98f

File tree

6 files changed

+113
-76
lines changed

6 files changed

+113
-76
lines changed

examples/file_encryption.rs

Lines changed: 42 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -28,24 +28,34 @@ Transaction History:
2828
println!(" ✓ Generated 256-bit encryption key");
2929

3030
// Encrypt the data
31-
let encrypted_data = encryption::encrypt(&encryption_key, financial_data)
32-
.expect("Encryption failed");
31+
let encrypted_data =
32+
encryption::encrypt(&encryption_key, financial_data).expect("Encryption failed");
3333

3434
println!(" ✓ Data encrypted with AES-256-GCM");
35-
println!(" Encrypted size: {} bytes", encrypted_data.ciphertext.len());
36-
println!(" Nonce (12 bytes): {}", hex::encode(&encrypted_data.nonce));
37-
println!(" First 32 bytes of ciphertext: {}...",
38-
hex::encode(&encrypted_data.ciphertext[..32.min(encrypted_data.ciphertext.len())]));
35+
println!(
36+
" Encrypted size: {} bytes",
37+
encrypted_data.ciphertext.len()
38+
);
39+
println!(
40+
" Nonce (12 bytes): {}",
41+
hex::encode(encrypted_data.nonce)
42+
);
43+
println!(
44+
" First 32 bytes of ciphertext: {}...",
45+
hex::encode(&encrypted_data.ciphertext[..32.min(encrypted_data.ciphertext.len())])
46+
);
3947

4048
// Decrypt the data
4149
println!("\n2. Decrypting Data with Correct Key");
42-
let decrypted_data = encryption::decrypt(&encryption_key, &encrypted_data)
43-
.expect("Decryption failed");
50+
let decrypted_data =
51+
encryption::decrypt(&encryption_key, &encrypted_data).expect("Decryption failed");
4452

4553
let decrypted_text = String::from_utf8(decrypted_data.clone()).unwrap();
4654
println!(" ✓ Decryption successful!");
47-
println!(" Decrypted data matches original: {}",
48-
decrypted_data == financial_data);
55+
println!(
56+
" Decrypted data matches original: {}",
57+
decrypted_data == financial_data
58+
);
4959
println!("\n Decrypted content:");
5060
println!("{}", decrypted_text);
5161

@@ -60,30 +70,40 @@ Transaction History:
6070
// Encrypt multiple files
6171
println!("\n4. Encrypting Multiple Financial Records");
6272

63-
let records = vec![
64-
("customer_001.txt", b"Customer: Alice Johnson, Account: ACC-001, Balance: $50,000"),
65-
("customer_002.txt", b"Customer: Bob Williams, Account: ACC-002, Balance: $75,250"),
66-
("customer_003.txt", b"Customer: Carol Davis, Account: ACC-003, Balance: $100,500"),
73+
let records: Vec<(&str, &[u8])> = vec![
74+
(
75+
"customer_001.txt",
76+
b"Customer: Alice Johnson, Account: ACC-001, Balance: $50,000",
77+
),
78+
(
79+
"customer_002.txt",
80+
b"Customer: Bob Williams, Account: ACC-002, Balance: $75,250",
81+
),
82+
(
83+
"customer_003.txt",
84+
b"Customer: Carol Davis, Account: ACC-003, Balance: $100,500",
85+
),
6786
];
6887

6988
let mut encrypted_records = Vec::new();
7089

7190
for (filename, data) in &records {
72-
let encrypted = encryption::encrypt(&encryption_key, data)
73-
.expect("Encryption failed");
91+
let encrypted = encryption::encrypt(&encryption_key, data).expect("Encryption failed");
7492
encrypted_records.push((filename, encrypted));
7593
println!(" ✓ Encrypted {}", filename);
7694
}
7795

7896
// Decrypt and verify all records
7997
println!("\n5. Decrypting All Records");
80-
for ((filename, original_data), (_, encrypted)) in records.iter().zip(encrypted_records.iter()) {
81-
let decrypted = encryption::decrypt(&encryption_key, encrypted)
82-
.expect("Decryption failed");
98+
for ((filename, original_data), (_, encrypted)) in records.iter().zip(encrypted_records.iter())
99+
{
100+
let decrypted = encryption::decrypt(&encryption_key, encrypted).expect("Decryption failed");
83101
let matches = &decrypted == original_data;
84-
println!(" {} - Decryption: {}",
85-
filename,
86-
if matches { "✓ Success" } else { "✗ Failed" });
102+
println!(
103+
" {} - Decryption: {}",
104+
filename,
105+
if matches { "✓ Success" } else { "✗ Failed" }
106+
);
87107
}
88108

89109
// Generate secure tokens

examples/password_hashing.rs

Lines changed: 26 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -13,8 +13,7 @@ fn main() {
1313
let user_password = SecurePassword::new(b"MySecurePassword123!".to_vec());
1414

1515
println!(" Hashing password with Argon2id...");
16-
let password_hash = password::hash_password(&user_password)
17-
.expect("Failed to hash password");
16+
let password_hash = password::hash_password(&user_password).expect("Failed to hash password");
1817

1918
println!(" Password hash: {}...", &password_hash[..50]);
2019
println!(" ✓ Hash stored in database\n");
@@ -44,7 +43,7 @@ fn main() {
4443
// Demonstrate multiple users with different passwords
4544
println!("4. Multiple User Accounts");
4645

47-
let users = vec![
46+
let users: Vec<(&str, &[u8])> = vec![
4847
("alice", b"AlicePass123!"),
4948
("bob", b"BobSecure456@"),
5049
("charlie", b"Charlie789#Pwd"),
@@ -65,19 +64,40 @@ fn main() {
6564
let alice_pwd = SecurePassword::new(b"AlicePass123!".to_vec());
6665
let (_, alice_hash) = &hashes[0];
6766
let is_valid = password::verify_password(&alice_pwd, alice_hash).unwrap();
68-
println!(" Alice authentication: {}", if is_valid { "✓ Success" } else { "✗ Failed" });
67+
println!(
68+
" Alice authentication: {}",
69+
if is_valid {
70+
"✓ Success"
71+
} else {
72+
"✗ Failed"
73+
}
74+
);
6975

7076
// Try to authenticate Bob with wrong password
7177
let wrong_bob_pwd = SecurePassword::new(b"WrongPassword".to_vec());
7278
let (_, bob_hash) = &hashes[1];
7379
let is_valid = password::verify_password(&wrong_bob_pwd, bob_hash).unwrap();
74-
println!(" Bob authentication (wrong pwd): {}", if is_valid { "✓ Success" } else { "✗ Failed" });
80+
println!(
81+
" Bob authentication (wrong pwd): {}",
82+
if is_valid {
83+
"✓ Success"
84+
} else {
85+
"✗ Failed"
86+
}
87+
);
7588

7689
// Authenticate Charlie correctly
7790
let charlie_pwd = SecurePassword::new(b"Charlie789#Pwd".to_vec());
7891
let (_, charlie_hash) = &hashes[2];
7992
let is_valid = password::verify_password(&charlie_pwd, charlie_hash).unwrap();
80-
println!(" Charlie authentication: {}", if is_valid { "✓ Success" } else { "✗ Failed" });
93+
println!(
94+
" Charlie authentication: {}",
95+
if is_valid {
96+
"✓ Success"
97+
} else {
98+
"✗ Failed"
99+
}
100+
);
81101

82102
println!("\n=== Security Features ===");
83103
println!("✓ Argon2id algorithm (resistant to GPU attacks)");

src/keyderivation.rs

Lines changed: 9 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
//! Key derivation functions (PBKDF2, HKDF)
22
3-
use hmac::{Hmac, Mac};
3+
use hmac::Hmac;
44
use sha2::{Sha256, Sha512};
55
use zeroize::{Zeroize, ZeroizeOnDrop};
66

@@ -93,8 +93,7 @@ impl Hkdf {
9393

9494
let hk = HkdfImpl::<Sha256>::new(Some(salt), input_key_material);
9595
let mut okm = vec![0u8; output_length];
96-
hk.expand(info, &mut okm)
97-
.expect("HKDF expand failed");
96+
hk.expand(info, &mut okm).expect("HKDF expand failed");
9897

9998
DerivedKey::from_bytes(okm)
10099
}
@@ -160,10 +159,13 @@ impl PasswordStrength {
160159

161160
// Common password check (basic)
162161
let common_passwords = [
163-
"password", "123456", "qwerty", "admin", "letmein", "welcome",
164-
"monkey", "dragon", "master", "sunshine", "princess", "football"
162+
"password", "123456", "qwerty", "admin", "letmein", "welcome", "monkey", "dragon",
163+
"master", "sunshine", "princess", "football",
165164
];
166-
if common_passwords.iter().any(|&common| password.to_lowercase().contains(common)) {
165+
if common_passwords
166+
.iter()
167+
.any(|&common| password.to_lowercase().contains(common))
168+
{
167169
score = score.saturating_sub(2);
168170
feedback.push("Avoid common passwords".to_string());
169171
}
@@ -276,7 +278,7 @@ mod tests {
276278

277279
#[test]
278280
fn test_password_strength_sequential() {
279-
let (score, feedback) = PasswordStrength::check("abc123xyz");
281+
let (_score, feedback) = PasswordStrength::check("abc123xyz");
280282
assert!(feedback.iter().any(|f| f.contains("sequential")));
281283
}
282284

src/keymanagement.rs

Lines changed: 7 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,6 @@ use crate::{CryptoError, SecureKey};
44
use serde::{Deserialize, Serialize};
55
use std::collections::HashMap;
66
use std::time::{SystemTime, UNIX_EPOCH};
7-
use zeroize::Zeroizing;
87

98
/// Key metadata
109
#[derive(Debug, Clone, Serialize, Deserialize)]
@@ -99,9 +98,7 @@ impl KeyStore {
9998

10099
/// Retrieve a key (returns clone of metadata but reference to key)
101100
pub fn get_key(&self, key_id: &str) -> Option<(&SecureKey, KeyMetadata)> {
102-
self.keys
103-
.get(key_id)
104-
.map(|(key, meta)| (key, meta.clone()))
101+
self.keys.get(key_id).map(|(key, meta)| (key, meta.clone()))
105102
}
106103

107104
/// Remove a key
@@ -137,15 +134,16 @@ impl KeyStore {
137134

138135
/// Rotate a key (generate new key, increment rotation counter)
139136
pub fn rotate_key(&mut self, key_id: &str) -> Result<(), CryptoError> {
140-
if let Some((_, meta)) = self.keys.get_mut(key_id) {
137+
if let Some((_, meta)) = self.keys.get(key_id) {
141138
let new_key = SecureKey::generate();
142-
meta.rotation_count += 1;
143-
meta.created_at = SystemTime::now()
139+
let mut new_meta = meta.clone();
140+
new_meta.rotation_count += 1;
141+
new_meta.created_at = SystemTime::now()
144142
.duration_since(UNIX_EPOCH)
145143
.unwrap()
146144
.as_secs();
147145

148-
self.keys.insert(key_id.to_string(), (new_key, meta.clone()));
146+
self.keys.insert(key_id.to_string(), (new_key, new_meta));
149147
Ok(())
150148
} else {
151149
Err(CryptoError::HashingError("Key not found".to_string()))
@@ -307,11 +305,7 @@ mod tests {
307305
)
308306
.with_expiration(1);
309307
store
310-
.store_key(
311-
"expired".to_string(),
312-
SecureKey::generate(),
313-
meta_expired,
314-
)
308+
.store_key("expired".to_string(), SecureKey::generate(), meta_expired)
315309
.unwrap();
316310

317311
// Add non-expired key

src/lib.rs

Lines changed: 20 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -18,22 +18,22 @@
1818
//! 2024 CISA/FBI guidance for memory-safe cryptographic implementations.
1919
2020
pub mod keyderivation;
21-
pub mod signatures;
2221
pub mod keymanagement;
22+
pub mod signatures;
2323

24-
pub use keyderivation::{DerivedKey, Hkdf, Pbkdf2, PasswordStrength};
25-
pub use signatures::{Ed25519KeyPair, Ed25519PublicKey, HmacKey, SignatureSuite};
24+
pub use keyderivation::{DerivedKey, Hkdf, PasswordStrength, Pbkdf2};
2625
pub use keymanagement::{KeyMetadata, KeyStore, RotationPolicy};
26+
pub use signatures::{Ed25519KeyPair, Ed25519PublicKey, HmacKey, SignatureSuite};
2727

2828
use aes_gcm::{
2929
aead::{Aead, KeyInit, OsRng},
3030
Aes256Gcm, Nonce,
3131
};
3232
use argon2::{
3333
password_hash::{PasswordHash, PasswordHasher, PasswordVerifier, SaltString},
34-
Argon2, Algorithm, Version, Params,
34+
Algorithm, Argon2, Params, Version,
3535
};
36-
use hmac::{Hmac, Mac};
36+
use hmac::Hmac;
3737
use rand::RngCore;
3838
use sha2::Sha256;
3939
use thiserror::Error;
@@ -272,10 +272,7 @@ pub mod encryption {
272272
}
273273

274274
/// Decrypt data using AES-256-GCM
275-
pub fn decrypt(
276-
key: &SecureKey,
277-
encrypted: &EncryptedData,
278-
) -> Result<Vec<u8>, CryptoError> {
275+
pub fn decrypt(key: &SecureKey, encrypted: &EncryptedData) -> Result<Vec<u8>, CryptoError> {
279276
let cipher = Aes256Gcm::new_from_slice(key.as_bytes())
280277
.map_err(|e| CryptoError::DecryptionError(e.to_string()))?;
281278

@@ -313,12 +310,13 @@ pub mod random {
313310
}
314311

315312
/// HMAC-SHA256 utilities for message authentication
316-
pub mod hmac {
313+
pub mod hmac_ops {
317314
use super::*;
315+
use hmac::Mac;
318316

319317
/// Compute HMAC-SHA256 for a message
320318
pub fn compute_hmac(key: &SecureKey, message: &[u8]) -> Result<Vec<u8>, CryptoError> {
321-
let mut mac = HmacSha256::new_from_slice(key.as_bytes())
319+
let mut mac = <HmacSha256 as Mac>::new_from_slice(key.as_bytes())
322320
.map_err(|e| CryptoError::HmacError(e.to_string()))?;
323321

324322
mac.update(message);
@@ -331,7 +329,7 @@ pub mod hmac {
331329
message: &[u8],
332330
expected_hmac: &[u8],
333331
) -> Result<bool, CryptoError> {
334-
let mut mac = HmacSha256::new_from_slice(key.as_bytes())
332+
let mut mac = <HmacSha256 as Mac>::new_from_slice(key.as_bytes())
335333
.map_err(|e| CryptoError::HmacError(e.to_string()))?;
336334

337335
mac.update(message);
@@ -482,19 +480,19 @@ mod tests {
482480
let key = SecureKey::generate();
483481
let message = b"Important financial transaction data";
484482

485-
let hmac_result = hmac::compute_hmac(&key, message).unwrap();
483+
let hmac_result = hmac_ops::compute_hmac(&key, message).unwrap();
486484
assert_eq!(hmac_result.len(), 32); // SHA-256 produces 32 bytes
487485

488486
// Verify correct HMAC
489-
assert!(hmac::verify_hmac(&key, message, &hmac_result).unwrap());
487+
assert!(hmac_ops::verify_hmac(&key, message, &hmac_result).unwrap());
490488

491489
// Verify fails with wrong key
492490
let wrong_key = SecureKey::generate();
493-
assert!(!hmac::verify_hmac(&wrong_key, message, &hmac_result).unwrap());
491+
assert!(!hmac_ops::verify_hmac(&wrong_key, message, &hmac_result).unwrap());
494492

495493
// Verify fails with modified message
496494
let modified_message = b"Modified transaction data";
497-
assert!(!hmac::verify_hmac(&key, modified_message, &hmac_result).unwrap());
495+
assert!(!hmac_ops::verify_hmac(&key, modified_message, &hmac_result).unwrap());
498496
}
499497

500498
#[test]
@@ -549,19 +547,19 @@ mod tests {
549547
let message1 = b"Message 1";
550548
let message2 = b"Message 2";
551549

552-
let hmac1 = hmac::compute_hmac(&key, message1).unwrap();
553-
let hmac2 = hmac::compute_hmac(&key, message2).unwrap();
550+
let hmac1 = hmac_ops::compute_hmac(&key, message1).unwrap();
551+
let hmac2 = hmac_ops::compute_hmac(&key, message2).unwrap();
554552

555553
// Different messages should produce different HMACs
556554
assert_ne!(hmac1, hmac2);
557555

558556
// Each HMAC should verify against its own message
559-
assert!(hmac::verify_hmac(&key, message1, &hmac1).unwrap());
560-
assert!(hmac::verify_hmac(&key, message2, &hmac2).unwrap());
557+
assert!(hmac_ops::verify_hmac(&key, message1, &hmac1).unwrap());
558+
assert!(hmac_ops::verify_hmac(&key, message2, &hmac2).unwrap());
561559

562560
// HMACs should not cross-verify
563-
assert!(!hmac::verify_hmac(&key, message1, &hmac2).unwrap());
564-
assert!(!hmac::verify_hmac(&key, message2, &hmac1).unwrap());
561+
assert!(!hmac_ops::verify_hmac(&key, message1, &hmac2).unwrap());
562+
assert!(!hmac_ops::verify_hmac(&key, message2, &hmac1).unwrap());
565563
}
566564

567565
#[test]

0 commit comments

Comments
 (0)