zigbee_host/
install_code.rs1use aes::cipher::{Array, BlockCipherEncrypt, KeyInit};
5use aes::Aes128;
6use crc::{Crc, CRC_16_IBM_SDLC};
7use zigbee_primitives::Key;
8
9const CRC: Crc<u16> = Crc::<u16>::new(&CRC_16_IBM_SDLC);
11
12#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
14pub enum InstallCodeError {
15 #[error("install code of {0} bytes: expected 8, 10, 14 or 18 including the CRC")]
17 Length(usize),
18 #[error("install code CRC mismatch")]
20 Crc,
21 #[error("install code is not hex")]
23 Hex,
24}
25
26pub fn parse_hex(text: &str) -> Result<Vec<u8>, InstallCodeError> {
28 let digits: String = text
29 .chars()
30 .filter(|c| !c.is_whitespace() && *c != '-' && *c != ':')
31 .collect();
32 if !digits.len().is_multiple_of(2) {
33 return Err(InstallCodeError::Hex);
34 }
35 (0..digits.len())
36 .step_by(2)
37 .map(|i| {
38 digits
39 .get(i..i + 2)
40 .and_then(|pair| u8::from_str_radix(pair, 16).ok())
41 .ok_or(InstallCodeError::Hex)
42 })
43 .collect()
44}
45
46pub fn link_key(code_with_crc: &[u8]) -> Result<Key, InstallCodeError> {
49 if !matches!(code_with_crc.len(), 8 | 10 | 14 | 18) {
50 return Err(InstallCodeError::Length(code_with_crc.len()));
51 }
52 let (code, crc) = code_with_crc.split_at(code_with_crc.len() - 2);
53 let wanted = match crc {
54 [lo, hi] => u16::from_le_bytes([*lo, *hi]),
55 _ => return Err(InstallCodeError::Length(code_with_crc.len())),
56 };
57 if CRC.checksum(code) != wanted {
58 return Err(InstallCodeError::Crc);
59 }
60 Ok(Key(aes_mmo_hash(code_with_crc)))
61}
62
63pub fn aes_mmo_hash(message: &[u8]) -> [u8; 16] {
66 let bit_len = (message.len() as u64 * 8) as u16;
67 let mut padded = message.to_vec();
68 padded.push(0x80);
69 while padded.len() % 16 != 14 {
70 padded.push(0x00);
71 }
72 padded.extend_from_slice(&bit_len.to_be_bytes());
73
74 let mut hash = [0u8; 16];
75 for chunk in padded.as_chunks::<16>().0 {
76 let cipher = Aes128::new(&Array::from(hash));
77 let block = *chunk;
78 let mut out = Array::from(block);
79 cipher.encrypt_block(&mut out);
80 for (h, (o, m)) in hash.iter_mut().zip(out.iter().zip(block.iter())) {
81 *h = o ^ m;
82 }
83 }
84 hash
85}
86
87#[cfg(test)]
88mod tests {
89 use super::*;
90
91 #[test]
92 fn derives_the_published_test_vector() {
93 let code = parse_hex("83FED3407A939723A5C639B26916D505C3B5").unwrap();
95 let key = link_key(&code).unwrap();
96 assert_eq!(key.to_hex(), "66b6900981e1ee3ca4206b6b861c02bb");
97 }
98
99 #[test]
100 fn rejects_bad_codes() {
101 let mut code = parse_hex("83FED3407A939723A5C639B26916D505C3B5").unwrap();
102 code[0] ^= 1;
103 assert_eq!(link_key(&code), Err(InstallCodeError::Crc));
104 assert_eq!(link_key(&[1, 2, 3]), Err(InstallCodeError::Length(3)));
105 assert_eq!(parse_hex("zz"), Err(InstallCodeError::Hex));
106 }
107}