use aes_gcm::aead::generic_array::GenericArray; use aes_gcm::aead::{Aead, NewAead}; use aes_gcm::Aes256Gcm; use anyhow::{anyhow, Result}; use hmac::Hmac; use pbkdf2::pbkdf2; use rand::RngCore; use sha2::Sha256; use std::fs; use std::path::Path; const NONCE_LEN: usize = 12; const SALT_LEN: usize = 16; pub struct VaultKey { cipher: Aes256Gcm, } impl VaultKey { pub fn derive_from_passphrase(passphrase: &str, salt_path: &Path) -> Result { let salt = if salt_path.exists() { fs::read(salt_path)? } else { let mut salt = [0u8; SALT_LEN]; rand::thread_rng().fill_bytes(&mut salt); if let Some(parent) = salt_path.parent() { fs::create_dir_all(parent)?; } fs::write(salt_path, &salt)?; salt.to_vec() }; let mut key = [0u8; 32]; pbkdf2::>(passphrase.as_bytes(), &salt, 100_000, &mut key); let cipher = Aes256Gcm::new_from_slice(&key).map_err(|e| anyhow!("cipher key: {e}"))?; Ok(Self { cipher }) } pub fn encrypt(&self, plaintext: &[u8]) -> Result> { let mut nonce_bytes = [0u8; NONCE_LEN]; rand::thread_rng().fill_bytes(&mut nonce_bytes); let nonce = GenericArray::from_slice(&nonce_bytes); let ciphertext = self .cipher .encrypt(nonce, plaintext) .map_err(|e| anyhow!("encrypt: {e}"))?; let mut out = nonce_bytes.to_vec(); out.extend(ciphertext); Ok(out) } pub fn decrypt(&self, blob: &[u8]) -> Result> { if blob.len() < NONCE_LEN { anyhow::bail!("blob too short"); } let (nonce_bytes, ct) = blob.split_at(NONCE_LEN); let nonce = GenericArray::from_slice(nonce_bytes); self.cipher .decrypt(nonce, ct) .map_err(|e| anyhow!("decrypt: {e}")) } } pub fn content_id(data: &[u8]) -> String { use sha2::Digest; hex::encode(Sha256::digest(data)) } pub fn pack_path(data_dir: &Path, id: &str) -> std::path::PathBuf { let prefix = &id[..2.min(id.len())]; data_dir.join(prefix).join(id) } #[cfg(test)] mod tests { use super::*; use tempfile::tempdir; #[test] fn roundtrip_crypto() { let dir = tempdir().unwrap(); let salt = dir.path().join("salt"); let key = VaultKey::derive_from_passphrase("test-vault", &salt).unwrap(); let enc = key.encrypt(b"stardust").unwrap(); let plain = key.decrypt(&enc).unwrap(); assert_eq!(plain, b"stardust"); } }