use super::StreamCipherError;
use crate::{
array::{Array, ArraySize},
typenum::Unsigned,
};
use common::{Block, BlockSizeUser, ParBlocks, ParBlocksSizeUser};
use inout::{InOut, InOutBuf};
pub trait StreamCipherBackend: ParBlocksSizeUser {
fn gen_ks_block(&mut self, block: &mut Block<Self>);
#[inline(always)]
fn gen_par_ks_blocks(&mut self, blocks: &mut ParBlocks<Self>) {
for block in blocks {
self.gen_ks_block(block);
}
}
#[inline(always)]
fn gen_tail_blocks(&mut self, blocks: &mut [Block<Self>]) {
assert!(blocks.len() < Self::ParBlocksSize::USIZE);
for block in blocks {
self.gen_ks_block(block);
}
}
}
pub trait StreamCipherClosure: BlockSizeUser {
fn call<B: StreamCipherBackend<BlockSize = Self::BlockSize>>(self, backend: &mut B);
}
pub trait StreamCipherCore: BlockSizeUser + Sized {
fn remaining_blocks(&self) -> Option<usize>;
fn process_with_backend(&mut self, f: impl StreamCipherClosure<BlockSize = Self::BlockSize>);
#[inline]
fn write_keystream_block(&mut self, block: &mut Block<Self>) {
self.process_with_backend(WriteBlockCtx { block });
}
#[inline]
fn write_keystream_blocks(&mut self, blocks: &mut [Block<Self>]) {
self.process_with_backend(WriteBlocksCtx { blocks });
}
#[inline]
fn apply_keystream_block_inout(&mut self, block: InOut<'_, '_, Block<Self>>) {
self.process_with_backend(ApplyBlockCtx { block });
}
#[inline]
fn apply_keystream_blocks(&mut self, blocks: &mut [Block<Self>]) {
self.process_with_backend(ApplyBlocksCtx {
blocks: blocks.into(),
});
}
#[inline]
fn apply_keystream_blocks_inout(&mut self, blocks: InOutBuf<'_, '_, Block<Self>>) {
self.process_with_backend(ApplyBlocksCtx { blocks });
}
#[inline]
fn try_apply_keystream_partial(
mut self,
mut buf: InOutBuf<'_, '_, u8>,
) -> Result<(), StreamCipherError> {
if let Some(rem_blocks) = self.remaining_blocks() {
let req_blocks = buf.len() / Self::BlockSize::USIZE;
if req_blocks > rem_blocks {
return Err(StreamCipherError);
}
}
if buf.len() > Self::BlockSize::USIZE {
let (blocks, tail) = buf.into_chunks();
self.apply_keystream_blocks_inout(blocks);
buf = tail;
}
let n = buf.len();
if n == 0 {
return Ok(());
}
let mut block = Block::<Self>::default();
block[..n].copy_from_slice(buf.get_in());
let t = InOutBuf::from_mut(&mut block);
self.apply_keystream_blocks_inout(t);
buf.get_out().copy_from_slice(&block[..n]);
Ok(())
}
#[inline]
fn apply_keystream_partial(self, buf: InOutBuf<'_, '_, u8>) {
self.try_apply_keystream_partial(buf)
.expect("number of remaining blocks insufficient");
}
}
pub trait StreamCipherCounter:
TryFrom<i32>
+ TryFrom<u32>
+ TryFrom<u64>
+ TryFrom<u128>
+ TryFrom<usize>
+ TryInto<i32>
+ TryInto<u32>
+ TryInto<u64>
+ TryInto<u128>
+ TryInto<usize>
+ Copy
{
fn is_max(&self) -> bool;
}
pub trait StreamCipherSeekCore: StreamCipherCore {
type Counter: StreamCipherCounter;
fn get_block_pos(&self) -> Self::Counter;
fn set_block_pos(&mut self, pos: Self::Counter);
}
macro_rules! impl_counter {
{$($t:ty )*} => {
$(
impl StreamCipherCounter for $t {
fn is_max(&self) -> bool {
*self == <$t>::MAX
}
}
)*
};
}
impl_counter! { u32 u64 u128 }
struct WriteBlockCtx<'a, BS: ArraySize> {
block: &'a mut Block<Self>,
}
impl<BS: ArraySize> BlockSizeUser for WriteBlockCtx<'_, BS> {
type BlockSize = BS;
}
impl<BS: ArraySize> StreamCipherClosure for WriteBlockCtx<'_, BS> {
#[inline(always)]
fn call<B: StreamCipherBackend<BlockSize = BS>>(self, backend: &mut B) {
backend.gen_ks_block(self.block);
}
}
struct WriteBlocksCtx<'a, BS: ArraySize> {
blocks: &'a mut [Block<Self>],
}
impl<BS: ArraySize> BlockSizeUser for WriteBlocksCtx<'_, BS> {
type BlockSize = BS;
}
impl<BS: ArraySize> StreamCipherClosure for WriteBlocksCtx<'_, BS> {
#[inline(always)]
fn call<B: StreamCipherBackend<BlockSize = BS>>(self, backend: &mut B) {
if B::ParBlocksSize::USIZE > 1 {
let (chunks, tail) = Array::slice_as_chunks_mut(self.blocks);
for chunk in chunks {
backend.gen_par_ks_blocks(chunk);
}
backend.gen_tail_blocks(tail);
} else {
for block in self.blocks {
backend.gen_ks_block(block);
}
}
}
}
struct ApplyBlockCtx<'inp, 'out, BS: ArraySize> {
block: InOut<'inp, 'out, Block<Self>>,
}
impl<BS: ArraySize> BlockSizeUser for ApplyBlockCtx<'_, '_, BS> {
type BlockSize = BS;
}
impl<BS: ArraySize> StreamCipherClosure for ApplyBlockCtx<'_, '_, BS> {
#[inline(always)]
fn call<B: StreamCipherBackend<BlockSize = BS>>(mut self, backend: &mut B) {
let mut t = Default::default();
backend.gen_ks_block(&mut t);
self.block.xor_in2out(&t);
}
}
struct ApplyBlocksCtx<'inp, 'out, BS: ArraySize> {
blocks: InOutBuf<'inp, 'out, Block<Self>>,
}
impl<BS: ArraySize> BlockSizeUser for ApplyBlocksCtx<'_, '_, BS> {
type BlockSize = BS;
}
impl<BS: ArraySize> StreamCipherClosure for ApplyBlocksCtx<'_, '_, BS> {
#[inline(always)]
#[allow(clippy::needless_range_loop)]
fn call<B: StreamCipherBackend<BlockSize = BS>>(self, backend: &mut B) {
if B::ParBlocksSize::USIZE > 1 {
let (chunks, mut tail) = self.blocks.into_chunks::<B::ParBlocksSize>();
for mut chunk in chunks {
let mut tmp = Default::default();
backend.gen_par_ks_blocks(&mut tmp);
chunk.xor_in2out(&tmp);
}
let n = tail.len();
let mut buf = Array::<_, B::ParBlocksSize>::default();
let ks = &mut buf[..n];
backend.gen_tail_blocks(ks);
for i in 0..n {
tail.get(i).xor_in2out(&ks[i]);
}
} else {
for mut block in self.blocks {
let mut t = Default::default();
backend.gen_ks_block(&mut t);
block.xor_in2out(&t);
}
}
}
}