1use aes::cipher::{BlockCipherEncrypt, KeyInit};
8use aes::Aes128;
9use ccm::aead::{Aead, Payload};
10use ccm::consts::{U13, U4, U8};
11use cmac::Mac;
12
13pub type Key = [u8; 16];
15
16pub fn e(key: &Key, block: &[u8; 16]) -> [u8; 16] {
18 let mut b = aes::Block::from(*block);
19 Aes128::new(&(*key).into()).encrypt_block(&mut b);
20 b.into()
21}
22
23pub fn cmac(key: &Key, msg: &[u8]) -> Key {
25 let mut m = <cmac::Cmac<Aes128> as KeyInit>::new(&(*key).into());
26 m.update(msg);
27 m.finalize().into_bytes().into()
28}
29
30pub fn s1(m: &[u8]) -> Key {
32 cmac(&[0; 16], m)
33}
34
35pub fn k1(n: &[u8], salt: &Key, p: &[u8]) -> Key {
37 let t = cmac(salt, n);
38 cmac(&t, p)
39}
40
41#[derive(Debug, Clone, Copy, PartialEq, Eq)]
43pub struct NetworkMaterial {
44 pub nid: u8,
46 pub encryption_key: Key,
48 pub privacy_key: Key,
50}
51
52pub fn k2(n: &Key, p: &[u8]) -> NetworkMaterial {
56 let salt = s1(b"smk2");
57 let t = cmac(&salt, n);
58 let mut m = Vec::with_capacity(p.len() + 17);
59 m.extend_from_slice(p);
60 m.push(1);
61 let t1 = cmac(&t, &m);
62 m.clear();
63 m.extend_from_slice(&t1);
64 m.extend_from_slice(p);
65 m.push(2);
66 let t2 = cmac(&t, &m);
67 m.clear();
68 m.extend_from_slice(&t2);
69 m.extend_from_slice(p);
70 m.push(3);
71 let t3 = cmac(&t, &m);
72 NetworkMaterial {
73 nid: t1[15] & 0x7f,
74 encryption_key: t2,
75 privacy_key: t3,
76 }
77}
78
79pub fn k3(n: &Key) -> [u8; 8] {
81 let t = cmac(&s1(b"smk3"), n);
82 let r = cmac(&t, b"id64\x01");
83 let mut out = [0u8; 8];
84 out.copy_from_slice(&r[8..]);
85 out
86}
87
88pub fn k4(n: &Key) -> u8 {
90 let t = cmac(&s1(b"smk4"), n);
91 cmac(&t, b"id6\x01")[15] & 0x3f
92}
93
94pub fn identity_key(net_key: &Key) -> Key {
96 k1(net_key, &s1(b"nkik"), b"id128\x01")
97}
98
99pub fn beacon_key(net_key: &Key) -> Key {
101 k1(net_key, &s1(b"nkbk"), b"id128\x01")
102}
103
104pub fn device_key(ecdh_secret: &[u8; 32], provisioning_salt: &Key) -> Key {
106 k1(ecdh_secret, provisioning_salt, b"prdk")
107}
108
109pub fn ccm_encrypt(
111 key: &Key,
112 nonce: &[u8; 13],
113 aad: &[u8],
114 plain: &[u8],
115 mic_len: usize,
116) -> Vec<u8> {
117 let p = Payload { msg: plain, aad };
118 let r = if mic_len == 8 {
119 ccm::Ccm::<Aes128, U8, U13>::new(&(*key).into()).encrypt(nonce.into(), p)
120 } else {
121 ccm::Ccm::<Aes128, U4, U13>::new(&(*key).into()).encrypt(nonce.into(), p)
122 };
123 r.unwrap_or_default()
125}
126
127pub fn ccm_decrypt(
129 key: &Key,
130 nonce: &[u8; 13],
131 aad: &[u8],
132 sealed: &[u8],
133 mic_len: usize,
134) -> Option<Vec<u8>> {
135 if sealed.len() < mic_len {
136 return None;
137 }
138 let p = Payload { msg: sealed, aad };
139 if mic_len == 8 {
140 ccm::Ccm::<Aes128, U8, U13>::new(&(*key).into())
141 .decrypt(nonce.into(), p)
142 .ok()
143 } else {
144 ccm::Ccm::<Aes128, U4, U13>::new(&(*key).into())
145 .decrypt(nonce.into(), p)
146 .ok()
147 }
148}
149
150#[cfg(test)]
151mod tests {
152 use super::*;
153
154 fn h<const N: usize>(s: &str) -> [u8; N] {
155 hex::decode(s.replace(' ', "")).unwrap().try_into().unwrap()
156 }
157
158 #[test]
160 fn s1_sample() {
161 assert_eq!(s1(b"test"), h::<16>("b73cefbd641ef2ea598c2b6efb62f79c"));
162 }
163
164 #[test]
165 fn k1_sample() {
166 let n: [u8; 16] = h("3216d1509884b533248541792b877f98");
167 let salt: [u8; 16] = h("2ba14ffa0df84a2831938d57d276cab4");
168 let p: [u8; 16] = h("5a09d60797eeb4478aada59db3352a0d");
169 assert_eq!(
170 k1(&n, &salt, &p),
171 h::<16>("f6ed15a8934afbe7d83e8dcb57fcf5d7")
172 );
173 }
174
175 #[test]
176 fn k2_master_sample() {
177 let m = k2(&h("f7a2a44f8e8a8029064f173ddc1e2b00"), &[0]);
178 assert_eq!(m.nid, 0x7f);
179 assert_eq!(
180 m.encryption_key,
181 h::<16>("9f589181a0f50de73c8070c7a6d27f46")
182 );
183 assert_eq!(m.privacy_key, h::<16>("4c715bd4a64b938f99b453351653124f"));
184 }
185
186 #[test]
187 fn k3_k4_samples() {
188 assert_eq!(
189 k3(&h("f7a2a44f8e8a8029064f173ddc1e2b00")),
190 h::<8>("ff046958233db014")
191 );
192 assert_eq!(k4(&h("3216d1509884b533248541792b877f98")), 0x38);
193 }
194
195 #[test]
196 fn ccm_round_trip_and_tamper() {
197 let k = [7u8; 16];
198 let n = [1u8; 13];
199 for mic in [4, 8] {
200 let c = ccm_encrypt(&k, &n, b"", b"hello mesh", mic);
201 assert_eq!(c.len(), 10 + mic);
202 assert_eq!(ccm_decrypt(&k, &n, b"", &c, mic).unwrap(), b"hello mesh");
203 let mut bad = c.clone();
204 bad[0] ^= 1;
205 assert!(ccm_decrypt(&k, &n, b"", &bad, mic).is_none());
206 }
207 assert!(ccm_decrypt(&k, &n, b"", &[1, 2], 4).is_none());
208 }
209}