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
use crate::constants::{
HeaderIntegrityHmacAlgorithm, HeaderIntegrityMacSize, HEADER_INTEGRITY_MAC_SIZE,
};
use crate::crypto;
use crate::header::keys::HeaderIntegrityMacKey;
use digest::generic_array::GenericArray;
use subtle::{Choice, ConstantTimeEq};
#[derive(Clone, Debug)]
pub struct HeaderIntegrityMac(GenericArray<u8, HeaderIntegrityMacSize>);
impl HeaderIntegrityMac {
pub(crate) fn compute(key: HeaderIntegrityMacKey, header_data: &[u8]) -> Self {
let routing_info_mac =
crypto::compute_keyed_hmac::<HeaderIntegrityHmacAlgorithm>(&key, header_data);
let mac_bytes = routing_info_mac.into_bytes();
if mac_bytes.len() < HEADER_INTEGRITY_MAC_SIZE {
panic!("Algorithm used for computing header integrity mac produced output smaller than minimum length of {}", HEADER_INTEGRITY_MAC_SIZE)
}
Self(
mac_bytes
.into_iter()
.take(HEADER_INTEGRITY_MAC_SIZE)
.collect(),
)
}
pub fn verify(
&self,
integrity_mac_key: HeaderIntegrityMacKey,
enc_routing_info: &[u8],
) -> bool {
let recomputed_integrity_mac = Self::compute(integrity_mac_key, enc_routing_info);
self.ct_eq(&recomputed_integrity_mac).into()
}
pub fn into_inner(self) -> GenericArray<u8, HeaderIntegrityMacSize> {
self.0
}
pub fn as_bytes(&self) -> &[u8] {
&self.0
}
pub fn from_bytes(bytes: [u8; HEADER_INTEGRITY_MAC_SIZE]) -> Self {
Self(bytes.into())
}
}
impl ConstantTimeEq for HeaderIntegrityMac {
fn ct_eq(&self, other: &Self) -> Choice {
self.0.ct_eq(&other.0)
}
}
#[cfg(test)]
mod computing_integrity_mac {
use super::*;
use crate::constants::INTEGRITY_MAC_KEY_SIZE;
use crate::header::routing::ENCRYPTED_ROUTING_INFO_SIZE;
#[test]
fn it_is_possible_to_verify_correct_mac() {
let key = [2u8; INTEGRITY_MAC_KEY_SIZE];
let data = vec![3u8; ENCRYPTED_ROUTING_INFO_SIZE];
let integrity_mac = HeaderIntegrityMac::compute(key, &data);
assert!(integrity_mac.verify(key, &data));
}
#[test]
fn it_lets_detecting_flipped_data_bits() {
let key = [2u8; INTEGRITY_MAC_KEY_SIZE];
let mut data = vec![3u8; ENCRYPTED_ROUTING_INFO_SIZE];
let integrity_mac = HeaderIntegrityMac::compute(key, &data);
data[10] = !data[10];
assert!(!integrity_mac.verify(key, &data));
}
}