use aes_gcm::aead::{AeadInOut, KeyInit};
use rand_core::CryptoRng;
use xaes_256_gcm::Xaes256Gcm;
use crate::{CryptoError, Key};
pub const PAGE_NONCE_LEN: usize = 24;
pub const PAGE_TAG_LEN: usize = 16;
pub const RECORD_OVERHEAD: usize = PAGE_NONCE_LEN + PAGE_TAG_LEN;
pub struct PageCipher(Xaes256Gcm);
impl PageCipher {
#[must_use]
pub fn new(key: &Key) -> Self {
Self(Xaes256Gcm::new(key.expose_bytes().into()))
}
pub fn seal(
&self,
rng: &mut (impl CryptoRng + ?Sized),
associated_data: &[u8],
record: &mut [u8],
) {
let (nonce, rest) = record
.split_first_chunk_mut::<PAGE_NONCE_LEN>()
.expect("room for a nonce");
let (data, tag) = rest
.split_last_chunk_mut::<PAGE_TAG_LEN>()
.expect("room for a tag");
rng.fill_bytes(nonce);
let sealed_tag = self
.0
.encrypt_inout_detached((&*nonce).into(), associated_data, data.into())
.expect("a record fits");
tag.copy_from_slice(&sealed_tag);
}
pub fn open<'a>(
&self,
associated_data: &[u8],
record: &'a mut [u8],
) -> Result<&'a [u8], CryptoError> {
let Some((nonce, rest)) = record.split_first_chunk_mut::<PAGE_NONCE_LEN>() else {
return Err(CryptoError::Decryption);
};
let Some((data, tag)) = rest.split_last_chunk_mut::<PAGE_TAG_LEN>() else {
return Err(CryptoError::Decryption);
};
match self.0.decrypt_inout_detached(
(&*nonce).into(),
associated_data,
(&mut *data).into(),
(&*tag).into(),
) {
Ok(()) => Ok(data),
Err(_) => Err(CryptoError::Decryption),
}
}
}