1use core::fmt;
22
23use aes::Aes128;
24use aes::cipher::generic_array::GenericArray;
25use aes::cipher::{BlockDecryptMut, 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 ccm_decrypt(
139 key: &Key,
140 nonce: &[u8; 13],
141 aad: &[u8],
142 data: &mut [u8],
143 tag: &[u8],
144) -> Result<()> {
145 use ccm::aead::AeadInPlace;
146 use ccm::consts::{U8, U13};
147 let tag: &[u8; 8] = tag.try_into().map_err(|_| Error::UnsupportedSecurity(10))?;
148 let cipher = ccm::Ccm::<Aes128, U8, U13>::new(key.bytes().into());
149 cipher.decrypt_in_place_detached(nonce.into(), aad, data, tag.into()).map_err(|_| {
150 data.zeroize();
151 Error::Verification(Check::Tag)
152 })
153}
154
155pub(crate) fn ctr_apply(key: &Key, iv: &[u8; 16], data: &mut [u8]) {
157 ctr::Ctr128BE::<Aes128>::new(key.bytes().into(), iv.into()).apply_keystream(data);
158}
159
160pub(crate) fn cmac(key: &Key, parts: &[&[u8]]) -> [u8; 16] {
162 let mut mac = <Cmac<Aes128> as KeyInit>::new(key.bytes().into());
163 for p in parts {
164 mac.update(p);
165 }
166 mac.finalize().into_bytes().into()
167}
168
169pub(crate) fn mac_matches(computed: &[u8], received: &[u8]) -> bool {
171 computed.len() == received.len()
172 && computed.iter().zip(received).fold(0u8, |acc, (x, y)| acc | (x ^ y)) == 0
173}
174
175pub(crate) fn derive(key: &Key, d: u8, counter: [u8; 4], id: [u8; 4]) -> Key {
179 let [c0, c1, c2, c3] = counter;
180 let [i0, i1, i2, i3] = id;
181 let input = [d, c0, c1, c2, c3, i0, i1, i2, i3, 7, 7, 7, 7, 7, 7, 7];
182 let mut derived = cmac(key, &[&input]);
183 let k = Key(derived);
184 derived.zeroize();
185 k
186}
187
188#[cfg(test)]
189mod tests {
190 extern crate std;
191 use super::*;
192 use std::format;
193
194 #[test]
195 fn keys_never_print() {
196 let k = Key::from_hex("01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F 11").unwrap();
197 assert_eq!(format!("{k:?}"), "Key(..)");
198 assert_eq!(k.bytes()[15], 0x11);
199 assert!(Key::from_hex("0102").is_none());
200 assert!(Key::from_hex("zz02030405060708090A0B0C0D0E0F11").is_none());
201 assert!(Key::from_hex("0102030405060708090A0B0C0D0E0F1122").is_none());
202 }
203
204 #[test]
205 fn cmac_matches_rfc_4493() {
206 let k = Key::from_hex("2b7e151628aed2a6abf7158809cf4f3c").unwrap();
208 let m =
209 [0x6b, 0xc1, 0xbe, 0xe2, 0x2e, 0x40, 0x9f, 0x96, 0xe9, 0x3d, 0x7e, 0x11, 0x73, 0x93, 0x17, 0x2a];
210 let t = cmac(&k, &[&m[..8], &m[8..]]);
211 assert_eq!(
212 t,
213 [0x07, 0x0a, 0x16, 0xb4, 0x6b, 0x4d, 0x41, 0x44, 0xf7, 0x9b, 0xdd, 0x9d, 0xd0, 0x4a, 0x28, 0x7c]
214 );
215 }
216}