use chacha20poly1305::{KeyInit, XChaCha20Poly1305, aead::Aead};
use crate::errors::CryptoError;
pub struct Encryptor {
cipher: XChaCha20Poly1305,
}
impl Encryptor {
pub fn new(key: &[u8; 32]) -> Self {
Self {
cipher: XChaCha20Poly1305::new(key.into()),
}
}
pub fn encrypt(&self, plaintext: &[u8], nonce: &[u8; 24]) -> Result<Vec<u8>, CryptoError> {
Ok(self.cipher.encrypt(nonce.into(), plaintext)?)
}
pub fn decrypt(&self, ciphertext: &[u8], nonce: &[u8; 24]) -> Result<Vec<u8>, CryptoError> {
Ok(self.cipher.decrypt(nonce.into(), ciphertext)?)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_encryption_decryption() {
let encryptor = Encryptor::new(&[7u8; 32]);
let plaintext = b"Hello, world!";
let nonce = b"the length of this is 24";
let mut ciphertext = encryptor.encrypt(plaintext, nonce).unwrap();
let decrypted_plaintext = encryptor.decrypt(&ciphertext, nonce).unwrap();
assert_eq!(plaintext.to_vec(), decrypted_plaintext);
ciphertext[0] ^= 1;
assert!(encryptor.decrypt(&ciphertext, nonce).is_err());
}
}