1use ic_core::traits::{Algorithm, Digest, Mac, SelfTest};
4use ic_core::{ensure, Result, Zeroize};
5
6const MAX_BLOCK_LEN: usize = 144;
11
12#[derive(Clone)]
18pub struct Hmac<D: Digest> {
19 inner: D,
20 outer: D,
21}
22
23pub trait HmacDigest: Digest {
29 const HMAC_ID: &'static str;
31 const HMAC_NAME: &'static str;
33}
34
35impl<D: HmacDigest> Algorithm for Hmac<D> {
36 const ID: &'static str = D::HMAC_ID;
37 const NAME: &'static str = D::HMAC_NAME;
38}
39
40impl<D: Digest> Hmac<D> {
41 fn absorb_pads(&mut self, key: &[u8]) {
55 let mut pad = [0x36u8; MAX_BLOCK_LEN];
56 let block = &mut pad[..D::BLOCK_LEN];
57 if key.len() > D::BLOCK_LEN {
58 xor_hashed_key::<D>(key, block);
59 } else {
60 for (p, k) in block.iter_mut().zip(key) {
61 *p ^= k;
62 }
63 }
64
65 self.inner.update(block);
66 for p in block.iter_mut() {
67 *p ^= 0x36 ^ 0x5c;
68 }
69 self.outer.update(block);
70
71 block.zeroize();
72 }
73}
74
75const fn large_state<D>() -> bool {
91 core::mem::size_of::<D>() > 512
92}
93
94#[inline(always)]
96fn keyed<D: Digest>(key: &[u8]) -> Hmac<D> {
97 let mut mac = Hmac {
98 inner: D::new(),
99 outer: D::new(),
100 };
101 mac.absorb_pads(key);
102 mac
103}
104
105#[inline(never)]
106fn keyed_out_of_line<D: Digest>(key: &[u8]) -> Hmac<D> {
107 keyed(key)
108}
109
110#[inline(always)]
112fn tag<D: Digest>(mut mac: Hmac<D>) -> D::Output {
113 let inner_digest = mac.inner.finalize();
114 mac.outer.update(inner_digest.as_ref());
115 mac.outer.finalize()
116}
117
118#[inline(never)]
119fn tag_out_of_line<D: Digest>(mac: Hmac<D>) -> D::Output {
120 tag(mac)
121}
122
123#[inline(never)]
128fn xor_hashed_key<D: Digest>(key: &[u8], block: &mut [u8]) {
129 let mut hashed = D::digest(key);
130 for (p, k) in block.iter_mut().zip(hashed.as_ref()) {
131 *p ^= k;
132 }
133 hashed.as_mut().zeroize();
135}
136
137impl<D: HmacDigest> Mac for Hmac<D> {
138 type Tag = D::Output;
139 const TAG_LEN: usize = D::OUTPUT_LEN;
140
141 fn new(key: &[u8]) -> Result<Self> {
142 ensure!(
143 D::BLOCK_LEN <= MAX_BLOCK_LEN,
144 InvalidParameter,
145 "digest block exceeds hmac buffer"
146 );
147 if large_state::<D>() {
148 Ok(keyed_out_of_line(key))
149 } else {
150 Ok(keyed(key))
151 }
152 }
153
154 fn update(&mut self, data: &[u8]) {
155 self.inner.update(data);
156 }
157
158 fn finalize(self) -> Self::Tag {
159 if large_state::<D>() {
160 tag_out_of_line(self)
161 } else {
162 tag(self)
163 }
164 }
165}
166
167macro_rules! hmac_alias {
168 (
169 $name:ident, $digest:ty, $id:literal, $disp:literal, $taglen:literal,
170 $kat_key:expr, $kat_msg:expr, $kat_tag:literal
171 ) => {
172 #[doc = concat!($disp, ".")]
173 pub type $name = Hmac<$digest>;
174
175 impl HmacDigest for $digest {
176 const HMAC_ID: &'static str = $id;
177 const HMAC_NAME: &'static str = $disp;
178 }
179
180 impl SelfTest for Hmac<$digest> {
181 fn self_test() -> Result<()> {
182 let mut key = [0u8; 20];
183 ic_core::codec::hex_decode($kat_key.as_bytes(), &mut key)?;
184 let tag = <Self as Mac>::mac(&key, $kat_msg)?;
185 let mut want = [0u8; $taglen];
186 ic_core::codec::hex_decode($kat_tag.as_bytes(), &mut want)?;
187 ensure!(
188 ic_core::ct::verify(&want, tag.as_ref()),
189 SelfTestFailed,
190 $id
191 );
192 Ok(())
193 }
194 }
195 };
196}
197
198const KAT_KEY: &str = "0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b";
200
201hmac_alias!(
208 HmacSha256,
209 ic_hash::Sha256,
210 "hmac-sha2-256",
211 "HMAC-SHA-256",
212 32,
213 KAT_KEY,
214 b"Hi There",
215 "b0344c61d8db38535ca8afceaf0bf12b881dc200c9833da726e9376c2e32cff7"
216);
217hmac_alias!(
218 HmacSha384,
219 ic_hash::Sha384,
220 "hmac-sha2-384",
221 "HMAC-SHA-384",
222 48,
223 KAT_KEY,
224 b"Hi There",
225 "afd03944d84895626b0825f4ab46907f15f9dadbe4101ec682aa034c7cebc59cfaea9ea9076ede7f4af152e8b2fa9cb6"
226);
227hmac_alias!(
228 HmacSha512,
229 ic_hash::Sha512,
230 "hmac-sha2-512",
231 "HMAC-SHA-512",
232 64,
233 KAT_KEY,
234 b"Hi There",
235 "87aa7cdea5ef619d4ff0b4241a1d6cb02379f4e2ce4ec2787ad0b30545e17cdedaa833b7d6b8a702038b274eaea3f4e4be9d914eeb61f1702e696c203a126854"
236);
237hmac_alias!(
238 HmacSha512_256,
239 ic_hash::Sha512_256,
240 "hmac-sha2-512-256",
241 "HMAC-SHA-512/256",
242 32,
243 KAT_KEY,
244 b"Hi There",
245 "9f9126c3d9c3c330d760425ca8a217e31feae31bfe70196ff81642b868402eab"
246);
247hmac_alias!(
248 HmacSha3_256,
249 ic_hash::Sha3_256,
250 "hmac-sha3-256",
251 "HMAC-SHA3-256",
252 32,
253 KAT_KEY,
254 b"Hi There",
255 "ba85192310dffa96e2a3a40e69774351140bb7185e1202cdcc917589f95e16bb"
256);
257hmac_alias!(
258 HmacSha3_512,
259 ic_hash::Sha3_512,
260 "hmac-sha3-512",
261 "HMAC-SHA3-512",
262 64,
263 KAT_KEY,
264 b"Hi There",
265 "eb3fbd4b2eaab8f5c504bd3a41465aacec15770a7cabac531e482f860b5ec7ba47ccb2c6f2afce8f88d22b6dc61380f23a668fd3888bb80537c0a0b86407689e"
266);
267
268#[cfg(test)]
269mod tests {
270 use super::*;
271 use ic_core::codec::hex;
272
273 #[test]
274 fn rfc4231_case_1() {
275 let key = [0x0bu8; 20];
276 assert_eq!(
277 hex(HmacSha256::mac(&key, b"Hi There").unwrap().as_ref()),
278 "b0344c61d8db38535ca8afceaf0bf12b881dc200c9833da726e9376c2e32cff7"
279 );
280 assert_eq!(
281 hex(HmacSha512::mac(&key, b"Hi There").unwrap().as_ref()),
282 "87aa7cdea5ef619d4ff0b4241a1d6cb02379f4e2ce4ec2787ad0b30545e17cdedaa833b7d6b8a702038b274eaea3f4e4be9d914eeb61f1702e696c203a126854"
283 );
284 }
285
286 #[test]
287 fn rfc4231_case_2_short_key() {
288 assert_eq!(
289 hex(HmacSha256::mac(b"Jefe", b"what do ya want for nothing?")
290 .unwrap()
291 .as_ref()),
292 "5bdcc146bf60754e6a042426089575c75a003f089d2739839dec58b964ec3843"
293 );
294 }
295
296 #[test]
298 fn rfc4231_case_3_long_data() {
299 let key = [0xaau8; 20];
300 let data = [0xddu8; 50];
301 assert_eq!(
302 hex(HmacSha256::mac(&key, &data).unwrap().as_ref()),
303 "773ea91e36800e46854db8ebd09181a72959098b3ef8c122d9635514ced565fe"
304 );
305 }
306
307 #[test]
310 fn rfc4231_case_6_oversized_key() {
311 let key = [0xaau8; 131];
312 assert_eq!(
313 hex(HmacSha256::mac(
314 &key,
315 b"Test Using Larger Than Block-Size Key - Hash Key First"
316 )
317 .unwrap()
318 .as_ref()),
319 "60e431591ee0b67f0d8a26aacbf5b77f8e0bc6213728c5140546040f0ee37f54"
320 );
321 }
322
323 #[test]
328 fn rfc4231_case_6_oversized_key_sha2_512_family() {
329 let key = [0xaau8; 131];
330 let msg = b"Test Using Larger Than Block-Size Key - Hash Key First";
331 assert_eq!(
332 hex(HmacSha384::mac(&key, msg).unwrap().as_ref()),
333 "4ece084485813e9088d2c63a041bc5b44f9ef1012a2b588f3cd11f05033ac4c60c2ef6ab4030fe8296248df163f44952"
334 );
335 assert_eq!(
336 hex(HmacSha512::mac(&key, msg).unwrap().as_ref()),
337 "80b24263c7c1a3ebb71493c1dd7be8b49b46d1f41b4aeec1121b013783f8f3526b56d037e05f2598bd0fd2215d6a1e5295e64f73f63f0aec8b915a985d786598"
338 );
339 }
340
341 #[test]
342 fn empty_key_and_message() {
343 assert_eq!(
344 hex(HmacSha256::mac(b"", b"").unwrap().as_ref()),
345 "b613679a0814d9ec772f95d778c35fc5ff1697c493715653c6c712144292c5ad"
346 );
347 }
348
349 #[test]
350 fn streaming_matches_one_shot() {
351 let data: Vec<u8> = (0..200u8).collect();
352 for split in [0usize, 1, 63, 64, 128, 200] {
353 let mut m = HmacSha256::new(b"k").unwrap();
354 m.update(&data[..split]);
355 m.update(&data[split..]);
356 assert_eq!(m.finalize(), HmacSha256::mac(b"k", &data).unwrap());
357 }
358 }
359
360 #[test]
361 fn verify_rejects_wrong_tag_and_length() {
362 let tag = HmacSha256::mac(b"k", b"m").unwrap();
363 HmacSha256::verify(b"k", b"m", tag.as_ref()).unwrap();
364 let mut bad = tag;
365 bad[0] ^= 1;
366 assert!(HmacSha256::verify(b"k", b"m", bad.as_ref()).is_err());
367 assert!(HmacSha256::verify(b"k", b"m", &tag.as_ref()[..31]).is_err());
368 }
369
370 #[test]
371 fn self_tests_pass() {
372 HmacSha256::self_test().unwrap();
373 HmacSha384::self_test().unwrap();
374 HmacSha512::self_test().unwrap();
375 HmacSha512_256::self_test().unwrap();
376 HmacSha3_256::self_test().unwrap();
377 HmacSha3_512::self_test().unwrap();
378 }
379}