Skip to main content

oxicrypto_core/traits/
mac.rs

1use alloc::vec::Vec;
2
3use crate::CryptoError;
4
5/// Message Authentication Code (HMAC, ...).
6pub trait Mac: Send + Sync {
7    /// Human-readable algorithm identifier (e.g. `"HMAC-SHA-256"`).
8    #[must_use]
9    fn name(&self) -> &'static str;
10    /// Required key length (minimum acceptable length; MACs are often variable).
11    #[must_use]
12    fn key_len(&self) -> usize;
13    /// Output tag length in bytes.
14    #[must_use]
15    fn output_len(&self) -> usize;
16    /// Compute a MAC tag for `msg` under `key` and write it into `out`.
17    #[must_use = "result must be checked"]
18    fn mac(&self, key: &[u8], msg: &[u8], out: &mut [u8]) -> Result<(), CryptoError>;
19    /// Verify a MAC tag in constant time.
20    ///
21    /// Returns [`CryptoError::InvalidTag`] on mismatch.
22    #[must_use = "result must be checked"]
23    fn verify(&self, key: &[u8], msg: &[u8], tag: &[u8]) -> Result<(), CryptoError>;
24
25    /// Convenience: compute MAC and return the tag as a [`Vec<u8>`].
26    #[must_use = "result must be checked"]
27    fn mac_to_vec(&self, key: &[u8], msg: &[u8]) -> Result<Vec<u8>, CryptoError> {
28        let mut out = alloc::vec![0u8; self.output_len()];
29        self.mac(key, msg, &mut out)?;
30        Ok(out)
31    }
32}
33
34/// Incremental (streaming) MAC computation.
35pub trait StreamingMac: Send {
36    /// Feed additional data into the MAC state.
37    fn update(&mut self, data: &[u8]);
38    /// Consume the MAC state and write the tag into `out`.
39    #[must_use = "result must be checked"]
40    fn finalize(self, out: &mut [u8]) -> Result<(), CryptoError>;
41    /// Consume the MAC state, compute the tag, and verify against `expected`
42    /// in constant time.
43    #[must_use = "result must be checked"]
44    fn verify(self, expected: &[u8]) -> Result<(), CryptoError>;
45}