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
21pub struct Crypto;
24
25impl Crypto {
26 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 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 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 pub fn encrypt(plaintext: &str, password: &str) -> Result<EncryptionResult> {
63 let salt = Self::generate_salt();
65
66 let key = Self::derive_key(password, &salt)?;
68
69 let cipher = Aes256Gcm::new(&key.into());
71 let nonce = Nonce::from_slice(&[0u8; NONCE_LENGTH]); let encrypted = cipher
74 .encrypt(nonce, plaintext.as_bytes())
75 .map_err(|e| EncryptError::Crypto(format!("Encryption failed: {}", e)))?;
76
77 let encrypted_data = hex::encode(&encrypted);
79
80 let hmac = Self::generate_hmac(&encrypted_data, &key);
82
83 Ok(EncryptionResult {
84 encrypted: encrypted_data,
85 salt,
86 hmac,
87 })
88 }
89
90 pub fn decrypt(
95 encrypted_data: &str,
96 salt: &str,
97 hmac: &str,
98 password: &str,
99 ) -> Result<String> {
100 let key = Self::derive_key(password, salt)?;
102
103 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 let cipher = Aes256Gcm::new(&key.into());
111 let nonce = Nonce::from_slice(&[0u8; NONCE_LENGTH]); 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 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 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}