use aead::generic_array::{
typenum::{U12, U16, U8},
GenericArray,
};
use aes::block_cipher_trait::BlockCipher;
use core::{convert::TryInto, mem};
type Block128 = GenericArray<u8, U16>;
type Block128x8 = GenericArray<Block128, U8>;
const BLOCK_SIZE: usize = 16;
pub(super) const BLOCK8_SIZE: usize = BLOCK_SIZE * 8;
pub(crate) struct Ctr32<'c, C>
where
C: BlockCipher<BlockSize = U16, ParBlocks = U8>,
{
cipher: &'c C,
counter_block: Block128,
buffer: Block128x8,
}
impl<'c, C> Ctr32<'c, C>
where
C: BlockCipher<BlockSize = U16, ParBlocks = U8>,
{
pub fn new(cipher: &'c C, nonce: &GenericArray<u8, U12>) -> Self {
let mut counter_block = GenericArray::default();
counter_block[..12].copy_from_slice(nonce.as_slice());
counter_block[15] = 1;
Self {
cipher,
counter_block,
buffer: unsafe { mem::zeroed() },
}
}
pub fn seek(&mut self, new_counter_value: u32) {
self.counter_block[12..].copy_from_slice(&new_counter_value.wrapping_add(1).to_be_bytes());
}
pub fn apply_keystream(&mut self, msg: &mut [u8]) {
for chunk in msg.chunks_mut(BLOCK8_SIZE) {
self.apply_8block_keystream(chunk);
}
}
pub fn apply_8block_keystream(&mut self, msg: &mut [u8]) {
let mut counter = u32::from_be_bytes(self.counter_block[12..].try_into().unwrap());
let n_blocks = msg.chunks(BLOCK_SIZE).count();
for block in self.buffer.iter_mut().take(n_blocks) {
*block = self.counter_block;
counter = counter.wrapping_add(1);
self.counter_block[12..].copy_from_slice(&counter.to_be_bytes());
}
if n_blocks == 1 {
self.cipher.encrypt_block(&mut self.buffer[0]);
} else {
self.cipher.encrypt_blocks(&mut self.buffer);
}
for (i, chunk) in msg.chunks_mut(BLOCK_SIZE).enumerate() {
let keystream_block = &self.buffer[i];
for (i, byte) in chunk.iter_mut().enumerate() {
*byte ^= keystream_block[i];
}
}
}
}