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
use super::{get_der_key, IPAD, OPAD};
use core::fmt;
use digest::{
    crypto_common::{Block, BlockSizeUser, InvalidLength, Key, KeySizeUser},
    Digest, FixedOutput, KeyInit, MacMarker, Output, OutputSizeUser, Update,
};
#[cfg(feature = "reset")]
use digest::{FixedOutputReset, Reset};

/// 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<D: Digest + BlockSizeUser> {
    digest: D,
    opad_key: Block<D>,
    #[cfg(feature = "reset")]
    ipad_key: Block<D>,
}

impl<D: Digest + BlockSizeUser> KeySizeUser for SimpleHmac<D> {
    type KeySize = D::BlockSize;
}

impl<D: Digest + BlockSizeUser> MacMarker for SimpleHmac<D> {}

impl<D: Digest + BlockSizeUser> KeyInit for SimpleHmac<D> {
    fn new(key: &Key<Self>) -> Self {
        Self::new_from_slice(key.as_slice()).unwrap()
    }

    #[inline]
    fn new_from_slice(key: &[u8]) -> Result<Self, InvalidLength> {
        let der_key = get_der_key::<D>(key);
        let mut ipad_key = der_key.clone();
        for b in ipad_key.iter_mut() {
            *b ^= IPAD;
        }
        let mut digest = D::new();
        digest.update(&ipad_key);

        let mut opad_key = der_key;
        for b in opad_key.iter_mut() {
            *b ^= OPAD;
        }

        Ok(Self {
            digest,
            opad_key,
            #[cfg(feature = "reset")]
            ipad_key,
        })
    }
}

impl<D: Digest + BlockSizeUser> Update for SimpleHmac<D> {
    #[inline(always)]
    fn update(&mut self, data: &[u8]) {
        self.digest.update(data);
    }
}

impl<D: Digest + BlockSizeUser> OutputSizeUser for SimpleHmac<D> {
    type OutputSize = D::OutputSize;
}

impl<D: Digest + BlockSizeUser> FixedOutput for SimpleHmac<D> {
    fn finalize_into(self, out: &mut Output<Self>) {
        let mut h = D::new();
        h.update(&self.opad_key);
        h.update(&self.digest.finalize());
        h.finalize_into(out);
    }
}

impl<D: Digest + BlockSizeUser + fmt::Debug> fmt::Debug for SimpleHmac<D> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("SimpleHmac")
            .field("digest", &self.digest)
            // TODO: replace with `finish_non_exhaustive` on MSRV
            // bump to 1.53
            .field("..", &"..")
            .finish()
    }
}

#[cfg(feature = "reset")]
#[cfg_attr(docsrs, doc(cfg(feature = "reset")))]
impl<D: Digest + BlockSizeUser + Reset> Reset for SimpleHmac<D> {
    fn reset(&mut self) {
        Reset::reset(&mut self.digest);
        self.digest.update(&self.ipad_key);
    }
}

#[cfg(feature = "reset")]
#[cfg_attr(docsrs, doc(cfg(feature = "reset")))]
impl<D: Digest + BlockSizeUser + FixedOutputReset> FixedOutputReset for SimpleHmac<D> {
    fn finalize_into_reset(&mut self, out: &mut Output<Self>) {
        let mut h = D::new();
        Update::update(&mut h, &self.opad_key);
        Update::update(&mut h, &self.digest.finalize_reset());
        Update::update(&mut self.digest, &self.ipad_key);
        Digest::finalize_into(h, out);
    }
}