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
use crate::{utils::wrap_err, TinkError};
use tink_proto::HashType;
const MIN_TAG_SIZE_IN_BYTES: usize = 10;
fn validate_hkdf_params(
hash: HashType,
_key_size: usize,
tag_size: usize,
) -> Result<(), crate::TinkError> {
let digest_size = super::get_hash_digest_size(hash)?;
if tag_size > 255 * digest_size {
Err("tag size too big".into())
} else if tag_size < MIN_TAG_SIZE_IN_BYTES {
Err("tag size too small".into())
} else {
Ok(())
}
}
pub fn compute_hkdf(
hash_alg: HashType,
key: &[u8],
salt: &[u8],
info: &[u8],
tag_size: usize,
) -> Result<Vec<u8>, crate::TinkError> {
let key_size = key.len();
validate_hkdf_params(hash_alg, key_size, tag_size).map_err(|e| wrap_err("hkdf", e))?;
match hash_alg {
HashType::Sha1 => compute_hkdf_with::<sha1::Sha1>(key, salt, info, tag_size),
HashType::Sha256 => compute_hkdf_with::<sha2::Sha256>(key, salt, info, tag_size),
HashType::Sha384 => compute_hkdf_with::<sha2::Sha384>(key, salt, info, tag_size),
HashType::Sha512 => compute_hkdf_with::<sha2::Sha512>(key, salt, info, tag_size),
h => Err(format!("hkdf: unsupported hash {:?}", h).into()),
}
}
fn compute_hkdf_with<D>(
key: &[u8],
salt: &[u8],
info: &[u8],
tag_size: usize,
) -> Result<Vec<u8>, crate::TinkError>
where
D: digest::Update + digest::BlockInput + digest::FixedOutput + digest::Reset + Default + Clone,
{
let prk = hkdf::Hkdf::<D>::new(Some(salt), key);
let mut okm = vec![0; tag_size];
prk.expand(info, &mut okm)
.map_err(|_| TinkError::new("compute of hkdf failed"))?;
Ok(okm)
}