//! MAC (Message Authentication Code) implementations via wolfCrypt. //! //! Provides HMAC-SHA256, HMAC-SHA384, HMAC-SHA512, and BLAKE2b-MAC. //! All `verify_mac` implementations use constant-time comparison to prevent //! timing side-channels. use ccc_crypto_core::{algorithms::MacAlgorithm, error::CryptoError}; // wolfCrypt hash type constants from `enum wc_HashType` in types.h (non-FIPS build). // WC_HASH_TYPE_SHA256 = 6, WC_HASH_TYPE_SHA384 = 7, WC_HASH_TYPE_SHA512 = 8. const WC_HASH_TYPE_SHA256: i32 = 6; const WC_HASH_TYPE_SHA384: i32 = 7; const WC_HASH_TYPE_SHA512: i32 = 8; // ────────────────────────────────────────────────────────────────────────────── // Public entry points // ────────────────────────────────────────────────────────────────────────────── /// Compute a MAC tag over `data` using the specified algorithm and `key`. pub fn compute_mac(algo: MacAlgorithm, key: &[u8], data: &[u8]) -> Result, CryptoError> { match algo { MacAlgorithm::HmacSha256 => hmac(WC_HASH_TYPE_SHA256, key, data, 32), MacAlgorithm::HmacSha384 => hmac(WC_HASH_TYPE_SHA384, key, data, 48), MacAlgorithm::HmacSha512 => hmac(WC_HASH_TYPE_SHA512, key, data, 64), MacAlgorithm::Blake2bMac => blake2b_mac(key, data), MacAlgorithm::Poly1305 => Err(CryptoError::UnsupportedAlgorithm( "Poly1305 standalone MAC is not exposed in this Phase".into(), )), } } /// Verify a MAC tag in constant time. /// /// Returns `Ok(true)` if the tag matches, `Ok(false)` if it does not. /// Never returns `Err` for a tag mismatch — only for structural errors. pub fn verify_mac( algo: MacAlgorithm, key: &[u8], data: &[u8], mac: &[u8], ) -> Result { let expected = compute_mac(algo, key, data)?; Ok(constant_time_eq(&expected, mac)) } // ────────────────────────────────────────────────────────────────────────────── // HMAC // ────────────────────────────────────────────────────────────────────────────── /// HMAC using wolfCrypt's `wc_HmacSetKey` / `wc_HmacUpdate` / `wc_HmacFinal`. /// /// `hash_type` must be a `WC_HASH_TYPE_*` constant; `out_len` must match the /// hash output size. This function is `pub(crate)` so that the KDF module can /// call it directly for RFC 5869 HKDF-Expand without duplicating HMAC logic. pub(crate) fn hmac( hash_type: i32, key: &[u8], data: &[u8], out_len: usize, ) -> Result, CryptoError> { let mut out = vec![0u8; out_len]; unsafe { // wolfSSL's Hmac struct embeds a wc_Sha256 (which requires ALIGN16). // Allocate with explicit 16-byte alignment to match the C struct layout. use std::alloc::{alloc_zeroed, dealloc, Layout}; // sizeof(Hmac) = 456 bytes; alignment = 16 (from embedded wc_Sha256). let layout = Layout::from_size_align(std::mem::size_of::().max(456), 16) .expect("layout must be valid"); let hmac_ptr = alloc_zeroed(layout) as *mut crate::sys::Hmac; if hmac_ptr.is_null() { return Err(CryptoError::InternalError("Hmac alloc failed".into())); } // wc_HmacInit MUST be called before wc_HmacSetKey per wolfSSL 5.x API. let ret = crate::sys::wc_HmacInit( hmac_ptr, std::ptr::null_mut(), -2, // INVALID_DEVID ); if ret != 0 { dealloc(hmac_ptr as *mut u8, layout); return Err(CryptoError::InternalError(format!( "wc_HmacInit returned {}", ret ))); } let ret = crate::sys::wc_HmacSetKey(hmac_ptr, hash_type, key.as_ptr(), key.len() as u32); if ret != 0 { crate::sys::wc_HmacFree(hmac_ptr); dealloc(hmac_ptr as *mut u8, layout); return Err(CryptoError::InvalidKey(format!( "wc_HmacSetKey returned {}", ret ))); } let ret = crate::sys::wc_HmacUpdate(hmac_ptr, data.as_ptr(), data.len() as u32); if ret != 0 { crate::sys::wc_HmacFree(hmac_ptr); dealloc(hmac_ptr as *mut u8, layout); return Err(CryptoError::InternalError(format!( "wc_HmacUpdate returned {}", ret ))); } let ret = crate::sys::wc_HmacFinal(hmac_ptr, out.as_mut_ptr()); if ret != 0 { crate::sys::wc_HmacFree(hmac_ptr); dealloc(hmac_ptr as *mut u8, layout); return Err(CryptoError::InternalError(format!( "wc_HmacFinal returned {}", ret ))); } crate::sys::wc_HmacFree(hmac_ptr); dealloc(hmac_ptr as *mut u8, layout); } Ok(out) } // ────────────────────────────────────────────────────────────────────────────── // BLAKE2b-MAC (keyed BLAKE2b) // ────────────────────────────────────────────────────────────────────────────── /// Keyed BLAKE2b-512 used as a MAC. /// /// Key length must be 1–64 bytes (wolfCrypt limitation). /// Output is always 64 bytes (BLAKE2b-512 full digest length). /// /// Uses `wc_InitBlake2b_WithKey` → `wc_Blake2bUpdate` → `wc_Blake2bFinal`. fn blake2b_mac(key: &[u8], data: &[u8]) -> Result, CryptoError> { if key.is_empty() || key.len() > 64 { return Err(CryptoError::InvalidKey( "BLAKE2b-MAC: key must be 1–64 bytes".into(), )); } const OUT_LEN: u32 = 64; let mut out = vec![0u8; OUT_LEN as usize]; unsafe { let mut b2b: crate::sys::Blake2b = std::mem::zeroed(); // Initialise with digest size and key for keyed (MAC) mode. let ret = crate::sys::wc_InitBlake2b_WithKey(&mut b2b, OUT_LEN, key.as_ptr(), key.len() as u32); if ret != 0 { return Err(CryptoError::InternalError(format!( "wc_InitBlake2b_WithKey returned {ret}" ))); } let ret = crate::sys::wc_Blake2bUpdate(&mut b2b, data.as_ptr(), data.len() as u32); if ret != 0 { return Err(CryptoError::InternalError(format!( "wc_Blake2bUpdate returned {ret}" ))); } let ret = crate::sys::wc_Blake2bFinal(&mut b2b, out.as_mut_ptr(), OUT_LEN); if ret != 0 { return Err(CryptoError::InternalError(format!( "wc_Blake2bFinal returned {ret}" ))); } } Ok(out) } // ────────────────────────────────────────────────────────────────────────────── // Constant-time comparison // ────────────────────────────────────────────────────────────────────────────── /// Constant-time byte-slice equality comparison. /// /// Returns `false` immediately if lengths differ (safe — length is not secret /// for fixed-size HMAC tags). fn constant_time_eq(a: &[u8], b: &[u8]) -> bool { if a.len() != b.len() { return false; } // Accumulate XOR differences; the branch is on the final accumulated value // only, not on any individual byte. let diff: u8 = a .iter() .zip(b.iter()) .fold(0u8, |acc, (x, y)| acc | (x ^ y)); diff == 0 } #[cfg(test)] #[path = "mac_tests.rs"] mod tests;