hkdf/
sealed.rs

1use hmac::digest::{
2    block_buffer::Eager,
3    core_api::{
4        BlockSizeUser, BufferKindUser, CoreProxy, CoreWrapper, FixedOutputCore, OutputSizeUser,
5        UpdateCore,
6    },
7    generic_array::typenum::{IsLess, Le, NonZero, U256},
8    Digest, FixedOutput, HashMarker, KeyInit, Output, Update,
9};
10use hmac::{Hmac, HmacCore, SimpleHmac};
11
12pub trait Sealed<H: OutputSizeUser> {
13    type Core: Clone;
14
15    fn new_from_slice(key: &[u8]) -> Self;
16
17    fn new_core(key: &[u8]) -> Self::Core;
18
19    fn from_core(core: &Self::Core) -> Self;
20
21    fn update(&mut self, data: &[u8]);
22
23    fn finalize(self) -> Output<H>;
24}
25
26impl<H> Sealed<H> for Hmac<H>
27where
28    H: CoreProxy + OutputSizeUser,
29    H::Core: HashMarker
30        + UpdateCore
31        + FixedOutputCore
32        + BufferKindUser<BufferKind = Eager>
33        + Default
34        + Clone,
35    <H::Core as BlockSizeUser>::BlockSize: IsLess<U256>,
36    Le<<H::Core as BlockSizeUser>::BlockSize, U256>: NonZero,
37{
38    type Core = HmacCore<H>;
39
40    #[inline(always)]
41    fn new_from_slice(key: &[u8]) -> Self {
42        KeyInit::new_from_slice(key).expect("HMAC can take a key of any size")
43    }
44
45    #[inline(always)]
46    fn new_core(key: &[u8]) -> Self::Core {
47        HmacCore::new_from_slice(key).expect("HMAC can take a key of any size")
48    }
49
50    #[inline(always)]
51    fn from_core(core: &Self::Core) -> Self {
52        CoreWrapper::from_core(core.clone())
53    }
54
55    #[inline(always)]
56    fn update(&mut self, data: &[u8]) {
57        Update::update(self, data);
58    }
59
60    #[inline(always)]
61    fn finalize(self) -> Output<H> {
62        // Output<H> and Output<H::Core> are always equal to each other,
63        // but we can not prove it at type level
64        Output::<H>::clone_from_slice(&self.finalize_fixed())
65    }
66}
67
68impl<H: Digest + BlockSizeUser + Clone> Sealed<H> for SimpleHmac<H> {
69    type Core = Self;
70
71    #[inline(always)]
72    fn new_from_slice(key: &[u8]) -> Self {
73        KeyInit::new_from_slice(key).expect("HMAC can take a key of any size")
74    }
75
76    #[inline(always)]
77    fn new_core(key: &[u8]) -> Self::Core {
78        KeyInit::new_from_slice(key).expect("HMAC can take a key of any size")
79    }
80
81    #[inline(always)]
82    fn from_core(core: &Self::Core) -> Self {
83        core.clone()
84    }
85
86    #[inline(always)]
87    fn update(&mut self, data: &[u8]) {
88        Update::update(self, data);
89    }
90
91    #[inline(always)]
92    fn finalize(self) -> Output<H> {
93        // Output<H> and Output<H::Core> are always equal to each other,
94        // but we can not prove it at type level
95        Output::<H>::clone_from_slice(&self.finalize_fixed())
96    }
97}