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
use crate::{
traits::{BlockMode, IvState},
utils::{xor, Block},
};
use block_padding::Padding;
use cipher::{generic_array::GenericArray, BlockCipher, BlockEncrypt};
use core::marker::PhantomData;
#[derive(Clone)]
pub struct Ofb<C: BlockCipher + BlockEncrypt, P: Padding> {
cipher: C,
iv: GenericArray<u8, C::BlockSize>,
_p: PhantomData<P>,
}
impl<C, P> BlockMode<C, P> for Ofb<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>]) {
for block in blocks.iter_mut() {
self.cipher.encrypt_block(&mut self.iv);
xor(block, &self.iv);
}
}
fn decrypt_blocks(&mut self, blocks: &mut [Block<C>]) {
self.encrypt_blocks(blocks)
}
}
impl<C, P> IvState<C, P> for Ofb<C, P>
where
C: BlockCipher + BlockEncrypt,
P: Padding,
{
fn iv_state(&self) -> GenericArray<u8, <Self as BlockMode<C, P>>::IvSize> {
self.iv.clone()
}
}