ic-mac 0.3.0

HMAC, CMAC, KMAC, and Poly1305 message authentication for IronCrypto
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
//! FIPS 198-1 HMAC, generic over any digest.

use ic_core::traits::internal::Digest;

use ic_core::traits::internal::Mac;

use ic_core::traits::{Algorithm, SelfTest};
use ic_core::{ensure, Result, Zeroize};

/// The largest block size among supported digests.
///
/// SHA-512 uses 128 bytes; SHA3-224 has the widest rate at 144, so the padded
/// key buffers are sized for it.
const MAX_BLOCK_LEN: usize = 144;

/// HMAC over the digest `D`.
///
/// The key is processed per FIPS 198-1: hashed if longer than the block size,
/// zero-padded otherwise. The padded key, and the hash of a long key, are
/// zeroized before the constructor returns.
#[derive(Clone)]
pub struct Hmac<D: Digest> {
    inner: D,
    outer: D,
}

/// A digest that can name its HMAC instantiation in the ontology.
///
/// Rust cannot concatenate `&'static str` constants at compile time, so the
/// composed identifier (`"hmac-sha2-256"`) is declared explicitly per digest
/// rather than derived from [`Digest::ID`].
pub trait HmacDigest: Digest {
    /// Ontology identifier of the HMAC built on this digest.
    const HMAC_ID: &'static str;
    /// Display name of the HMAC built on this digest.
    const HMAC_NAME: &'static str;
}

impl<D: HmacDigest> Algorithm for Hmac<D> {
    const ID: &'static str = D::HMAC_ID;
    const NAME: &'static str = D::HMAC_NAME;
}

impl<D: Digest> Hmac<D> {
    /// Absorb the inner and outer pads into the two fresh states.
    ///
    /// One buffer, built as the inner pad directly -- the zero-padded key
    /// XOR 0x36 -- and turned into the outer pad in place, since
    /// `k ^ 0x5c == (k ^ 0x36) ^ (0x36 ^ 0x5c)`. The wipe is volatile and
    /// byte by byte, which is what makes it stick and also what makes it
    /// cost: it covers the one block this digest used, not two buffers sized
    /// for the widest digest there is. For SHA-256 that is 64 bytes where it
    /// was 288, on every HMAC key setup -- and HKDF sets up a key per call.
    ///
    /// The states are absorbed into where they will live rather than built as
    /// locals and moved into the result: for SHA-384 on Cortex-M4 the locals,
    /// the result and a third state for a long key had shared one 4.4 KiB frame.
    fn absorb_pads(&mut self, key: &[u8]) {
        let mut pad = [0x36u8; MAX_BLOCK_LEN];
        let block = &mut pad[..D::BLOCK_LEN];
        if key.len() > D::BLOCK_LEN {
            xor_hashed_key::<D>(key, block);
        } else {
            for (p, k) in block.iter_mut().zip(key) {
                *p ^= k;
            }
        }

        self.inner.update(block);
        for p in block.iter_mut() {
            *p ^= 0x36 ^ 0x5c;
        }
        self.outer.update(block);

        block.zeroize();
    }
}

// # Where the frames go
//
// A SHA-512 state carries its 640-byte message schedule, so SHA-384 and
// SHA-512 states are about 860 bytes and an HMAC over either is 1.7 KiB.
// Inlined into a caller -- HKDF, say -- key setup and finalization each
// brought their own copies of those states into the caller's frame beside the
// caller's: one HMAC-SHA384 tag reached 11 KiB of stack on Cortex-M4. For
// those digests, key setup and finalization stay out of line, so their
// frames are used one after another instead of all at once.
//
// Not for the small states. SHA-256 gained nothing from it on Cortex-M4, and
// the call cost a short HMAC-SHA256 about 8% on x86-64. The test is a
// constant for each digest, so whichever branch is not taken compiles away.

/// Whether `D`'s state is large enough to keep HMAC's work out of line.
const fn large_state<D>() -> bool {
    core::mem::size_of::<D>() > 512
}

/// `Hmac` keyed with `key`.
#[inline(always)]
fn keyed<D: Digest>(key: &[u8]) -> Hmac<D> {
    let mut mac = Hmac {
        inner: D::new(),
        outer: D::new(),
    };
    mac.absorb_pads(key);
    mac
}

#[inline(never)]
fn keyed_out_of_line<D: Digest>(key: &[u8]) -> Hmac<D> {
    keyed(key)
}

/// The tag: the outer hash over the inner one.
#[inline(always)]
fn tag<D: Digest>(mut mac: Hmac<D>) -> D::Output {
    let inner_digest = mac.inner.finalize();
    mac.outer.update(inner_digest.as_ref());
    mac.outer.finalize()
}

#[inline(never)]
fn tag_out_of_line<D: Digest>(mac: Hmac<D>) -> D::Output {
    tag(mac)
}

/// The whole tag in one pass: the inner hash to completion, then the outer.
///
/// [`Mac::mac`] through `new`, `update` and `finalize` builds both keyed
/// states up front and carries them, as one `Hmac`, through a constructor, a
/// `Result` and a finalizer -- the outer state sitting idle the whole time.
/// A one-shot caller never needs the outer state until the inner digest
/// exists, so here each state is built where it is used and only one is alive
/// at a time. The same compressions in the same order, so the same tag; for a
/// 200-byte HMAC-SHA256 that was about a tenth of the time, on top of the
/// hashing. The pad is wiped as soon as the outer state has absorbed it.
#[inline(always)]
fn one_shot<D: Digest>(key: &[u8], data: &[u8]) -> D::Output {
    let mut pad = [0x36u8; MAX_BLOCK_LEN];
    let block = &mut pad[..D::BLOCK_LEN];
    if key.len() > D::BLOCK_LEN {
        xor_hashed_key::<D>(key, block);
    } else {
        for (p, k) in block.iter_mut().zip(key) {
            *p ^= k;
        }
    }

    let mut inner = D::new();
    inner.update(block);
    // The outer pad goes in before the message, not after the inner digest:
    // it does not depend on the message, and issued here its compression is
    // independent work the CPU overlaps with the inner hash's blocks instead
    // of a block of latency at the end.
    for p in block.iter_mut() {
        *p ^= 0x36 ^ 0x5c;
    }
    let mut outer = D::new();
    outer.update(block);
    block.zeroize();

    inner.update(data);
    let inner_digest = inner.finalize();
    outer.update(inner_digest.as_ref());
    outer.finalize()
}

#[inline(never)]
fn one_shot_out_of_line<D: Digest>(key: &[u8], data: &[u8]) -> D::Output {
    one_shot::<D>(key, data)
}

/// XOR `D(key)` into `block`, for a key longer than one block.
///
/// Out of line so that the third digest state it needs is on the stack only
/// while it runs, not for the whole of key setup.
#[inline(never)]
fn xor_hashed_key<D: Digest>(key: &[u8], block: &mut [u8]) {
    let mut hashed = D::digest(key);
    for (p, k) in block.iter_mut().zip(hashed.as_ref()) {
        *p ^= k;
    }
    // Key-equivalent: HMAC under the hash is HMAC under the key.
    hashed.as_mut().zeroize();
}

impl<D: HmacDigest> Mac for Hmac<D> {
    type Tag = D::Output;
    const TAG_LEN: usize = D::OUTPUT_LEN;

    fn new(key: &[u8]) -> Result<Self> {
        ic_core::module::operational()?;
        ensure!(
            D::BLOCK_LEN <= MAX_BLOCK_LEN,
            InvalidParameter,
            "digest block exceeds hmac buffer"
        );
        if large_state::<D>() {
            Ok(keyed_out_of_line(key))
        } else {
            Ok(keyed(key))
        }
    }

    fn update(&mut self, data: &[u8]) {
        self.inner.update(data);
    }

    fn finalize(self) -> Self::Tag {
        if large_state::<D>() {
            tag_out_of_line(self)
        } else {
            tag(self)
        }
    }

    fn mac(key: &[u8], data: &[u8]) -> Result<Self::Tag> {
        ic_core::module::operational()?;
        ensure!(
            D::BLOCK_LEN <= MAX_BLOCK_LEN,
            InvalidParameter,
            "digest block exceeds hmac buffer"
        );
        if large_state::<D>() {
            Ok(one_shot_out_of_line::<D>(key, data))
        } else {
            Ok(one_shot::<D>(key, data))
        }
    }
}

macro_rules! hmac_alias {
    (
        $name:ident, $digest:ty, $id:literal, $disp:literal, $taglen:literal,
        $kat_key:expr, $kat_msg:expr, $kat_tag:literal
    ) => {
        #[doc = concat!($disp, ".")]
        pub type $name = Hmac<$digest>;

        impl HmacDigest for $digest {
            const HMAC_ID: &'static str = $id;
            const HMAC_NAME: &'static str = $disp;
        }

        impl SelfTest for Hmac<$digest> {
            fn self_test() -> Result<()> {
                let mut key = [0u8; 20];
                ic_core::codec::hex_decode($kat_key.as_bytes(), &mut key)?;
                let tag = <Self as Mac>::mac(&key, $kat_msg)?;
                let mut want = [0u8; $taglen];
                ic_core::codec::hex_decode($kat_tag.as_bytes(), &mut want)?;
                ensure!(
                    ic_core::ct::verify(&want, tag.as_ref()),
                    SelfTestFailed,
                    $id
                );
                Ok(())
            }
        }
    };
}

/// The RFC 4231 test-case-1 key: twenty `0x0b` bytes.
const KAT_KEY: &str = "0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b";

// Known-answer vectors, all over the RFC 4231 test-case-1 input
// (a 20-byte 0x0b key over "Hi There"):
//
// * SHA-256 / SHA-384 / SHA-512 tags are RFC 4231 test case 1.
// * SHA-512/256 and the SHA-3 tags are the corresponding NIST HMAC sample
//   values for the same input.
hmac_alias!(
    HmacSha256,
    ic_hash::Sha256,
    "hmac-sha2-256",
    "HMAC-SHA-256",
    32,
    KAT_KEY,
    b"Hi There",
    "b0344c61d8db38535ca8afceaf0bf12b881dc200c9833da726e9376c2e32cff7"
);
hmac_alias!(
    HmacSha384,
    ic_hash::Sha384,
    "hmac-sha2-384",
    "HMAC-SHA-384",
    48,
    KAT_KEY,
    b"Hi There",
    "afd03944d84895626b0825f4ab46907f15f9dadbe4101ec682aa034c7cebc59cfaea9ea9076ede7f4af152e8b2fa9cb6"
);
hmac_alias!(
    HmacSha512,
    ic_hash::Sha512,
    "hmac-sha2-512",
    "HMAC-SHA-512",
    64,
    KAT_KEY,
    b"Hi There",
    "87aa7cdea5ef619d4ff0b4241a1d6cb02379f4e2ce4ec2787ad0b30545e17cdedaa833b7d6b8a702038b274eaea3f4e4be9d914eeb61f1702e696c203a126854"
);
hmac_alias!(
    HmacSha512_256,
    ic_hash::Sha512_256,
    "hmac-sha2-512-256",
    "HMAC-SHA-512/256",
    32,
    KAT_KEY,
    b"Hi There",
    "9f9126c3d9c3c330d760425ca8a217e31feae31bfe70196ff81642b868402eab"
);
hmac_alias!(
    HmacSha3_256,
    ic_hash::Sha3_256,
    "hmac-sha3-256",
    "HMAC-SHA3-256",
    32,
    KAT_KEY,
    b"Hi There",
    "ba85192310dffa96e2a3a40e69774351140bb7185e1202cdcc917589f95e16bb"
);
hmac_alias!(
    HmacSha3_512,
    ic_hash::Sha3_512,
    "hmac-sha3-512",
    "HMAC-SHA3-512",
    64,
    KAT_KEY,
    b"Hi There",
    "eb3fbd4b2eaab8f5c504bd3a41465aacec15770a7cabac531e482f860b5ec7ba47ccb2c6f2afce8f88d22b6dc61380f23a668fd3888bb80537c0a0b86407689e"
);

#[cfg(test)]
mod tests {
    use super::*;
    use ic_core::codec::hex;

    #[test]
    fn rfc4231_case_1() {
        let key = [0x0bu8; 20];
        assert_eq!(
            hex(HmacSha256::mac(&key, b"Hi There").unwrap().as_ref()),
            "b0344c61d8db38535ca8afceaf0bf12b881dc200c9833da726e9376c2e32cff7"
        );
        assert_eq!(
            hex(HmacSha512::mac(&key, b"Hi There").unwrap().as_ref()),
            "87aa7cdea5ef619d4ff0b4241a1d6cb02379f4e2ce4ec2787ad0b30545e17cdedaa833b7d6b8a702038b274eaea3f4e4be9d914eeb61f1702e696c203a126854"
        );
    }

    #[test]
    fn rfc4231_case_2_short_key() {
        assert_eq!(
            hex(HmacSha256::mac(b"Jefe", b"what do ya want for nothing?")
                .unwrap()
                .as_ref()),
            "5bdcc146bf60754e6a042426089575c75a003f089d2739839dec58b964ec3843"
        );
    }

    /// Case 3 uses a key and message that both exceed one block.
    #[test]
    fn rfc4231_case_3_long_data() {
        let key = [0xaau8; 20];
        let data = [0xddu8; 50];
        assert_eq!(
            hex(HmacSha256::mac(&key, &data).unwrap().as_ref()),
            "773ea91e36800e46854db8ebd09181a72959098b3ef8c122d9635514ced565fe"
        );
    }

    /// Case 6: a 131-byte key, longer than the SHA-256 block, so it is hashed
    /// down first.
    #[test]
    fn rfc4231_case_6_oversized_key() {
        let key = [0xaau8; 131];
        assert_eq!(
            hex(HmacSha256::mac(
                &key,
                b"Test Using Larger Than Block-Size Key - Hash Key First"
            )
            .unwrap()
            .as_ref()),
            "60e431591ee0b67f0d8a26aacbf5b77f8e0bc6213728c5140546040f0ee37f54"
        );
    }

    /// Case 6 again, for SHA-384 and SHA-512: 131 bytes is also longer than
    /// their 128-byte block. These are the digests whose key setup runs out of
    /// line, so this is what checks the long-key path there. RFC 4231 section
    /// 4.7; both tags also checked against Python's `hmac` module.
    #[test]
    fn rfc4231_case_6_oversized_key_sha2_512_family() {
        let key = [0xaau8; 131];
        let msg = b"Test Using Larger Than Block-Size Key - Hash Key First";
        assert_eq!(
            hex(HmacSha384::mac(&key, msg).unwrap().as_ref()),
            "4ece084485813e9088d2c63a041bc5b44f9ef1012a2b588f3cd11f05033ac4c60c2ef6ab4030fe8296248df163f44952"
        );
        assert_eq!(
            hex(HmacSha512::mac(&key, msg).unwrap().as_ref()),
            "80b24263c7c1a3ebb71493c1dd7be8b49b46d1f41b4aeec1121b013783f8f3526b56d037e05f2598bd0fd2215d6a1e5295e64f73f63f0aec8b915a985d786598"
        );
    }

    #[test]
    fn empty_key_and_message() {
        assert_eq!(
            hex(HmacSha256::mac(b"", b"").unwrap().as_ref()),
            "b613679a0814d9ec772f95d778c35fc5ff1697c493715653c6c712144292c5ad"
        );
    }

    #[test]
    fn streaming_matches_one_shot() {
        let data: Vec<u8> = (0..200u8).collect();
        for split in [0usize, 1, 63, 64, 128, 200] {
            let mut m = HmacSha256::new(b"k").unwrap();
            m.update(&data[..split]);
            m.update(&data[split..]);
            assert_eq!(m.finalize(), HmacSha256::mac(b"k", &data).unwrap());
        }
    }

    /// `mac` has its own one-pass path; it must give the tag that `new`,
    /// `update` and `finalize` give, for every digest, for keys shorter than,
    /// equal to and longer than the block (the last are hashed first), and for
    /// messages either side of a block boundary. The RFC 4231 cases above go
    /// through `mac` and pin it to published values; this pins the two paths
    /// to each other everywhere else.
    #[test]
    fn the_one_shot_path_matches_the_streaming_one() {
        fn check<D: HmacDigest>() {
            let block = D::BLOCK_LEN;
            for key_len in [0, 1, 20, block - 1, block, block + 1, 2 * block + 3] {
                let key: Vec<u8> = (0..key_len).map(|i| (i * 13 + 5) as u8).collect();
                for len in [0, 1, 55, 56, 63, 64, 65, 111, 112, 128, 200] {
                    let data: Vec<u8> = (0..len).map(|i| (i * 7 + 1) as u8).collect();
                    let mut m = Hmac::<D>::new(&key).unwrap();
                    m.update(&data);
                    let want = m.finalize();
                    let got = Hmac::<D>::mac(&key, &data).unwrap();
                    assert_eq!(
                        got.as_ref(),
                        want.as_ref(),
                        "{} key {key_len} msg {len}",
                        D::ID
                    );
                }
            }
        }
        check::<ic_hash::Sha256>();
        check::<ic_hash::Sha384>();
        check::<ic_hash::Sha512>();
        check::<ic_hash::Sha512_256>();
        check::<ic_hash::Sha3_256>();
        check::<ic_hash::Sha3_512>();
    }

    #[test]
    fn verify_rejects_wrong_tag_and_length() {
        let tag = HmacSha256::mac(b"k", b"m").unwrap();
        <HmacSha256 as ic_core::traits::Mac>::verify(b"k", b"m", tag.as_ref()).unwrap();
        let mut bad = tag;
        bad[0] ^= 1;
        assert!(<HmacSha256 as ic_core::traits::Mac>::verify(b"k", b"m", bad.as_ref()).is_err());
        assert!(
            <HmacSha256 as ic_core::traits::Mac>::verify(b"k", b"m", &tag.as_ref()[..31]).is_err()
        );
    }

    #[test]
    fn self_tests_pass() {
        HmacSha256::self_test().unwrap();
        HmacSha384::self_test().unwrap();
        HmacSha512::self_test().unwrap();
        HmacSha512_256::self_test().unwrap();
        HmacSha3_256::self_test().unwrap();
        HmacSha3_512::self_test().unwrap();
    }
}