use aes_gcm::aead::{Aead, KeyInit, OsRng};
use aes_gcm::{AeadCore, Aes256Gcm, Nonce};
use crate::errors::{EnvVaultError, Result};
const NONCE_LEN: usize = 12;
pub fn encrypt(key: &[u8], plaintext: &[u8]) -> Result<Vec<u8>> {
let cipher = Aes256Gcm::new_from_slice(key)
.map_err(|e| EnvVaultError::EncryptionFailed(format!("invalid key length: {e}")))?;
let nonce = Aes256Gcm::generate_nonce(&mut OsRng);
let ciphertext = cipher
.encrypt(&nonce, plaintext)
.map_err(|e| EnvVaultError::EncryptionFailed(format!("encryption error: {e}")))?;
let mut output = Vec::with_capacity(NONCE_LEN + ciphertext.len());
output.extend_from_slice(&nonce);
output.extend_from_slice(&ciphertext);
Ok(output)
}
pub fn decrypt(key: &[u8], ciphertext_with_nonce: &[u8]) -> Result<Vec<u8>> {
if ciphertext_with_nonce.len() < NONCE_LEN {
return Err(EnvVaultError::DecryptionFailed);
}
let (nonce_bytes, ciphertext) = ciphertext_with_nonce.split_at(NONCE_LEN);
let nonce = Nonce::from_slice(nonce_bytes);
let cipher = Aes256Gcm::new_from_slice(key).map_err(|_| EnvVaultError::DecryptionFailed)?;
let plaintext = cipher
.decrypt(nonce, ciphertext)
.map_err(|_| EnvVaultError::DecryptionFailed)?;
Ok(plaintext)
}