1use cipher::{
2 AlgorithmName, Array, Block, BlockCipherDecrypt, BlockCipherEncBackend, BlockCipherEncClosure,
3 BlockCipherEncrypt, BlockModeDecBackend, BlockModeDecClosure, BlockModeDecrypt, BlockSizeUser,
4 InnerIvInit, Iv, IvSizeUser, IvState, ParBlocks, ParBlocksSizeUser,
5 array::ArraySize,
6 common::InnerUser,
7 inout::{InOut, InOutBuf, NotEqualError},
8 typenum::Unsigned,
9};
10use core::fmt;
11
12#[cfg(feature = "zeroize")]
13use cipher::zeroize::{Zeroize, ZeroizeOnDrop};
14
15pub struct Decryptor<C>
17where
18 C: BlockCipherEncrypt,
19{
20 cipher: C,
21 iv: Block<C>,
22}
23
24pub struct BufDecryptor<C>
26where
27 C: BlockCipherEncrypt,
28{
29 cipher: C,
30 iv: Block<C>,
31 pos: usize,
32}
33
34impl<C> BufDecryptor<C>
35where
36 C: BlockCipherEncrypt,
37{
38 pub fn decrypt(&mut self, mut data: &mut [u8]) {
40 let bs = C::BlockSize::USIZE;
41 let n = data.len();
42
43 if n < bs - self.pos {
44 xor_set2(data, &mut self.iv[self.pos..self.pos + n]);
45 self.pos += n;
46 return;
47 }
48 let (left, right) = { data }.split_at_mut(bs - self.pos);
49 data = right;
50 let mut iv = self.iv.clone();
51 xor_set2(left, &mut iv[self.pos..]);
52 self.cipher.encrypt_block(&mut iv);
53
54 let mut chunks = data.chunks_exact_mut(bs);
55 for chunk in &mut chunks {
56 xor_set2(chunk, iv.as_mut_slice());
57 self.cipher.encrypt_block(&mut iv);
58 }
59
60 let rem = chunks.into_remainder();
61 xor_set2(rem, iv.as_mut_slice());
62 self.pos = rem.len();
63 self.iv = iv;
64 }
65
66 pub fn get_state(&self) -> (&Block<C>, usize) {
68 (&self.iv, self.pos)
69 }
70
71 pub fn from_state(cipher: C, iv: &Block<C>, pos: usize) -> Self {
73 Self {
74 cipher,
75 iv: iv.clone(),
76 pos,
77 }
78 }
79}
80
81impl<C> InnerUser for BufDecryptor<C>
82where
83 C: BlockCipherEncrypt,
84{
85 type Inner = C;
86}
87
88impl<C> IvSizeUser for BufDecryptor<C>
89where
90 C: BlockCipherEncrypt,
91{
92 type IvSize = C::BlockSize;
93}
94
95impl<C> InnerIvInit for BufDecryptor<C>
96where
97 C: BlockCipherEncrypt,
98{
99 #[inline]
100 fn inner_iv_init(cipher: C, iv: &Iv<Self>) -> Self {
101 let mut iv = iv.clone();
102 cipher.encrypt_block(&mut iv);
103 Self { cipher, iv, pos: 0 }
104 }
105}
106
107impl<C> AlgorithmName for BufDecryptor<C>
108where
109 C: BlockCipherEncrypt + AlgorithmName,
110{
111 fn write_alg_name(f: &mut fmt::Formatter<'_>) -> fmt::Result {
112 f.write_str("cfb::BufDecryptor<")?;
113 <C as AlgorithmName>::write_alg_name(f)?;
114 f.write_str(">")
115 }
116}
117
118impl<C> fmt::Debug for BufDecryptor<C>
119where
120 C: BlockCipherEncrypt + AlgorithmName,
121{
122 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
123 f.write_str("cfb::BufDecryptor<")?;
124 <C as AlgorithmName>::write_alg_name(f)?;
125 f.write_str("> { ... }")
126 }
127}
128
129impl<C: BlockCipherEncrypt> Drop for BufDecryptor<C> {
130 fn drop(&mut self) {
131 #[cfg(feature = "zeroize")]
132 self.iv.zeroize();
133 }
134}
135
136#[cfg(feature = "zeroize")]
137impl<C: BlockCipherEncrypt + ZeroizeOnDrop> ZeroizeOnDrop for BufDecryptor<C> {}
138
139impl<C> BlockSizeUser for Decryptor<C>
140where
141 C: BlockCipherEncrypt,
142{
143 type BlockSize = C::BlockSize;
144}
145
146impl<C> BlockModeDecrypt for Decryptor<C>
147where
148 C: BlockCipherEncrypt,
149{
150 fn decrypt_with_backend(&mut self, f: impl BlockModeDecClosure<BlockSize = Self::BlockSize>) {
151 struct Closure<'a, BS, BC>
154 where
155 BS: ArraySize,
156 BC: BlockModeDecClosure<BlockSize = BS>,
157 {
158 iv: &'a mut Array<u8, BS>,
159 f: BC,
160 }
161
162 impl<BS, BC> BlockSizeUser for Closure<'_, BS, BC>
163 where
164 BS: ArraySize,
165 BC: BlockModeDecClosure<BlockSize = BS>,
166 {
167 type BlockSize = BS;
168 }
169
170 impl<BS, BC> BlockCipherEncClosure for Closure<'_, BS, BC>
171 where
172 BS: ArraySize,
173 BC: BlockModeDecClosure<BlockSize = BS>,
174 {
175 #[inline(always)]
176 fn call<B: BlockCipherEncBackend<BlockSize = Self::BlockSize>>(
177 self,
178 cipher_backend: &B,
179 ) {
180 let Self { iv, f } = self;
181 f.call(&mut CbcDecryptBackend { iv, cipher_backend });
182 }
183 }
184
185 let Self { cipher, iv } = self;
186 cipher.encrypt_with_backend(Closure { iv, f });
187 }
188}
189
190impl<C> Decryptor<C>
191where
192 C: BlockCipherEncrypt,
193{
194 pub fn decrypt_inout(mut self, data: InOutBuf<'_, '_, u8>) {
196 let (blocks, mut tail) = data.into_chunks();
197 self.decrypt_blocks_inout(blocks);
198 let n = tail.len();
199 if n != 0 {
200 let mut block = Block::<Self>::default();
201 block[..n].copy_from_slice(tail.get_in());
202 self.decrypt_block(&mut block);
203 tail.get_out().copy_from_slice(&block[..n]);
204 }
205 }
206
207 pub fn decrypt(self, buf: &mut [u8]) {
209 self.decrypt_inout(buf.into());
210 }
211
212 pub fn decrypt_b2b(self, in_buf: &[u8], out_buf: &mut [u8]) -> Result<(), NotEqualError> {
217 InOutBuf::new(in_buf, out_buf).map(|b| self.decrypt_inout(b))
218 }
219}
220
221impl<C> InnerUser for Decryptor<C>
222where
223 C: BlockCipherEncrypt,
224{
225 type Inner = C;
226}
227
228impl<C> IvSizeUser for Decryptor<C>
229where
230 C: BlockCipherEncrypt,
231{
232 type IvSize = C::BlockSize;
233}
234
235impl<C> InnerIvInit for Decryptor<C>
236where
237 C: BlockCipherEncrypt,
238{
239 #[inline]
240 fn inner_iv_init(cipher: C, iv: &Iv<Self>) -> Self {
241 let mut iv = iv.clone();
242 cipher.encrypt_block(&mut iv);
243 Self { cipher, iv }
244 }
245}
246
247impl<C> IvState for Decryptor<C>
248where
249 C: BlockCipherEncrypt + BlockCipherDecrypt,
250{
251 #[inline]
252 fn iv_state(&self) -> Iv<Self> {
253 let mut res = self.iv.clone();
254 self.cipher.decrypt_block(&mut res);
255 res
256 }
257}
258
259impl<C> AlgorithmName for Decryptor<C>
260where
261 C: BlockCipherEncrypt + AlgorithmName,
262{
263 fn write_alg_name(f: &mut fmt::Formatter<'_>) -> fmt::Result {
264 f.write_str("cfb::Decryptor<")?;
265 <C as AlgorithmName>::write_alg_name(f)?;
266 f.write_str(">")
267 }
268}
269
270impl<C> fmt::Debug for Decryptor<C>
271where
272 C: BlockCipherEncrypt + AlgorithmName,
273{
274 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
275 f.write_str("cfb::Decryptor<")?;
276 <C as AlgorithmName>::write_alg_name(f)?;
277 f.write_str("> { ... }")
278 }
279}
280
281impl<C: BlockCipherEncrypt> Drop for Decryptor<C> {
282 fn drop(&mut self) {
283 #[cfg(feature = "zeroize")]
284 self.iv.zeroize();
285 }
286}
287
288#[cfg(feature = "zeroize")]
289impl<C: BlockCipherEncrypt + ZeroizeOnDrop> ZeroizeOnDrop for Decryptor<C> {}
290
291struct CbcDecryptBackend<'a, BS, BK>
292where
293 BS: ArraySize,
294 BK: BlockCipherEncBackend<BlockSize = BS>,
295{
296 iv: &'a mut Array<u8, BS>,
297 cipher_backend: &'a BK,
298}
299
300impl<BS, BK> BlockSizeUser for CbcDecryptBackend<'_, BS, BK>
301where
302 BS: ArraySize,
303 BK: BlockCipherEncBackend<BlockSize = BS>,
304{
305 type BlockSize = BS;
306}
307
308impl<BS, BK> ParBlocksSizeUser for CbcDecryptBackend<'_, BS, BK>
309where
310 BS: ArraySize,
311 BK: BlockCipherEncBackend<BlockSize = BS>,
312{
313 type ParBlocksSize = BK::ParBlocksSize;
314}
315
316impl<BS, BK> BlockModeDecBackend for CbcDecryptBackend<'_, BS, BK>
317where
318 BS: ArraySize,
319 BK: BlockCipherEncBackend<BlockSize = BS>,
320{
321 #[inline(always)]
322 fn decrypt_block(&mut self, mut block: InOut<'_, '_, Block<Self>>) {
323 let mut t = block.clone_in();
324 block.xor_in2out(self.iv);
325 self.cipher_backend.encrypt_block((&mut t).into());
326 *self.iv = t;
327 }
328
329 #[inline(always)]
330 fn decrypt_par_blocks(&mut self, mut blocks: InOut<'_, '_, ParBlocks<Self>>) {
331 let mut t = ParBlocks::<Self>::default();
332 let b = (blocks.get_in(), &mut t).into();
333 self.cipher_backend.encrypt_par_blocks(b);
334
335 let n = t.len();
336 blocks.get(0).xor_in2out(self.iv);
337 for i in 1..n {
338 blocks.get(i).xor_in2out(&t[i - 1]);
339 }
340 *self.iv = t[n - 1].clone();
341 }
342}
343
344#[inline(always)]
345fn xor_set2(buf1: &mut [u8], buf2: &mut [u8]) {
346 for (a, b) in buf1.iter_mut().zip(buf2) {
347 let t = *a;
348 *a ^= *b;
349 *b = t;
350 }
351}