1use core::fmt;
22
23use aes::Aes128;
24use aes::cipher::generic_array::GenericArray;
25use aes::cipher::{BlockDecryptMut, BlockEncryptMut, KeyInit, KeyIvInit, StreamCipher};
26use cmac::{Cmac, Mac};
27use zeroize::Zeroize;
28
29use crate::app::Address;
30use crate::{Check, Error, Result};
31
32#[derive(Clone)]
34pub struct Key([u8; 16]);
35
36impl Drop for Key {
37 fn drop(&mut self) {
38 self.0.zeroize();
39 }
40}
41
42impl Key {
43 pub const fn new(bytes: [u8; 16]) -> Self {
45 Self(bytes)
46 }
47
48 pub fn from_hex(text: &str) -> Option<Self> {
52 let mut key = Self([0; 16]);
53 let mut n = 0usize;
54 let mut high: Option<u8> = None;
55 for c in text.bytes().filter(|c| !c.is_ascii_whitespace()) {
56 let v = match c {
57 b'0'..=b'9' => c - b'0',
58 b'a'..=b'f' => c - b'a' + 10,
59 b'A'..=b'F' => c - b'A' + 10,
60 _ => return None,
61 };
62 match high.take() {
63 None => high = Some(v),
64 Some(h) => {
65 *key.0.get_mut(n)? = (h << 4) | v;
66 n += 1;
67 }
68 }
69 }
70 (n == 16 && high.is_none()).then_some(key)
71 }
72
73 pub(crate) const fn bytes(&self) -> &[u8; 16] {
74 &self.0
75 }
76}
77
78impl fmt::Debug for Key {
79 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
81 f.write_str("Key(..)")
82 }
83}
84
85impl From<[u8; 16]> for Key {
86 fn from(bytes: [u8; 16]) -> Self {
87 Self(bytes)
88 }
89}
90
91pub trait Keys {
93 fn key(&self, meter: &Address) -> Option<&Key>;
95}
96
97impl Keys for Key {
99 fn key(&self, _: &Address) -> Option<&Key> {
100 Some(self)
101 }
102}
103
104impl Keys for [(Address, Key)] {
107 fn key(&self, meter: &Address) -> Option<&Key> {
108 self.iter().find(|(a, _)| a.manufacturer == meter.manufacturer && a.id == meter.id).map(|(_, k)| k)
109 }
110}
111
112impl<const N: usize> Keys for [(Address, Key); N] {
113 fn key(&self, meter: &Address) -> Option<&Key> {
114 self.as_slice().key(meter)
115 }
116}
117
118impl<K: Keys + ?Sized> Keys for &K {
119 fn key(&self, meter: &Address) -> Option<&Key> {
120 (**self).key(meter)
121 }
122}
123
124pub(crate) fn cbc_decrypt(key: &Key, iv: &[u8; 16], data: &mut [u8]) -> Result<()> {
126 if data.len() % 16 != 0 {
127 return Err(Error::Verification(Check::Length));
128 }
129 let mut cipher = cbc::Decryptor::<Aes128>::new(key.bytes().into(), iv.into());
130 for block in data.chunks_exact_mut(16) {
131 cipher.decrypt_block_mut(GenericArray::from_mut_slice(block));
132 }
133 Ok(())
134}
135
136pub(crate) fn cbc_encrypt(key: &Key, iv: &[u8; 16], data: &mut [u8]) -> Result<()> {
138 if data.len() % 16 != 0 {
139 return Err(Error::InvalidLength);
140 }
141 let mut cipher = cbc::Encryptor::<Aes128>::new(key.bytes().into(), iv.into());
142 for block in data.chunks_exact_mut(16) {
143 cipher.encrypt_block_mut(GenericArray::from_mut_slice(block));
144 }
145 Ok(())
146}
147
148pub(crate) fn ccm_encrypt(key: &Key, nonce: &[u8; 13], aad: &[u8], data: &mut [u8]) -> Result<[u8; 8]> {
150 use ccm::aead::AeadInPlace;
151 use ccm::consts::{U8, U13};
152 let cipher = ccm::Ccm::<Aes128, U8, U13>::new(key.bytes().into());
153 let tag = cipher.encrypt_in_place_detached(nonce.into(), aad, data).map_err(|_| Error::InvalidLength)?;
154 Ok(tag.into())
155}
156
157pub(crate) fn ccm_decrypt(
160 key: &Key,
161 nonce: &[u8; 13],
162 aad: &[u8],
163 data: &mut [u8],
164 tag: &[u8],
165) -> Result<()> {
166 use ccm::aead::AeadInPlace;
167 use ccm::consts::{U8, U13};
168 let tag: &[u8; 8] = tag.try_into().map_err(|_| Error::UnsupportedSecurity(10))?;
169 let cipher = ccm::Ccm::<Aes128, U8, U13>::new(key.bytes().into());
170 cipher.decrypt_in_place_detached(nonce.into(), aad, data, tag.into()).map_err(|_| {
171 data.zeroize();
172 Error::Verification(Check::Tag)
173 })
174}
175
176pub(crate) fn ctr_apply(key: &Key, iv: &[u8; 16], data: &mut [u8]) {
178 ctr::Ctr128BE::<Aes128>::new(key.bytes().into(), iv.into()).apply_keystream(data);
179}
180
181pub(crate) fn cmac(key: &Key, parts: &[&[u8]]) -> [u8; 16] {
183 let mut mac = <Cmac<Aes128> as KeyInit>::new(key.bytes().into());
184 for p in parts {
185 mac.update(p);
186 }
187 mac.finalize().into_bytes().into()
188}
189
190pub(crate) fn mac_matches(computed: &[u8], received: &[u8]) -> bool {
192 computed.len() == received.len()
193 && computed.iter().zip(received).fold(0u8, |acc, (x, y)| acc | (x ^ y)) == 0
194}
195
196pub(crate) fn derive(key: &Key, d: u8, counter: [u8; 4], id: [u8; 4]) -> Key {
200 let [c0, c1, c2, c3] = counter;
201 let [i0, i1, i2, i3] = id;
202 let input = [d, c0, c1, c2, c3, i0, i1, i2, i3, 7, 7, 7, 7, 7, 7, 7];
203 let mut derived = cmac(key, &[&input]);
204 let k = Key(derived);
205 derived.zeroize();
206 k
207}
208
209#[cfg(test)]
210mod tests {
211 extern crate std;
212 use super::*;
213 use std::format;
214
215 #[test]
216 fn keys_never_print() {
217 let k = Key::from_hex("01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F 11").unwrap();
218 assert_eq!(format!("{k:?}"), "Key(..)");
219 assert_eq!(k.bytes()[15], 0x11);
220 assert!(Key::from_hex("0102").is_none());
221 assert!(Key::from_hex("zz02030405060708090A0B0C0D0E0F11").is_none());
222 assert!(Key::from_hex("0102030405060708090A0B0C0D0E0F1122").is_none());
223 }
224
225 #[test]
226 fn cmac_matches_rfc_4493() {
227 let k = Key::from_hex("2b7e151628aed2a6abf7158809cf4f3c").unwrap();
229 let m =
230 [0x6b, 0xc1, 0xbe, 0xe2, 0x2e, 0x40, 0x9f, 0x96, 0xe9, 0x3d, 0x7e, 0x11, 0x73, 0x93, 0x17, 0x2a];
231 let t = cmac(&k, &[&m[..8], &m[8..]]);
232 assert_eq!(
233 t,
234 [0x07, 0x0a, 0x16, 0xb4, 0x6b, 0x4d, 0x41, 0x44, 0xf7, 0x9b, 0xdd, 0x9d, 0xd0, 0x4a, 0x28, 0x7c]
235 );
236 }
237}