RustCrypto / hashes

Collection of cryptographic hash functions written in pure Rust
1.81k stars 245 forks source link

Add section on Blake2 MAC with variable output + convenience method #602

Open lamafab opened 1 month ago

lamafab commented 1 month ago

This reintroduces the MAC section that used to be present in the version "0.9" but has since been removed. This demonstrates the new API changes and required trait imports. Additionally, the blake2_mac_impl! macro was expanded with the following convenience method, which is very straight-forward:

/// Creates a new instance using the provided key, skipping the salt
/// and persona. This method is equivalent to calling
/// [`new_with_salt_and_personal`](Self::new_with_salt_and_personal)
/// with empty slices for the salt and persona.
 #[inline]
pub fn new_with_key(key: &[u8]) -> Result<Self, InvalidLength> {
    Self::new_with_salt_and_personal(key, &[], &[])
}

You can cut that method out, of course. Maybe it's redundant somehow?

Full example:

use blake2::Blake2bMac;
use blake2::digest::{Update, FixedOutput, consts::U16};
use hex_literal::hex;

let mut hasher: Blake2bMac<U16> = Blake2bMac::new_with_key(b"my_key").unwrap();
hasher.update(b"my_input");
let res = hasher.finalize_fixed();

assert_eq!(res.as_ref(), hex!("3c3869ce1c58d0569827a731d8eab099"));

Which is equivalent to the (outdated) "0.9" way of doing this:

use blake2::VarBlake2b;
use blake2::digest::{Update, VariableOutput};
use hex_literal::hex;

let mut hasher = VarBlake2b::new_keyed(b"my_key", 16);
hasher.update(b"my_input");
let res = hasher.finalize_boxed();

assert_eq!(res.as_ref(), hex!("3c3869ce1c58d0569827a731d8eab099"));

It's probably worth commenting on whether it's possible to somehow combine Blake2bMac with Blake2bVar, respectively MAC output size set at run time. That's not entirely clear to me, either.