use crate::{chacha20, ct_eq, poly1305::Poly1305};
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct AuthError;
impl core::fmt::Display for AuthError {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
f.write_str("authentication tag mismatch")
}
}
impl core::error::Error for AuthError {}
fn tag(key: &[u8; 32], nonce: &[u8; 12], aad: &[u8], ciphertext: &[u8]) -> [u8; 16] {
let block0 = chacha20::block(key, 0, nonce);
let mut otk = [0u8; 32];
otk.copy_from_slice(&block0[..32]);
let mut p = Poly1305::new(&otk);
let zeros = [0u8; 16];
p.update(aad);
p.update(&zeros[..(16 - aad.len() % 16) % 16]);
p.update(ciphertext);
p.update(&zeros[..(16 - ciphertext.len() % 16) % 16]);
p.update(&(aad.len() as u64).to_le_bytes());
p.update(&(ciphertext.len() as u64).to_le_bytes());
p.finalize()
}
pub fn seal(key: &[u8; 32], nonce: &[u8; 12], aad: &[u8], buf: &mut [u8]) -> [u8; 16] {
chacha20::xor_keystream(key, 1, nonce, buf);
tag(key, nonce, aad, buf)
}
pub fn open(
key: &[u8; 32],
nonce: &[u8; 12],
aad: &[u8],
buf: &mut [u8],
tag_in: &[u8; 16],
) -> Result<(), AuthError> {
if !ct_eq(&tag(key, nonce, aad, buf), tag_in) {
return Err(AuthError);
}
chacha20::xor_keystream(key, 1, nonce, buf);
Ok(())
}