use core::fmt;
use aes::Aes128;
use aes::cipher::generic_array::GenericArray;
use aes::cipher::{BlockDecryptMut, KeyInit, KeyIvInit, StreamCipher};
use cmac::{Cmac, Mac};
use zeroize::Zeroize;
use crate::app::Address;
use crate::{Check, Error, Result};
#[derive(Clone)]
pub struct Key([u8; 16]);
impl Drop for Key {
fn drop(&mut self) {
self.0.zeroize();
}
}
impl Key {
pub const fn new(bytes: [u8; 16]) -> Self {
Self(bytes)
}
pub fn from_hex(text: &str) -> Option<Self> {
let mut key = Self([0; 16]);
let mut n = 0usize;
let mut high: Option<u8> = None;
for c in text.bytes().filter(|c| !c.is_ascii_whitespace()) {
let v = match c {
b'0'..=b'9' => c - b'0',
b'a'..=b'f' => c - b'a' + 10,
b'A'..=b'F' => c - b'A' + 10,
_ => return None,
};
match high.take() {
None => high = Some(v),
Some(h) => {
*key.0.get_mut(n)? = (h << 4) | v;
n += 1;
}
}
}
(n == 16 && high.is_none()).then_some(key)
}
pub(crate) const fn bytes(&self) -> &[u8; 16] {
&self.0
}
}
impl fmt::Debug for Key {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("Key(..)")
}
}
impl From<[u8; 16]> for Key {
fn from(bytes: [u8; 16]) -> Self {
Self(bytes)
}
}
pub trait Keys {
fn key(&self, meter: &Address) -> Option<&Key>;
}
impl Keys for Key {
fn key(&self, _: &Address) -> Option<&Key> {
Some(self)
}
}
impl Keys for [(Address, Key)] {
fn key(&self, meter: &Address) -> Option<&Key> {
self.iter().find(|(a, _)| a.manufacturer == meter.manufacturer && a.id == meter.id).map(|(_, k)| k)
}
}
impl<const N: usize> Keys for [(Address, Key); N] {
fn key(&self, meter: &Address) -> Option<&Key> {
self.as_slice().key(meter)
}
}
impl<K: Keys + ?Sized> Keys for &K {
fn key(&self, meter: &Address) -> Option<&Key> {
(**self).key(meter)
}
}
pub(crate) fn cbc_decrypt(key: &Key, iv: &[u8; 16], data: &mut [u8]) -> Result<()> {
if data.len() % 16 != 0 {
return Err(Error::Verification(Check::Length));
}
let mut cipher = cbc::Decryptor::<Aes128>::new(key.bytes().into(), iv.into());
for block in data.chunks_exact_mut(16) {
cipher.decrypt_block_mut(GenericArray::from_mut_slice(block));
}
Ok(())
}
pub(crate) fn ccm_decrypt(
key: &Key,
nonce: &[u8; 13],
aad: &[u8],
data: &mut [u8],
tag: &[u8],
) -> Result<()> {
use ccm::aead::AeadInPlace;
use ccm::consts::{U8, U13};
let tag: &[u8; 8] = tag.try_into().map_err(|_| Error::UnsupportedSecurity(10))?;
let cipher = ccm::Ccm::<Aes128, U8, U13>::new(key.bytes().into());
cipher.decrypt_in_place_detached(nonce.into(), aad, data, tag.into()).map_err(|_| {
data.zeroize();
Error::Verification(Check::Tag)
})
}
pub(crate) fn ctr_apply(key: &Key, iv: &[u8; 16], data: &mut [u8]) {
ctr::Ctr128BE::<Aes128>::new(key.bytes().into(), iv.into()).apply_keystream(data);
}
pub(crate) fn cmac(key: &Key, parts: &[&[u8]]) -> [u8; 16] {
let mut mac = <Cmac<Aes128> as KeyInit>::new(key.bytes().into());
for p in parts {
mac.update(p);
}
mac.finalize().into_bytes().into()
}
pub(crate) fn mac_matches(computed: &[u8], received: &[u8]) -> bool {
computed.len() == received.len()
&& computed.iter().zip(received).fold(0u8, |acc, (x, y)| acc | (x ^ y)) == 0
}
pub(crate) fn derive(key: &Key, d: u8, counter: [u8; 4], id: [u8; 4]) -> Key {
let [c0, c1, c2, c3] = counter;
let [i0, i1, i2, i3] = id;
let input = [d, c0, c1, c2, c3, i0, i1, i2, i3, 7, 7, 7, 7, 7, 7, 7];
let mut derived = cmac(key, &[&input]);
let k = Key(derived);
derived.zeroize();
k
}
#[cfg(test)]
mod tests {
extern crate std;
use super::*;
use std::format;
#[test]
fn keys_never_print() {
let k = Key::from_hex("01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F 11").unwrap();
assert_eq!(format!("{k:?}"), "Key(..)");
assert_eq!(k.bytes()[15], 0x11);
assert!(Key::from_hex("0102").is_none());
assert!(Key::from_hex("zz02030405060708090A0B0C0D0E0F11").is_none());
assert!(Key::from_hex("0102030405060708090A0B0C0D0E0F1122").is_none());
}
#[test]
fn cmac_matches_rfc_4493() {
let k = Key::from_hex("2b7e151628aed2a6abf7158809cf4f3c").unwrap();
let m =
[0x6b, 0xc1, 0xbe, 0xe2, 0x2e, 0x40, 0x9f, 0x96, 0xe9, 0x3d, 0x7e, 0x11, 0x73, 0x93, 0x17, 0x2a];
let t = cmac(&k, &[&m[..8], &m[8..]]);
assert_eq!(
t,
[0x07, 0x0a, 0x16, 0xb4, 0x6b, 0x4d, 0x41, 0x44, 0xf7, 0x9b, 0xdd, 0x9d, 0xd0, 0x4a, 0x28, 0x7c]
);
}
}