tail_cbc/
lib.rs

1mod decrypt;
2mod encrypt;
3mod unaligned_bytes;
4mod unaligned_bytes_mut;
5
6pub use cipher;
7pub use decrypt::Decryptor;
8pub use encrypt::Encryptor;
9
10pub use crate::unaligned_bytes_mut::{UnalignedBytesDecryptMut, UnalignedBytesEncryptMut};
11use cipher::generic_array::{ArrayLength, GenericArray};
12use cipher::inout::InOutBuf;
13use cipher::{
14    Block, BlockCipher, BlockDecrypt, BlockDecryptMut, BlockEncrypt, BlockEncryptMut,
15    BlockSizeUser
16};
17
18#[inline(always)]
19fn xor<N: ArrayLength<u8>>(out: &mut GenericArray<u8, N>, buf: &GenericArray<u8, N>) {
20    for (a, b) in out.iter_mut().zip(buf) {
21        *a ^= *b;
22    }
23}
24
25/// If unaligned tail procesing failed, this struct should be returned.
26#[derive(Debug)]
27pub struct TailError;
28
29impl<C: BlockCipher + BlockDecryptMut + BlockEncrypt + BlockSizeUser> UnalignedBytesDecryptMut
30    for Decryptor<C>
31{
32    fn proc_tail(
33        &self,
34        blocks: &mut InOutBuf<'_, '_, Block<Self>>,
35        tail: &mut InOutBuf<'_, '_, u8>,
36    ) -> Result<(), TailError> {
37        match blocks.get_in().last() {
38            Some(last) => {
39                let mut last: Block<C> = last.clone();
40                self.cipher.encrypt_block(&mut last);
41                tail.xor_in2out(&last[0..tail.len()]);
42                Ok(())
43            }
44            None => Err(TailError {}),
45        }
46    }
47}
48impl<C: BlockCipher + BlockEncryptMut + BlockDecrypt + BlockSizeUser> UnalignedBytesEncryptMut
49    for Encryptor<C>
50{
51    fn proc_tail(
52        &self,
53        blocks: &mut InOutBuf<'_, '_, Block<Self>>,
54        tail: &mut InOutBuf<'_, '_, u8>,
55    ) -> Result<(), TailError> {
56        match blocks.get_in().last() {
57            Some(last) => {
58                let mut last: Block<C> = last.clone();
59                self.cipher.decrypt_block(&mut last);
60                tail.xor_in2out(&last[0..tail.len()]);
61                Ok(())
62            }
63            None => Err(TailError {}),
64        }
65    }
66}