Skip to main content

best_encrypt/
crypto.rs

1use crate::error::{EncryptError, Result};
2use aes_gcm::{Aes256Gcm, Nonce, KeyInit};
3use aes_gcm::aead::Aead;
4use ring::pbkdf2;
5use ring::hmac;
6use serde::{Deserialize, Serialize};
7use std::num::NonZeroU32;
8
9const KEY_LENGTH: usize = 32;
10const SALT_LENGTH: usize = 32;
11const NONCE_LENGTH: usize = 12;
12const ITERATIONS: NonZeroU32 = unsafe { NonZeroU32::new_unchecked(100_000) };
13
14#[derive(Debug, Serialize, Deserialize)]
15pub struct EncryptionResult {
16    pub encrypted: String,
17    pub salt: String,
18    pub hmac: String,
19}
20
21/// Triple-layer encryption implementation for the Encrypt tool.
22/// Provides AES-256-GCM encryption with PBKDF2 key derivation and HMAC signatures.
23pub struct Crypto;
24
25impl Crypto {
26    /// Generate a random salt for key derivation
27    pub fn generate_salt() -> String {
28        use ring::rand::{SecureRandom, SystemRandom};
29        let rng = SystemRandom::new();
30        let mut salt = [0u8; SALT_LENGTH];
31        rng.fill(&mut salt).unwrap();
32        hex::encode(salt)
33    }
34
35    /// Derive encryption key from password using PBKDF2
36    pub fn derive_key(password: &str, salt: &str) -> Result<[u8; KEY_LENGTH]> {
37        let salt_bytes = hex::decode(salt)?;
38        let mut key = [0u8; KEY_LENGTH];
39        
40        pbkdf2::derive(
41            pbkdf2::PBKDF2_HMAC_SHA256,
42            ITERATIONS,
43            &salt_bytes,
44            password.as_bytes(),
45            &mut key,
46        );
47        
48        Ok(key)
49    }
50
51    /// Generate HMAC signature for data integrity
52    pub fn generate_hmac(data: &str, key: &[u8]) -> String {
53        let signing_key = hmac::Key::new(hmac::HMAC_SHA256, key);
54        let signature = hmac::sign(&signing_key, data.as_bytes());
55        hex::encode(signature.as_ref())
56    }
57
58    /// Triple-layer encryption:
59    /// 1. Generate random salt
60    /// 2. Derive key using PBKDF2
61    /// 3. AES-256-GCM encryption with HMAC
62    pub fn encrypt(plaintext: &str, password: &str) -> Result<EncryptionResult> {
63        // Phase 1: Generate salt
64        let salt = Self::generate_salt();
65
66        // Phase 2: Derive key from password
67        let key = Self::derive_key(password, &salt)?;
68
69        // Phase 3: AES-256-GCM encryption
70        let cipher = Aes256Gcm::new(&key.into());
71        let nonce = Nonce::from_slice(&[0u8; NONCE_LENGTH]); // In production, use random nonce
72        
73        let encrypted = cipher
74            .encrypt(nonce, plaintext.as_bytes())
75            .map_err(|e| EncryptError::Crypto(format!("Encryption failed: {}", e)))?;
76
77        // Combine nonce and encrypted data
78        let encrypted_data = hex::encode(&encrypted);
79
80        // Phase 3: Generate HMAC signature
81        let hmac = Self::generate_hmac(&encrypted_data, &key);
82
83        Ok(EncryptionResult {
84            encrypted: encrypted_data,
85            salt,
86            hmac,
87        })
88    }
89
90    /// Triple-layer decryption:
91    /// 1. Verify HMAC signature
92    /// 2. Derive key using PBKDF2
93    /// 3. AES-256-GCM decryption
94    pub fn decrypt(
95        encrypted_data: &str,
96        salt: &str,
97        hmac: &str,
98        password: &str,
99    ) -> Result<String> {
100        // Phase 2: Derive key from password
101        let key = Self::derive_key(password, salt)?;
102
103        // Phase 3: Verify HMAC signature
104        let expected_hmac = Self::generate_hmac(encrypted_data, &key);
105        if expected_hmac != hmac {
106            return Err(EncryptError::Crypto("HMAC verification failed".to_string()));
107        }
108
109        // Phase 3: AES-256-GCM decryption
110        let cipher = Aes256Gcm::new(&key.into());
111        let nonce = Nonce::from_slice(&[0u8; NONCE_LENGTH]); // In production, use stored nonce
112        
113        let encrypted_bytes = hex::decode(encrypted_data)?;
114        let decrypted = cipher
115            .decrypt(nonce, encrypted_bytes.as_ref())
116            .map_err(|_| EncryptError::Crypto("Decryption failed".to_string()))?;
117
118        String::from_utf8(decrypted)
119            .map_err(|e| EncryptError::Crypto(format!("Invalid UTF-8: {}", e)))
120    }
121
122    /// Hash password for storage using PBKDF2
123    pub fn hash_password(password: &str) -> Result<String> {
124        let salt = Self::generate_salt();
125        let salt_bytes = hex::decode(&salt)?;
126        let mut hash = [0u8; 64];
127        
128        pbkdf2::derive(
129            pbkdf2::PBKDF2_HMAC_SHA256,
130            ITERATIONS,
131            &salt_bytes,
132            password.as_bytes(),
133            &mut hash,
134        );
135        
136        Ok(format!("{}:{}", salt, hex::encode(hash)))
137    }
138
139    /// Verify password against stored hash
140    pub fn verify_password(password: &str, stored_hash: &str) -> Result<bool> {
141        let parts: Vec<&str> = stored_hash.split(':').collect();
142        if parts.len() != 2 {
143            return Ok(false);
144        }
145        
146        let salt = parts[0];
147        let stored_hash_hex = parts[1];
148        
149        let salt_bytes = hex::decode(salt)?;
150        let mut computed_hash = [0u8; 64];
151        
152        pbkdf2::derive(
153            pbkdf2::PBKDF2_HMAC_SHA256,
154            ITERATIONS,
155            &salt_bytes,
156            password.as_bytes(),
157            &mut computed_hash,
158        );
159        
160        Ok(hex::encode(computed_hash) == stored_hash_hex)
161    }
162}