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
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
#[cfg(feature = "alloc")]
pub use alloc::vec::Vec;
use crate::{
errors::{BlockModeError, InvalidKeyIvLength},
utils::{to_blocks, Block, Key},
};
use block_padding::Padding;
use cipher::{
generic_array::{typenum::Unsigned, ArrayLength, GenericArray},
BlockCipher, NewBlockCipher,
};
pub trait BlockMode<C: BlockCipher, P: Padding>: Sized {
type IvSize: ArrayLength<u8>;
fn new(cipher: C, iv: &GenericArray<u8, Self::IvSize>) -> Self;
fn new_fix(key: &Key<C>, iv: &GenericArray<u8, Self::IvSize>) -> Self
where
C: NewBlockCipher,
{
Self::new(C::new(key), iv)
}
fn new_from_slices(key: &[u8], iv: &[u8]) -> Result<Self, InvalidKeyIvLength>
where
C: NewBlockCipher,
{
if iv.len() != Self::IvSize::USIZE {
return Err(InvalidKeyIvLength);
}
let iv = GenericArray::from_slice(iv);
let cipher = C::new_from_slice(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 {
return Err(BlockModeError);
}
self.decrypt_blocks(to_blocks(buffer));
P::unpad(buffer).map_err(|_| BlockModeError)
}
#[cfg(feature = "alloc")]
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 = "alloc")]
fn decrypt_vec(mut self, ciphertext: &[u8]) -> Result<Vec<u8>, BlockModeError> {
let bs = C::BlockSize::to_usize();
if ciphertext.len() % bs != 0 {
return 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)
}
}
pub trait IvState<C, P>: BlockMode<C, P>
where
C: BlockCipher,
P: Padding,
{
fn iv_state(&self) -> GenericArray<u8, Self::IvSize>;
}