1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
use crate::{
traits::{BlockMode, IvState},
utils::Block,
};
use block_padding::Padding;
use cipher::{generic_array::GenericArray, BlockCipher, BlockEncrypt};
use core::marker::PhantomData;
#[derive(Clone)]
pub struct Cfb8<C: BlockCipher + BlockEncrypt, P: Padding> {
cipher: C,
iv: GenericArray<u8, C::BlockSize>,
_p: PhantomData<P>,
}
impl<C, P> BlockMode<C, P> for Cfb8<C, P>
where
C: BlockCipher + BlockEncrypt,
P: Padding,
{
type IvSize = C::BlockSize;
fn new(cipher: C, iv: &Block<C>) -> Self {
Self {
cipher,
iv: iv.clone(),
_p: Default::default(),
}
}
fn encrypt_blocks(&mut self, blocks: &mut [Block<C>]) {
let mut iv = self.iv.clone();
let n = iv.len();
for block in blocks.iter_mut() {
for b in block.iter_mut() {
let iv_copy = iv.clone();
self.cipher.encrypt_block(&mut iv);
*b ^= iv[0];
iv[..n - 1].clone_from_slice(&iv_copy[1..]);
iv[n - 1] = *b;
}
}
self.iv = iv;
}
fn decrypt_blocks(&mut self, blocks: &mut [Block<C>]) {
let mut iv = self.iv.clone();
let n = iv.len();
for block in blocks.iter_mut() {
for b in block.iter_mut() {
let iv_copy = iv.clone();
self.cipher.encrypt_block(&mut iv);
let t = *b;
*b ^= iv[0];
iv[..n - 1].clone_from_slice(&iv_copy[1..]);
iv[n - 1] = t;
}
}
self.iv = iv;
}
}
impl<C, P> IvState<C, P> for Cfb8<C, P>
where
C: BlockCipher + BlockEncrypt,
P: Padding,
{
fn iv_state(&self) -> GenericArray<u8, Self::IvSize> {
self.iv.clone()
}
}