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
use aesni::Aes128;
use byteorder::{BigEndian, ByteOrder};
use clear_on_drop::clear::Clear;
use constant_time_eq::constant_time_eq;
use cmac::Cmac;
use cmac::crypto_mac::Mac;
use challenge::CHALLENGE_SIZE;
use context::Context;
use super::KEY_SIZE;
#[derive(Eq)]
pub struct Cryptogram([u8; CHALLENGE_SIZE]);
impl Cryptogram {
pub fn from_slice(slice: &[u8]) -> Self {
assert_eq!(slice.len(), 8, "cryptogram must be 8-bytes long");
let mut cryptogram = [0u8; CHALLENGE_SIZE];
cryptogram.copy_from_slice(slice);
Cryptogram(cryptogram)
}
pub fn as_slice(&self) -> &[u8] {
&self.0
}
}
impl PartialEq for Cryptogram {
fn eq(&self, other: &Cryptogram) -> bool {
constant_time_eq(&self.0[..], &other.0[..])
}
}
impl Drop for Cryptogram {
fn drop(&mut self) {
self.0.clear();
}
}
pub(crate) fn calculate(
mac_key: &[u8; KEY_SIZE],
derivation_constant: u8,
context: &Context,
output: &mut [u8],
) {
let output_len = output.len();
assert!(
output_len <= 16,
"up to 16-bytes of data supported ({} requested)",
output_len
);
let mut derivation_data = [0u8; 32];
derivation_data[11] = derivation_constant;
derivation_data[12] = 0x00;
BigEndian::write_u16(&mut derivation_data[13..15], (output_len * 8) as u16);
derivation_data[15] = 0x01;
derivation_data[16..].copy_from_slice(context.as_slice());
let mut mac = Cmac::<Aes128>::new_varkey(&mac_key[..]).unwrap();
mac.input(&derivation_data);
output.copy_from_slice(&mac.result().code().as_slice()[..output_len]);
}