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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
#[cfg(feature = "std")]
pub use std::vec::Vec;
use block_cipher_trait::BlockCipher;
use block_cipher_trait::generic_array::GenericArray;
use block_cipher_trait::generic_array::typenum::Unsigned;
use block_padding::Padding;
use utils::{Block, Key, to_blocks};
#[derive(Clone, Copy, Debug)]
pub struct BlockModeError;
#[derive(Clone, Copy, Debug)]
pub struct InvalidKeyIvLength;
pub trait BlockMode<C: BlockCipher, P: Padding>: Sized {
fn new(cipher: C, iv: &Block<C>) -> Self;
fn new_fix(key: &Key<C>, iv: &Block<C>) -> Self {
Self::new(C::new(key), iv)
}
fn new_var(key: &[u8], iv: &[u8]) -> Result<Self, InvalidKeyIvLength> {
if iv.len() != C::BlockSize::to_usize() {
return Err(InvalidKeyIvLength);
}
let iv = GenericArray::from_slice(iv);
let cipher = C::new_varkey(key).map_err(|_| InvalidKeyIvLength)?;
Ok(Self::new(cipher, iv))
}
fn encrypt_blocks(&mut self, blocks: &mut [Block<C>]);
fn decrypt_blocks(&mut self, blocks: &mut [Block<C>]);
fn encrypt(
mut self, buffer: &mut [u8], pos: usize
) -> Result<&[u8], BlockModeError> {
let bs = C::BlockSize::to_usize();
let buf = P::pad(buffer, pos, bs).map_err(|_| BlockModeError)?;
self.encrypt_blocks(to_blocks(buf));
Ok(buf)
}
fn decrypt(mut self, buffer: &mut [u8]) -> Result<&[u8], BlockModeError> {
let bs = C::BlockSize::to_usize();
if buffer.len() % bs != 0 { Err(BlockModeError)? }
self.decrypt_blocks(to_blocks(buffer));
P::unpad(buffer).map_err(|_| BlockModeError)
}
#[cfg(feature = "std")]
fn encrypt_vec(mut self, plaintext: &[u8]) -> Vec<u8> {
let bs = C::BlockSize::to_usize();
let pos = plaintext.len();
let n = pos + bs;
let mut buf = Vec::with_capacity(n);
buf.extend_from_slice(plaintext);
let block: Block<C> = Default::default();
buf.extend_from_slice(&block[..n - pos]);
let n = P::pad(&mut buf, pos, bs)
.expect("enough space for padding is allocated")
.len();
buf.truncate(n);
self.encrypt_blocks(to_blocks(&mut buf));
buf
}
#[cfg(feature = "std")]
fn decrypt_vec(mut self, ciphertext: &[u8]) -> Result<Vec<u8>, BlockModeError> {
let bs = C::BlockSize::to_usize();
if ciphertext.len() % bs != 0 { Err(BlockModeError)? }
let mut buf = ciphertext.to_vec();
self.decrypt_blocks(to_blocks(&mut buf));
let n = P::unpad(&buf).map_err(|_| BlockModeError)?.len();
buf.truncate(n);
Ok(buf)
}
}