pub trait Mac:
Send
+ Sync
+ MaybeDebug {
// Required methods
fn name(&self) -> &'static str;
fn key_len(&self) -> usize;
fn output_len(&self) -> usize;
fn mac(
&self,
key: &[u8],
msg: &[u8],
out: &mut [u8],
) -> Result<(), CryptoError>;
fn verify(
&self,
key: &[u8],
msg: &[u8],
tag: &[u8],
) -> Result<(), CryptoError>;
// Provided methods
fn min_key_len(&self) -> usize { ... }
fn mac_to_vec(&self, key: &[u8], msg: &[u8]) -> Result<Vec<u8>, CryptoError> { ... }
}Expand description
Message Authentication Code (HMAC, CMAC, KMAC, Poly1305, …).
§Minimum key lengths
For security, MAC keys must meet the following minimum lengths. Passing a
key shorter than min_key_len() is accepted at the API level (the MAC spec
does not mandate rejection) but reduces the security level significantly.
| Algorithm | Minimum recommended key | Notes |
|---|---|---|
| HMAC-SHA-256 | 32 bytes (= output length) | RFC 2104: key < block-size is padded |
| HMAC-SHA-384 | 48 bytes | same rule |
| HMAC-SHA-512 | 64 bytes | same rule |
| HMAC-SHA3-256/512 | output length | same rule |
| CMAC-AES-128 | 16 bytes (exact) | AES block cipher key |
| CMAC-AES-256 | 32 bytes (exact) | AES block cipher key |
| Poly1305 | 32 bytes (exact) | one-time key; must not be reused |
| KMAC128 / KMAC256 | 16 bytes | NIST SP 800-185 recommendation |
Required Methods§
Sourcefn key_len(&self) -> usize
fn key_len(&self) -> usize
Required key length in bytes (the minimum acceptable for this MAC).
For HMAC variants this returns the hash output length. For CMAC-AES this returns the exact AES key size (16 or 32 bytes). For Poly1305 this returns 32 (the one-time key size).
Sourcefn output_len(&self) -> usize
fn output_len(&self) -> usize
Output tag length in bytes.
Sourcefn mac(&self, key: &[u8], msg: &[u8], out: &mut [u8]) -> Result<(), CryptoError>
fn mac(&self, key: &[u8], msg: &[u8], out: &mut [u8]) -> Result<(), CryptoError>
Compute a MAC tag for msg under key and write it into out.
Sourcefn verify(&self, key: &[u8], msg: &[u8], tag: &[u8]) -> Result<(), CryptoError>
fn verify(&self, key: &[u8], msg: &[u8], tag: &[u8]) -> Result<(), CryptoError>
Verify a MAC tag in constant time.
Returns CryptoError::InvalidTag on mismatch.
Provided Methods§
Sourcefn min_key_len(&self) -> usize
fn min_key_len(&self) -> usize
Minimum recommended key length in bytes.
Providing a shorter key is accepted but reduces security.
Default returns self.key_len() (which for most MACs returns output_len()).
Sourcefn mac_to_vec(&self, key: &[u8], msg: &[u8]) -> Result<Vec<u8>, CryptoError>
fn mac_to_vec(&self, key: &[u8], msg: &[u8]) -> Result<Vec<u8>, CryptoError>
Convenience: compute MAC and return the tag as a Vec<u8>.
Dyn Compatibility§
This trait is dyn compatible.
In older versions of Rust, dyn compatibility was called "object safety".