1//! Mid-level cryptographic operations used in the onion service protocol.
2use tor_llcrypto::d::Sha3_256;
3use tor_llcrypto::util::ct::CtByteArray;
45use digest::Digest;
67/// The length of the MAC returned by [`hs_mac`].
8pub const HS_MAC_LEN: usize = 32;
910/// Compute the lightweight MAC function used in the onion service protocol.
11///
12/// (See rend-spec-v3 section 0.3 `MAC`.)
13///
14/// This is not a great MAC; KMAC wasn't defined at the time that the HSv3
15/// design was written. Please don't use this MAC in new protocols.
16pub fn hs_mac(key: &[u8], msg: &[u8]) -> CtByteArray<HS_MAC_LEN> {
17// rend-spec-v3 says: "Instantiate H with SHA3-256... Instantiate MAC(key=k,
18 // message=m) with H(k_len | k | m), where k_len is htonll(len(k))."
1920let mut hasher = Sha3_256::new();
21let klen = key.len() as u64;
22 hasher.update(klen.to_be_bytes());
23 hasher.update(key);
24 hasher.update(msg);
25let a: [u8; HS_MAC_LEN] = hasher.finalize().into();
26 a.into()
27}
2829/// Reference to a slice of bytes usable to compute the [`hs_mac`] function.
30#[derive(Copy, Clone, derive_more::From)]
31pub struct HsMacKey<'a>(&'a [u8]);
3233impl<'a> tor_llcrypto::traits::ShortMac<HS_MAC_LEN> for HsMacKey<'a> {
34fn mac(&self, input: &[u8]) -> CtByteArray<HS_MAC_LEN> {
35 hs_mac(self.0, input)
36 }
3738fn validate(&self, input: &[u8], mac: &[u8; HS_MAC_LEN]) -> subtle::Choice {
39use subtle::ConstantTimeEq;
40let m = hs_mac(self.0, input);
41 m.as_ref().ct_eq(mac)
42 }
43}
4445#[cfg(test)]
46mod test {
47// @@ begin test lint list maintained by maint/add_warning @@
48#![allow(clippy::bool_assert_comparison)]
49 #![allow(clippy::clone_on_copy)]
50 #![allow(clippy::dbg_macro)]
51 #![allow(clippy::mixed_attributes_style)]
52 #![allow(clippy::print_stderr)]
53 #![allow(clippy::print_stdout)]
54 #![allow(clippy::single_char_pattern)]
55 #![allow(clippy::unwrap_used)]
56 #![allow(clippy::unchecked_duration_subtraction)]
57 #![allow(clippy::useless_vec)]
58 #![allow(clippy::needless_pass_by_value)]
59//! <!-- @@ end test lint list maintained by maint/add_warning @@ -->
6061use super::*;
62use hex_literal::hex;
6364/// Helper: just call Sha3_256 and return the result as a CtByteArray.
65fn d(s: &[u8]) -> CtByteArray<32> {
66let a: [u8; 32] = Sha3_256::digest(s).into();
67 a.into()
68 }
6970#[test]
71fn mac_from_definition() {
72assert_eq!(hs_mac(b"", b""), d(&[0; 8]));
73assert_eq!(
74 hs_mac(b"hello", b"world"),
75 d(b"\0\0\0\0\0\0\0\x05helloworld")
76 );
77assert_eq!(
78 hs_mac(b"helloworl", b"d"),
79 d(b"\0\0\0\0\0\0\0\x09helloworld")
80 );
81 }
8283#[test]
84fn mac_testvec() {
85// From C Tor; originally generated in Python.
86let msg = b"i am in a library somewhere using my computer";
87let key = b"i'm from the past talking to the future.";
8889assert_eq!(
90 hs_mac(key, msg).as_ref(),
91&hex!("753fba6d87d49497238a512a3772dd291e55f7d1cd332c9fb5c967c7a10a13ca")
92 );
93 }
94}