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
#![no_std]
#![warn(rust_2018_idioms)]
#[cfg(feature = "std")]
extern crate std;
use core::fmt;
use digest::generic_array::{self, ArrayLength, GenericArray};
use digest::{BlockInput, FixedOutput, Reset, Update};
use hmac::{Hmac, Mac, NewMac};
#[derive(Copy, Clone, Eq, PartialEq, Debug)]
pub struct InvalidPrkLength;
#[derive(Copy, Clone, Eq, PartialEq, Debug)]
pub struct InvalidLength;
#[derive(Clone)]
pub struct HkdfExtract<D>
where
D: Update + BlockInput + FixedOutput + Reset + Default + Clone,
D::BlockSize: ArrayLength<u8>,
D::OutputSize: ArrayLength<u8>,
{
hmac: Hmac<D>,
}
impl<D> HkdfExtract<D>
where
D: Update + BlockInput + FixedOutput + Reset + Default + Clone,
D::BlockSize: ArrayLength<u8>,
D::OutputSize: ArrayLength<u8>,
{
pub fn new(salt: Option<&[u8]>) -> HkdfExtract<D> {
let hmac = match salt {
Some(s) => Hmac::<D>::new_varkey(s).expect("HMAC can take a key of any size"),
None => Hmac::<D>::new(&Default::default()),
};
HkdfExtract { hmac }
}
pub fn input_ikm(&mut self, ikm: &[u8]) {
self.hmac.update(ikm);
}
pub fn finalize(self) -> (GenericArray<u8, D::OutputSize>, Hkdf<D>) {
let prk = self.hmac.finalize().into_bytes();
let hkdf = Hkdf::from_prk(&prk).expect("PRK size is correct");
(prk, hkdf)
}
}
#[derive(Clone)]
pub struct Hkdf<D>
where
D: Update + BlockInput + FixedOutput + Reset + Default + Clone,
D::BlockSize: ArrayLength<u8>,
D::OutputSize: ArrayLength<u8>,
{
hmac: Hmac<D>,
}
impl<D> Hkdf<D>
where
D: Update + BlockInput + FixedOutput + Reset + Default + Clone,
D::BlockSize: ArrayLength<u8>,
D::OutputSize: ArrayLength<u8>,
{
pub fn new(salt: Option<&[u8]>, ikm: &[u8]) -> Hkdf<D> {
let (_, hkdf) = Hkdf::extract(salt, ikm);
hkdf
}
pub fn from_prk(prk: &[u8]) -> Result<Hkdf<D>, InvalidPrkLength> {
use crate::generic_array::typenum::Unsigned;
if prk.len() < D::OutputSize::to_usize() {
return Err(InvalidPrkLength);
}
Ok(Hkdf {
hmac: Hmac::new_varkey(prk).expect("HMAC can take a key of any size"),
})
}
pub fn extract(salt: Option<&[u8]>, ikm: &[u8]) -> (GenericArray<u8, D::OutputSize>, Hkdf<D>) {
let mut extract_ctx = HkdfExtract::new(salt);
extract_ctx.input_ikm(ikm);
extract_ctx.finalize()
}
pub fn expand_multi_info(
&self,
info_components: &[&[u8]],
okm: &mut [u8],
) -> Result<(), InvalidLength> {
use crate::generic_array::typenum::Unsigned;
let mut prev: Option<GenericArray<u8, <D as digest::FixedOutput>::OutputSize>> = None;
let hmac_output_bytes = D::OutputSize::to_usize();
if okm.len() > hmac_output_bytes * 255 {
return Err(InvalidLength);
}
let mut hmac = self.hmac.clone();
for (blocknum, okm_block) in okm.chunks_mut(hmac_output_bytes).enumerate() {
let block_len = okm_block.len();
if let Some(ref prev) = prev {
hmac.update(prev)
};
for info in info_components {
hmac.update(info);
}
hmac.update(&[blocknum as u8 + 1]);
let output = hmac.finalize_reset().into_bytes();
okm_block.copy_from_slice(&output[..block_len]);
prev = Some(output);
}
Ok(())
}
pub fn expand(&self, info: &[u8], okm: &mut [u8]) -> Result<(), InvalidLength> {
self.expand_multi_info(&[info], okm)
}
}
impl fmt::Display for InvalidPrkLength {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
f.write_str("invalid pseudorandom key length, too short")
}
}
#[cfg(feature = "std")]
impl ::std::error::Error for InvalidPrkLength {}
impl fmt::Display for InvalidLength {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
f.write_str("invalid number of blocks, too large output")
}
}
#[cfg(feature = "std")]
impl ::std::error::Error for InvalidLength {}