use aes_gcm::{
Aes256Gcm, Nonce,
aead::{Aead, KeyInit},
};
use zeroize::{Zeroize, ZeroizeOnDrop};
use crate::random;
#[derive(Debug, thiserror::Error)]
pub enum AesError {
#[error("encryption failed: {0}")]
Encrypt(String),
#[error("decryption failed: {0}")]
Decrypt(String),
#[error("invalid key length: expected 32, got {0}")]
InvalidKeyLength(usize),
#[error("invalid nonce length: expected 12, got {0}")]
InvalidNonceLength(usize),
}
#[derive(Zeroize, ZeroizeOnDrop)]
pub struct AesGcmEncryptor {
key: [u8; 32],
}
impl AesGcmEncryptor {
pub fn new(key: [u8; 32]) -> Result<Self, AesError> {
Ok(Self { key })
}
pub fn generate() -> Result<Self, AesError> {
let mut key = [0u8; 32];
random::secure_random_bytes(&mut key);
Ok(Self { key })
}
pub fn encrypt(&self, plaintext: &[u8]) -> Result<Vec<u8>, AesError> {
let cipher =
Aes256Gcm::new_from_slice(&self.key).map_err(|e| AesError::Encrypt(e.to_string()))?;
let mut nonce_bytes = [0u8; 12];
random::secure_random_bytes(&mut nonce_bytes);
let nonce = Nonce::from_slice(&nonce_bytes);
let ciphertext = cipher
.encrypt(nonce, plaintext)
.map_err(|e| AesError::Encrypt(e.to_string()))?;
let mut output = Vec::with_capacity(12 + ciphertext.len());
output.extend_from_slice(&nonce_bytes);
output.extend_from_slice(&ciphertext);
Ok(output)
}
pub fn decrypt(&self, data: &[u8]) -> Result<Vec<u8>, AesError> {
if data.len() < 12 {
return Err(AesError::Decrypt("data too short".into()));
}
let (nonce_bytes, ciphertext) = data.split_at(12);
let nonce = Nonce::from_slice(nonce_bytes);
let cipher =
Aes256Gcm::new_from_slice(&self.key).map_err(|e| AesError::Decrypt(e.to_string()))?;
cipher
.decrypt(nonce, ciphertext)
.map_err(|e| AesError::Decrypt(e.to_string()))
}
pub fn key_bytes(&self) -> &[u8; 32] {
&self.key
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn round_trip() {
let enc = AesGcmEncryptor::generate().unwrap();
let plaintext = b"hello world, this is a test message!";
let ciphertext = enc.encrypt(plaintext).unwrap();
let decrypted = enc.decrypt(&ciphertext).unwrap();
assert_eq!(decrypted, plaintext);
}
#[test]
fn wrong_key_fails() {
let enc1 = AesGcmEncryptor::generate().unwrap();
let enc2 = AesGcmEncryptor::generate().unwrap();
let ciphertext = enc1.encrypt(b"secret").unwrap();
assert!(enc2.decrypt(&ciphertext).is_err());
}
#[test]
fn tampered_ciphertext_fails() {
let enc = AesGcmEncryptor::generate().unwrap();
let mut ciphertext = enc.encrypt(b"secret").unwrap();
if let Some(last) = ciphertext.last_mut() {
*last ^= 0xff;
}
assert!(enc.decrypt(&ciphertext).is_err());
}
#[test]
fn empty_plaintext() {
let enc = AesGcmEncryptor::generate().unwrap();
let ciphertext = enc.encrypt(b"").unwrap();
let decrypted = enc.decrypt(&ciphertext).unwrap();
assert_eq!(decrypted, b"");
}
#[test]
fn key_zeroize_on_drop() {
let key = [0x42u8; 32];
let enc = AesGcmEncryptor::new(key).unwrap();
let ptr = enc.key.as_ptr();
drop(enc);
assert!(!ptr.is_null());
}
}