use crate::errors::EnkryptitError;
use chacha20poly1305::{
XChaCha20Poly1305, XNonce,
aead::{AeadInPlace, OsRng},
};
use rand::RngCore;
pub fn encrypt_chunk(
data: &mut Vec<u8>,
nonce: &[u8; 24],
cipher: &XChaCha20Poly1305,
step: u64,
) -> Result<(), EnkryptitError> {
let new_nonce = derive_nonce(nonce, step);
cipher.encrypt_in_place(XNonce::from_slice(&new_nonce), b"", data)?;
Ok(())
}
pub fn derive_nonce(master_nonce: &[u8; 24], step: u64) -> [u8; 24] {
let mut nonce = *master_nonce;
nonce[16..24].copy_from_slice(&step.to_le_bytes());
nonce
}
pub fn decrypt_chunk(
data: &mut Vec<u8>,
cipher: &XChaCha20Poly1305,
nonce: &[u8; 24],
step: u64,
) -> Result<(), EnkryptitError> {
let new_nonce = derive_nonce(nonce, step);
cipher.decrypt_in_place(XNonce::from_slice(&new_nonce), b"", data)?;
Ok(())
}
pub fn generate_nonce() -> [u8; 24] {
let mut rng = OsRng;
let mut nonce_bytes = [0u8; 24];
rng.fill_bytes(&mut nonce_bytes);
nonce_bytes
}