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
use block_cipher_trait::generic_array::GenericArray;
use block_cipher_trait::BlockCipher;
use block_padding::Padding;
use traits::BlockMode;
use utils::{xor, Block};
use core::marker::PhantomData;
pub struct Pcbc<C: BlockCipher, P: Padding> {
cipher: C,
iv: GenericArray<u8, C::BlockSize>,
_p: PhantomData<P>,
}
impl<C: BlockCipher, P: Padding> Pcbc<C, P> {
pub fn new(cipher: C, iv: &Block<C>) -> Self {
Self {
cipher,
iv: iv.clone(),
_p: Default::default(),
}
}
}
impl<C: BlockCipher, P: Padding> BlockMode<C, P> for Pcbc<C, P> {
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);
}
}
}