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
75
76
77
78
use crate::{
traits::{BlockMode, IvState},
utils::{xor, Block},
};
use block_padding::Padding;
use cipher::{generic_array::GenericArray, BlockCipher, BlockDecrypt, BlockEncrypt};
use core::marker::PhantomData;
#[derive(Clone)]
pub struct Pcbc<C: BlockCipher + BlockEncrypt + BlockDecrypt, P: Padding> {
cipher: C,
iv: GenericArray<u8, C::BlockSize>,
_p: PhantomData<P>,
}
impl<C, P> Pcbc<C, P>
where
C: BlockCipher + BlockEncrypt + BlockDecrypt,
P: Padding,
{
pub fn new(cipher: C, iv: &Block<C>) -> Self {
Self {
cipher,
iv: iv.clone(),
_p: Default::default(),
}
}
}
impl<C, P> BlockMode<C, P> for Pcbc<C, P>
where
C: BlockCipher + BlockEncrypt + BlockDecrypt,
P: Padding,
{
type IvSize = C::BlockSize;
fn new(cipher: C, iv: &GenericArray<u8, C::BlockSize>) -> Self {
Self {
cipher,
iv: iv.clone(),
_p: Default::default(),
}
}
fn encrypt_blocks(&mut self, blocks: &mut [Block<C>]) {
for block in blocks {
let plaintext = block.clone();
xor(block, &self.iv);
self.cipher.encrypt_block(block);
self.iv = plaintext;
xor(&mut self.iv, block);
}
}
fn decrypt_blocks(&mut self, blocks: &mut [Block<C>]) {
for block in blocks {
let ciphertext = block.clone();
self.cipher.decrypt_block(block);
xor(block, &self.iv);
self.iv = ciphertext;
xor(&mut self.iv, block);
}
}
}
impl<C, P> IvState<C, P> for Pcbc<C, P>
where
C: BlockCipher + BlockEncrypt + BlockDecrypt,
P: Padding,
{
fn iv_state(&self) -> GenericArray<u8, Self::IvSize> {
self.iv.clone()
}
}