use crate::{ChaCha20Poly1305Cipher, CipherKey};
#[derive(Clone)]
pub struct Safe<T> {
pub metadata: T,
encrypted_bytes: Box<[u8]>,
nonce: [u8; 24],
}
impl<T> Safe<T> {
pub fn from_plain_bytes(
metadata: T,
key: &CipherKey,
plain_bytes: &[u8],
) -> Result<Self, String> {
let (encrypted_bytes, nonce) = ChaCha20Poly1305Cipher::encrypt(&key, &plain_bytes)?;
Ok(Safe {
metadata,
encrypted_bytes: encrypted_bytes.into_boxed_slice(),
nonce,
})
}
pub fn decrypt(&self, key: &CipherKey) -> Result<Vec<u8>, String> {
Ok(ChaCha20Poly1305Cipher::decrypt(&key, &self.nonce, &self.encrypted_bytes)?)
}
pub fn get_bytes(&self) -> &[u8] {
&self.encrypted_bytes
}
}