//! HMAC: keyed-hash message authentication code (RFC 2104). use crate::sha2::{Sha256, Sha384, Sha512}; /// Trait abstracting a hash function for use with HMAC. pub trait HashFunction { /// Block size in bytes (64 for SHA-256, 128 for SHA-512/SHA-384). const BLOCK_SIZE: usize; /// Output digest size in bytes. const OUTPUT_SIZE: usize; fn hash_new() -> Self; fn hash_update(&mut self, data: &[u8]); fn hash_finalize(self) -> Vec; } impl HashFunction for Sha256 { const BLOCK_SIZE: usize = 64; const OUTPUT_SIZE: usize = 32; fn hash_new() -> Self { Sha256::new() } fn hash_update(&mut self, data: &[u8]) { Sha256::update(self, data); } fn hash_finalize(self) -> Vec { Sha256::finalize(self).to_vec() } } impl HashFunction for Sha512 { const BLOCK_SIZE: usize = 128; const OUTPUT_SIZE: usize = 64; fn hash_new() -> Self { Sha512::new() } fn hash_update(&mut self, data: &[u8]) { Sha512::update(self, data); } fn hash_finalize(self) -> Vec { Sha512::finalize(self).to_vec() } } impl HashFunction for Sha384 { const BLOCK_SIZE: usize = 128; const OUTPUT_SIZE: usize = 48; fn hash_new() -> Self { Sha384::new() } fn hash_update(&mut self, data: &[u8]) { Sha384::update(self, data); } fn hash_finalize(self) -> Vec { Sha384::finalize(self).to_vec() } } /// HMAC hasher, generic over the hash function `H`. /// /// Implements RFC 2104: `HMAC(K, m) = H((K' ⊕ opad) ∥ H((K' ⊕ ipad) ∥ m))` pub struct Hmac { /// Inner hash, pre-seeded with `K' ⊕ ipad`. inner: H, /// Pre-computed `K' ⊕ opad` for the outer hash. opad_key: Vec, } impl Hmac { /// Create a new HMAC instance with the given key. /// /// Keys longer than the hash block size are hashed first. /// Keys shorter than the block size are zero-padded. pub fn new(key: &[u8]) -> Self { // Step 1: Derive the block-sized key K'. let mut key_block = vec![0u8; H::BLOCK_SIZE]; if key.len() > H::BLOCK_SIZE { let mut h = H::hash_new(); h.hash_update(key); let hashed = h.hash_finalize(); key_block[..hashed.len()].copy_from_slice(&hashed); } else { key_block[..key.len()].copy_from_slice(key); } // Step 2: Compute ipad and opad keys. let mut ipad_key = vec![0u8; H::BLOCK_SIZE]; let mut opad_key = vec![0u8; H::BLOCK_SIZE]; for i in 0..H::BLOCK_SIZE { ipad_key[i] = key_block[i] ^ 0x36; opad_key[i] = key_block[i] ^ 0x5c; } // Step 3: Start the inner hash with K' ⊕ ipad. let mut inner = H::hash_new(); inner.hash_update(&ipad_key); Self { inner, opad_key } } /// Feed data into the HMAC computation. pub fn update(&mut self, data: &[u8]) { self.inner.hash_update(data); } /// Finalize and return the HMAC digest. pub fn finalize(self) -> Vec { // Complete inner hash: H((K' ⊕ ipad) ∥ message) let inner_hash = self.inner.hash_finalize(); // Compute outer hash: H((K' ⊕ opad) ∥ inner_hash) let mut outer = H::hash_new(); outer.hash_update(&self.opad_key); outer.hash_update(&inner_hash); outer.hash_finalize() } } /// One-shot HMAC-SHA-256. pub fn hmac_sha256(key: &[u8], data: &[u8]) -> [u8; 32] { let mut h = Hmac::::new(key); h.update(data); let result = h.finalize(); let mut out = [0u8; 32]; out.copy_from_slice(&result); out } /// One-shot HMAC-SHA-384. pub fn hmac_sha384(key: &[u8], data: &[u8]) -> [u8; 48] { let mut h = Hmac::::new(key); h.update(data); let result = h.finalize(); let mut out = [0u8; 48]; out.copy_from_slice(&result); out } /// One-shot HMAC-SHA-512. pub fn hmac_sha512(key: &[u8], data: &[u8]) -> [u8; 64] { let mut h = Hmac::::new(key); h.update(data); let result = h.finalize(); let mut out = [0u8; 64]; out.copy_from_slice(&result); out } // --------------------------------------------------------------------------- // Tests — RFC 4231 test vectors // --------------------------------------------------------------------------- #[cfg(test)] mod tests { use super::*; fn hex(bytes: &[u8]) -> String { bytes.iter().map(|b| format!("{b:02x}")).collect() } // ----------------------------------------------------------------------- // Test Case 1: Key = 0x0b * 20, Data = "Hi There" // ----------------------------------------------------------------------- #[test] fn rfc4231_case1_sha256() { let key = [0x0bu8; 20]; assert_eq!( hex(&hmac_sha256(&key, b"Hi There")), "b0344c61d8db38535ca8afceaf0bf12b881dc200c9833da726e9376c2e32cff7" ); } #[test] fn rfc4231_case1_sha384() { let key = [0x0bu8; 20]; assert_eq!( hex(&hmac_sha384(&key, b"Hi There")), "afd03944d84895626b0825f4ab46907f15f9dadbe4101ec682aa034c7cebc59cfaea9ea9076ede7f4af152e8b2fa9cb6" ); } #[test] fn rfc4231_case1_sha512() { let key = [0x0bu8; 20]; assert_eq!( hex(&hmac_sha512(&key, b"Hi There")), "87aa7cdea5ef619d4ff0b4241a1d6cb02379f4e2ce4ec2787ad0b30545e17cdedaa833b7d6b8a702038b274eaea3f4e4be9d914eeb61f1702e696c203a126854" ); } // ----------------------------------------------------------------------- // Test Case 2: Key = "Jefe", Data = "what do ya want for nothing?" // ----------------------------------------------------------------------- #[test] fn rfc4231_case2_sha256() { assert_eq!( hex(&hmac_sha256(b"Jefe", b"what do ya want for nothing?")), "5bdcc146bf60754e6a042426089575c75a003f089d2739839dec58b964ec3843" ); } #[test] fn rfc4231_case2_sha384() { assert_eq!( hex(&hmac_sha384(b"Jefe", b"what do ya want for nothing?")), "af45d2e376484031617f78d2b58a6b1b9c7ef464f5a01b47e42ec3736322445e8e2240ca5e69e2c78b3239ecfab21649" ); } #[test] fn rfc4231_case2_sha512() { assert_eq!( hex(&hmac_sha512(b"Jefe", b"what do ya want for nothing?")), "164b7a7bfcf819e2e395fbe73b56e0a387bd64222e831fd610270cd7ea2505549758bf75c05a994a6d034f65f8f0e6fdcaeab1a34d4a6b4b636e070a38bce737" ); } // ----------------------------------------------------------------------- // Test Case 3: Key = 0xaa * 20, Data = 0xdd * 50 // ----------------------------------------------------------------------- #[test] fn rfc4231_case3_sha256() { let key = [0xaau8; 20]; let data = [0xddu8; 50]; assert_eq!( hex(&hmac_sha256(&key, &data)), "773ea91e36800e46854db8ebd09181a72959098b3ef8c122d9635514ced565fe" ); } #[test] fn rfc4231_case3_sha384() { let key = [0xaau8; 20]; let data = [0xddu8; 50]; assert_eq!( hex(&hmac_sha384(&key, &data)), "88062608d3e6ad8a0aa2ace014c8a86f0aa635d947ac9febe83ef4e55966144b2a5ab39dc13814b94e3ab6e101a34f27" ); } #[test] fn rfc4231_case3_sha512() { let key = [0xaau8; 20]; let data = [0xddu8; 50]; assert_eq!( hex(&hmac_sha512(&key, &data)), "fa73b0089d56a284efb0f0756c890be9b1b5dbdd8ee81a3655f83e33b2279d39bf3e848279a722c806b485a47e67c807b946a337bee8942674278859e13292fb" ); } // ----------------------------------------------------------------------- // Test Case 4: Key = 0x01..0x19 (25 bytes), Data = 0xcd * 50 // ----------------------------------------------------------------------- #[test] fn rfc4231_case4_sha256() { let key: Vec = (0x01..=0x19).collect(); let data = [0xcdu8; 50]; assert_eq!( hex(&hmac_sha256(&key, &data)), "82558a389a443c0ea4cc819899f2083a85f0faa3e578f8077a2e3ff46729665b" ); } #[test] fn rfc4231_case4_sha384() { let key: Vec = (0x01..=0x19).collect(); let data = [0xcdu8; 50]; assert_eq!( hex(&hmac_sha384(&key, &data)), "3e8a69b7783c25851933ab6290af6ca77a9981480850009cc5577c6e1f573b4e6801dd23c4a7d679ccf8a386c674cffb" ); } #[test] fn rfc4231_case4_sha512() { let key: Vec = (0x01..=0x19).collect(); let data = [0xcdu8; 50]; assert_eq!( hex(&hmac_sha512(&key, &data)), "b0ba465637458c6990e5a8c5f61d4af7e576d97ff94b872de76f8050361ee3dba91ca5c11aa25eb4d679275cc5788063a5f19741120c4f2de2adebeb10a298dd" ); } // ----------------------------------------------------------------------- // Test Case 5: Truncation (Key = 0x0c * 20, Data = "Test With Truncation") // Verify the first 16 bytes of the full HMAC match the truncated vector. // ----------------------------------------------------------------------- #[test] fn rfc4231_case5_sha256_truncated() { let key = [0x0cu8; 20]; let result = hmac_sha256(&key, b"Test With Truncation"); assert_eq!(hex(&result[..16]), "a3b6167473100ee06e0c796c2955552b"); } #[test] fn rfc4231_case5_sha384_truncated() { let key = [0x0cu8; 20]; let result = hmac_sha384(&key, b"Test With Truncation"); assert_eq!(hex(&result[..16]), "3abf34c3503b2a23a46efc619baef897"); } #[test] fn rfc4231_case5_sha512_truncated() { let key = [0x0cu8; 20]; let result = hmac_sha512(&key, b"Test With Truncation"); assert_eq!(hex(&result[..16]), "415fad6271580a531d4179bc891d87a6"); } // ----------------------------------------------------------------------- // Test Case 6: Key longer than block size (0xaa * 131) // Data = "Test Using Larger Than Block-Size Key - Hash Key First" // ----------------------------------------------------------------------- #[test] fn rfc4231_case6_sha256() { let key = [0xaau8; 131]; assert_eq!( hex(&hmac_sha256( &key, b"Test Using Larger Than Block-Size Key - Hash Key First" )), "60e431591ee0b67f0d8a26aacbf5b77f8e0bc6213728c5140546040f0ee37f54" ); } #[test] fn rfc4231_case6_sha384() { let key = [0xaau8; 131]; assert_eq!( hex(&hmac_sha384(&key, b"Test Using Larger Than Block-Size Key - Hash Key First")), "4ece084485813e9088d2c63a041bc5b44f9ef1012a2b588f3cd11f05033ac4c60c2ef6ab4030fe8296248df163f44952" ); } #[test] fn rfc4231_case6_sha512() { let key = [0xaau8; 131]; assert_eq!( hex(&hmac_sha512(&key, b"Test Using Larger Than Block-Size Key - Hash Key First")), "80b24263c7c1a3ebb71493c1dd7be8b49b46d1f41b4aeec1121b013783f8f3526b56d037e05f2598bd0fd2215d6a1e5295e64f73f63f0aec8b915a985d786598" ); } // ----------------------------------------------------------------------- // Test Case 7: Key longer than block size, data longer than block size // Key = 0xaa * 131 // ----------------------------------------------------------------------- const CASE7_DATA: &[u8] = b"This is a test using a larger than block-size key and a larger than block-size data. The key needs to be hashed before being used by the HMAC algorithm."; #[test] fn rfc4231_case7_sha256() { let key = [0xaau8; 131]; assert_eq!( hex(&hmac_sha256(&key, CASE7_DATA)), "9b09ffa71b942fcb27635fbcd5b0e944bfdc63644f0713938a7f51535c3a35e2" ); } #[test] fn rfc4231_case7_sha384() { let key = [0xaau8; 131]; assert_eq!( hex(&hmac_sha384(&key, CASE7_DATA)), "6617178e941f020d351e2f254e8fd32c602420feb0b8fb9adccebb82461e99c5a678cc31e799176d3860e6110c46523e" ); } #[test] fn rfc4231_case7_sha512() { let key = [0xaau8; 131]; assert_eq!( hex(&hmac_sha512(&key, CASE7_DATA)), "e37b6a775dc87dbaa4dfa9f96e5e3ffddebd71f8867289865df5a32d20cdc944b6022cac3c4982b10d5eeb55c3e4de15134676fb6de0446065c97440fa8c6a58" ); } // ----------------------------------------------------------------------- // Streaming API tests // ----------------------------------------------------------------------- #[test] fn streaming_matches_oneshot_sha256() { let key = b"secret key"; let data = b"The quick brown fox jumps over the lazy dog"; let expected = hmac_sha256(key, data); let mut h = Hmac::::new(key); h.update(&data[..10]); h.update(&data[10..30]); h.update(&data[30..]); let result = h.finalize(); assert_eq!(&result[..], &expected[..]); } #[test] fn streaming_matches_oneshot_sha512() { let key = b"another secret key"; let data = b"Some message to authenticate"; let expected = hmac_sha512(key, data); let mut h = Hmac::::new(key); h.update(&data[..5]); h.update(&data[5..]); let result = h.finalize(); assert_eq!(&result[..], &expected[..]); } #[test] fn empty_data() { let key = [0x0bu8; 20]; let result = hmac_sha256(&key, b""); // Just verify it doesn't panic and produces 32 bytes. assert_eq!(result.len(), 32); } #[test] fn key_exactly_block_size_sha256() { // Key exactly 64 bytes (SHA-256 block size) — no hashing, no padding needed. let key = [0x42u8; 64]; let result = hmac_sha256(&key, b"test"); assert_eq!(result.len(), 32); // Verify streaming matches. let mut h = Hmac::::new(&key); h.update(b"test"); assert_eq!(&h.finalize()[..], &result[..]); } }