use crate::utils::{IPAD, OPAD, get_der_key}; use core::fmt; use digest::{ Digest, FixedOutput, KeyInit, MacMarker, Output, OutputSizeUser, Update, common::{Block, BlockSizeUser, InvalidLength, Key, KeySizeUser}, }; /// Simplified HMAC instance able to operate over hash functions /// which do not expose block-level API and hash functions which /// process blocks lazily (e.g. BLAKE2). #[derive(Clone)] pub struct SimpleHmac { digest: D, opad_key: Block, } impl KeySizeUser for SimpleHmac { type KeySize = D::BlockSize; } impl MacMarker for SimpleHmac {} impl KeyInit for SimpleHmac { fn new(key: &Key) -> Self { Self::new_from_slice(key.as_slice()).expect("HMAC accepts keys of any length") } #[inline] fn new_from_slice(key: &[u8]) -> Result { let mut buf = get_der_key::(key); buf.iter_mut().for_each(|b: &mut u8| *b ^= IPAD); let mut digest = D::new(); digest.update(&buf); buf.iter_mut().for_each(|b: &mut u8| *b ^= OPAD ^ IPAD); Ok(Self { digest, opad_key: buf, }) } } impl Update for SimpleHmac { #[inline(always)] fn update(&mut self, data: &[u8]) { self.digest.update(data); } } impl OutputSizeUser for SimpleHmac { type OutputSize = D::OutputSize; } impl FixedOutput for SimpleHmac { fn finalize_into(self, out: &mut Output) { let mut h = D::new(); h.update(&self.opad_key); h.update(self.digest.finalize()); h.finalize_into(out); } } impl fmt::Debug for SimpleHmac { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.write_str("SimpleHmac { ... }") } }