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
use tink_core::TinkError;
use tink_proto::HashType;
const MIN_HKDF_KEY_SIZE_IN_BYTES: usize = 32;
#[derive(Clone)]
pub struct HkdfPrf {
prk: HkdfPrfVariant,
}
#[allow(clippy::large_enum_variant)]
#[derive(Clone)]
enum HkdfPrfVariant {
Sha1(hkdf::Hkdf<sha1::Sha1>),
Sha256(hkdf::Hkdf<sha2::Sha256>),
Sha512(hkdf::Hkdf<sha2::Sha512>),
}
impl HkdfPrf {
pub fn new(hash_alg: HashType, key: &[u8], salt: &[u8]) -> Result<HkdfPrf, TinkError> {
let prk = match hash_alg {
HashType::Sha1 => HkdfPrfVariant::Sha1(hkdf::Hkdf::<sha1::Sha1>::new(Some(salt), key)),
HashType::Sha256 => {
HkdfPrfVariant::Sha256(hkdf::Hkdf::<sha2::Sha256>::new(Some(salt), key))
}
HashType::Sha512 => {
HkdfPrfVariant::Sha512(hkdf::Hkdf::<sha2::Sha512>::new(Some(salt), key))
}
h => return Err(format!("HkdfPrf: unsupported hash {:?}", h).into()),
};
Ok(HkdfPrf { prk })
}
}
pub fn validate_hkdf_prf_params(
hash: HashType,
key_size: usize,
_salt: &[u8],
) -> Result<(), TinkError> {
if key_size < MIN_HKDF_KEY_SIZE_IN_BYTES {
Err("key too short".into())
} else if tink_core::subtle::get_hash_func(hash).is_none() {
Err("invalid hash function".into())
} else if hash != HashType::Sha256 && hash != HashType::Sha512 {
Err("Only SHA-256 and SHA-512 currently allowed for HKDF".into())
} else {
Ok(())
}
}
impl tink_core::Prf for HkdfPrf {
fn compute_prf(&self, data: &[u8], out_len: usize) -> Result<Vec<u8>, TinkError> {
match &self.prk {
HkdfPrfVariant::Sha1(prk) => compute_hkdf_with::<sha1::Sha1>(prk, data, out_len),
HkdfPrfVariant::Sha256(prk) => compute_hkdf_with::<sha2::Sha256>(prk, data, out_len),
HkdfPrfVariant::Sha512(prk) => compute_hkdf_with::<sha2::Sha512>(prk, data, out_len),
}
}
}
fn compute_hkdf_with<D>(
prk: &hkdf::Hkdf<D>,
data: &[u8],
out_len: usize,
) -> Result<Vec<u8>, TinkError>
where
D: digest::Update + digest::BlockInput + digest::FixedOutput + digest::Reset + Default + Clone,
{
let mut okm = vec![0; out_len];
prk.expand(data, &mut okm)
.map_err(|_| TinkError::new("HkdfPrf: compute of hkdf failed"))?;
Ok(okm)
}