use crate::primitives::hash::gf128_double_u128;
use aes::cipher::{generic_array::GenericArray, BlockEncrypt, KeyInit};
use aes::Aes128Enc;
use zeroize::Zeroize;
pub(crate) const WIDTH_BIT6: u8 = 6;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[repr(u8)]
pub(crate) enum Branch {
RoKey = 0x01,
PrpStream = 0x02,
}
#[inline]
pub(crate) fn prefix_block(pos: u16, sym: u8) -> [u8; 16] {
let mut b = [0u8; 16];
b[1..3].copy_from_slice(&pos.to_be_bytes());
b[3] = sym;
b
}
#[inline]
pub(crate) fn final_block(branch: Branch, n: u16, s: u16, width: u8) -> [u8; 16] {
let mut b = [0u8; 16];
b[0] = branch as u8;
b[1..3].copy_from_slice(&n.to_be_bytes());
b[3..5].copy_from_slice(&s.to_be_bytes());
b[5] = width;
b
}
pub(crate) struct CmacAccumulator {
cipher: Aes128Enc,
k1: [u8; 16],
state: [u8; 16],
}
impl CmacAccumulator {
pub(crate) fn new(key: &[u8; 16]) -> Self {
let cipher = Aes128Enc::new(GenericArray::from_slice(key));
let mut acc = Self {
cipher,
k1: [0u8; 16],
state: [0u8; 16],
};
let mut l = acc.encrypt([0u8; 16]); acc.k1 = gf128_double_u128(u128::from_be_bytes(l)).to_be_bytes();
l.zeroize(); acc
}
#[inline]
fn encrypt(&self, mut b: [u8; 16]) -> [u8; 16] {
self.cipher
.encrypt_block(GenericArray::from_mut_slice(&mut b));
b
}
#[inline]
pub(crate) fn absorb(&mut self, block: &[u8; 16]) {
let mut mixed =
(u128::from_be_bytes(self.state) ^ u128::from_be_bytes(*block)).to_be_bytes();
self.cipher
.encrypt_block(GenericArray::from_mut_slice(&mut mixed));
self.state = mixed;
}
#[inline]
pub(crate) fn finalize(&self, final_block: &[u8; 16]) -> [u8; 16] {
let mut mixed = (u128::from_be_bytes(self.state)
^ u128::from_be_bytes(*final_block)
^ u128::from_be_bytes(self.k1))
.to_be_bytes();
self.cipher
.encrypt_block(GenericArray::from_mut_slice(&mut mixed));
mixed
}
#[cfg(test)]
pub(crate) fn subkey1(&self) -> [u8; 16] {
self.k1
}
}
impl Drop for CmacAccumulator {
fn drop(&mut self) {
self.k1.zeroize();
self.state.zeroize();
}
}
#[cfg(test)]
mod tests {
use super::*;
use hex_literal::hex;
use quickcheck::TestResult;
#[test]
fn nist_sp800_38b_aes128() {
let k = hex!("2b7e151628aed2a6abf7158809cf4f3c");
let acc = CmacAccumulator::new(&k);
assert_eq!(acc.subkey1(), hex!("fbeed618357133667c85e08f7236a8de"));
let m1 = hex!("6bc1bee22e409f96e93d7e117393172a");
assert_eq!(acc.finalize(&m1), hex!("070a16b46b4d4144f79bdd9dd04a287c"));
let mut acc = CmacAccumulator::new(&k);
acc.absorb(&hex!("6bc1bee22e409f96e93d7e117393172a"));
acc.absorb(&hex!("ae2d8a571e03ac9c9eb76fac45af8e51"));
acc.absorb(&hex!("30c81c46a35ce411e5fbc1191a0a52ef"));
assert_eq!(
acc.finalize(&hex!("f69f2445df4f9b17ad2b417be66c3710")),
hex!("51f0bebf7e3b9d92fc49741779363cfe")
);
}
#[test]
fn encoding_is_injective_on_block_type() {
assert_eq!(prefix_block(7, 0x3f)[0], 0x00);
assert_ne!(final_block(Branch::RoKey, 7, 9, WIDTH_BIT6)[0], 0x00);
assert_ne!(final_block(Branch::PrpStream, 7, 9, WIDTH_BIT6)[0], 0x00);
assert_ne!(
final_block(Branch::RoKey, 1, 2, WIDTH_BIT6),
final_block(Branch::PrpStream, 1, 2, WIDTH_BIT6)
);
assert_ne!(
final_block(Branch::RoKey, 1, 2, WIDTH_BIT6),
final_block(Branch::RoKey, 1, 3, WIDTH_BIT6)
);
assert_ne!(prefix_block(1, 2), prefix_block(2, 2));
}
#[test]
fn finalize_does_not_mutate_state() {
let mut acc = CmacAccumulator::new(&[0x11u8; 16]);
acc.absorb(&prefix_block(0, 5));
let a = acc.finalize(&final_block(Branch::RoKey, 1, 0, WIDTH_BIT6));
let _ = acc.finalize(&final_block(Branch::PrpStream, 1, 0, WIDTH_BIT6));
let a_again = acc.finalize(&final_block(Branch::RoKey, 1, 0, WIDTH_BIT6));
assert_eq!(a, a_again);
}
fn reference_cmac(key: &[u8; 16], blocks: &[[u8; 16]]) -> [u8; 16] {
let cipher = Aes128Enc::new(GenericArray::from_slice(key));
let enc = |mut b: [u8; 16]| {
cipher.encrypt_block(GenericArray::from_mut_slice(&mut b));
b
};
let k1 = gf128_double_u128(u128::from_be_bytes(enc([0u8; 16]))).to_be_bytes();
let (last, prefix) = blocks.split_last().expect("at least one block");
let mut state = 0u128;
for blk in prefix {
state = u128::from_be_bytes(enc((state ^ u128::from_be_bytes(*blk)).to_be_bytes()));
}
enc((state ^ u128::from_be_bytes(*last) ^ u128::from_be_bytes(k1)).to_be_bytes())
}
quickcheck! {
fn prop_incremental_matches_reference(key: Vec<u8>, msg: Vec<u8>) -> TestResult {
if key.len() < 16 {
return TestResult::discard();
}
let mut k = [0u8; 16];
k.copy_from_slice(&key[..16]);
let nblocks = 1 + (msg.len() % 8);
let mut blocks = Vec::with_capacity(nblocks);
for i in 0..nblocks {
let mut b = [0u8; 16];
for (j, slot) in b.iter_mut().enumerate() {
*slot = msg
.get(i * 16 + j)
.copied()
.unwrap_or((i as u8).wrapping_mul(31).wrapping_add(j as u8));
}
blocks.push(b);
}
let mut acc = CmacAccumulator::new(&k);
let (last, prefix) = blocks.split_last().unwrap();
for blk in prefix {
acc.absorb(blk);
}
TestResult::from_bool(acc.finalize(last) == reference_cmac(&k, &blocks))
}
fn prop_final_block_injective(n: u16, s: u16, width: u8) -> bool {
[Branch::RoKey, Branch::PrpStream].iter().copied().all(|branch| {
let fb = final_block(branch, n, s, width);
fb[0] == branch as u8
&& fb[0] != 0x00
&& u16::from_be_bytes([fb[1], fb[2]]) == n
&& u16::from_be_bytes([fb[3], fb[4]]) == s
&& fb[5] == width
})
}
fn prop_prefix_block_injective(pos: u16, sym: u8) -> bool {
let pb = prefix_block(pos, sym);
pb[0] == 0x00 && u16::from_be_bytes([pb[1], pb[2]]) == pos && pb[3] == sym
}
}
}
#[cfg(kani)]
mod kani_proofs {
use super::*;
fn any_branch() -> Branch {
if kani::any() {
Branch::RoKey
} else {
Branch::PrpStream
}
}
#[kani::proof]
fn final_block_injective() {
let (b1, n1, s1, w1) = (any_branch(), kani::any(), kani::any(), kani::any());
let (b2, n2, s2, w2) = (any_branch(), kani::any(), kani::any(), kani::any());
if final_block(b1, n1, s1, w1) == final_block(b2, n2, s2, w2) {
assert!(b1 == b2 && n1 == n2 && s1 == s2 && w1 == w2);
}
}
#[kani::proof]
fn prefix_block_injective() {
let (p1, y1): (u16, u8) = (kani::any(), kani::any());
let (p2, y2): (u16, u8) = (kani::any(), kani::any());
if prefix_block(p1, y1) == prefix_block(p2, y2) {
assert!(p1 == p2 && y1 == y2);
}
}
#[kani::proof]
fn prefix_and_final_blocks_disjoint() {
let pb = prefix_block(kani::any(), kani::any());
let fb = final_block(any_branch(), kani::any(), kani::any(), kani::any());
assert!(pb != fb);
}
}