use crate::{ZeroizeArray, ZeroizeBytesArray};
use nanorand::{BufferedRng, ChaCha8, Rng};
pub const XNONCE_LENGTH: usize = 24;
pub const TAG_LENGTH: usize = 16;
#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Clone)]
pub struct EncryptedMem<const N: usize> {
ciphertext: ZeroizeBytesArray<N>,
xnonce: ZeroizeArray<XNONCE_LENGTH>,
}
impl<const N: usize> EncryptedMem<N> {
pub fn new() -> Self {
let mut nonce_buffer = [0u8; XNONCE_LENGTH];
let mut rng = BufferedRng::new(ChaCha8::new());
rng.fill(&mut nonce_buffer);
let outcome = EncryptedMem {
ciphertext: ZeroizeBytesArray::with_additional_capacity(TAG_LENGTH),
xnonce: ZeroizeArray::new(nonce_buffer),
};
nonce_buffer[..].copy_from_slice(&[0u8; XNONCE_LENGTH]);
outcome
}
pub fn new_with_added_capacity(capacity: usize) -> Self {
let mut nonce_buffer = [0u8; XNONCE_LENGTH];
let mut rng = BufferedRng::new(ChaCha8::new());
rng.fill(&mut nonce_buffer);
let outcome = EncryptedMem {
ciphertext: ZeroizeBytesArray::with_additional_capacity(capacity),
xnonce: ZeroizeArray::new(nonce_buffer),
};
nonce_buffer[..].copy_from_slice(&[0u8; XNONCE_LENGTH]);
outcome
}
pub fn add_ciphertext(&mut self, ciphertext: ZeroizeBytesArray<N>) -> &mut Self {
self.ciphertext = ciphertext;
self
}
pub fn ciphertext(&self) -> &ZeroizeBytesArray<N> {
&self.ciphertext
}
pub fn xnonce(&self) -> ZeroizeArray<XNONCE_LENGTH> {
self.xnonce.clone()
}
}