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
use tink_core::{utils::wrap_err, Prf, TinkError};
use tink_proto::HashType;
const MIN_KEY_SIZE_IN_BYTES: usize = 16;
const MIN_TAG_SIZE_IN_BYTES: usize = 10;
#[derive(Clone)]
pub struct Hmac {
prf: tink_prf::subtle::HmacPrf,
tag_size: usize,
}
impl Hmac {
pub fn new(hash_alg: HashType, key: &[u8], tag_size: usize) -> Result<Self, TinkError> {
let key_size = key.len();
if let Err(e) = validate_hmac_params(hash_alg, key_size, tag_size) {
return Err(wrap_err("Hmac", e));
}
let prf = tink_prf::subtle::HmacPrf::new(hash_alg, key)?;
Ok(Hmac { prf, tag_size })
}
}
pub fn validate_hmac_params(
hash: HashType,
key_size: usize,
tag_size: usize,
) -> Result<(), TinkError> {
let digest_size = tink_core::subtle::get_hash_digest_size(hash)?;
if tag_size > digest_size {
return Err("tag size too big".into());
}
if tag_size < MIN_TAG_SIZE_IN_BYTES {
return Err("tag size too small".into());
}
if key_size < MIN_KEY_SIZE_IN_BYTES {
return Err("key too short".into());
}
Ok(())
}
impl tink_core::Mac for Hmac {
fn compute_mac(&self, data: &[u8]) -> Result<Vec<u8>, TinkError> {
self.prf.compute_prf(data, self.tag_size)
}
}