Skip to main content

cfb_mode/
encrypt.rs

1use cipher::{
2    AlgorithmName, Block, BlockCipherDecrypt, BlockCipherEncBackend, BlockCipherEncClosure,
3    BlockCipherEncrypt, BlockModeEncBackend, BlockModeEncClosure, BlockModeEncrypt, BlockSizeUser,
4    InnerIvInit, Iv, IvSizeUser, IvState, ParBlocksSizeUser, SetIvState,
5    array::{Array, ArraySize},
6    common::InnerUser,
7    consts::U1,
8    inout::{InOut, InOutBuf, NotEqualError},
9};
10use core::fmt;
11
12#[cfg(feature = "zeroize")]
13use cipher::zeroize::{Zeroize, ZeroizeOnDrop};
14
15mod buf;
16pub use buf::BufEncryptor;
17
18/// CFB mode encryptor.
19pub struct Encryptor<C>
20where
21    C: BlockCipherEncrypt,
22{
23    cipher: C,
24    iv: Block<C>,
25}
26
27impl<C> BlockSizeUser for Encryptor<C>
28where
29    C: BlockCipherEncrypt,
30{
31    type BlockSize = C::BlockSize;
32}
33
34impl<C> BlockModeEncrypt for Encryptor<C>
35where
36    C: BlockCipherEncrypt,
37{
38    fn encrypt_with_backend(&mut self, f: impl BlockModeEncClosure<BlockSize = Self::BlockSize>) {
39        /// This closure is used to receive block cipher backend and create
40        /// respective `Backend` based on it.
41        struct Closure<'a, BS, BC>
42        where
43            BS: ArraySize,
44            BC: BlockModeEncClosure<BlockSize = BS>,
45        {
46            iv: &'a mut Array<u8, BS>,
47            f: BC,
48        }
49
50        impl<BS, BC> BlockSizeUser for Closure<'_, BS, BC>
51        where
52            BS: ArraySize,
53            BC: BlockModeEncClosure<BlockSize = BS>,
54        {
55            type BlockSize = BS;
56        }
57
58        impl<BS, BC> BlockCipherEncClosure for Closure<'_, BS, BC>
59        where
60            BS: ArraySize,
61            BC: BlockModeEncClosure<BlockSize = BS>,
62        {
63            #[inline(always)]
64            fn call<B: BlockCipherEncBackend<BlockSize = Self::BlockSize>>(
65                self,
66                cipher_backend: &B,
67            ) {
68                let Self { iv, f } = self;
69                f.call(&mut CbcEncryptBackend { iv, cipher_backend });
70            }
71        }
72
73        let Self { cipher, iv } = self;
74        cipher.encrypt_with_backend(Closure { iv, f });
75    }
76}
77
78impl<C> Encryptor<C>
79where
80    C: BlockCipherEncrypt,
81{
82    /// Encrypt data using `InOutBuf`.
83    pub fn encrypt_inout(mut self, data: InOutBuf<'_, '_, u8>) {
84        let (blocks, mut tail) = data.into_chunks();
85        self.encrypt_blocks_inout(blocks);
86        let n = tail.len();
87        if n != 0 {
88            let mut block = Block::<Self>::default();
89            block[..n].copy_from_slice(tail.get_in());
90            self.encrypt_block(&mut block);
91            tail.get_out().copy_from_slice(&block[..n]);
92        }
93    }
94
95    /// Encrypt data in place.
96    pub fn encrypt(self, buf: &mut [u8]) {
97        self.encrypt_inout(buf.into());
98    }
99
100    /// Encrypt data from buffer to buffer.
101    ///
102    /// # Errors
103    /// If `in_buf` and `out_buf` have different lengths.
104    pub fn encrypt_b2b(self, in_buf: &[u8], out_buf: &mut [u8]) -> Result<(), NotEqualError> {
105        InOutBuf::new(in_buf, out_buf).map(|b| self.encrypt_inout(b))
106    }
107}
108
109impl<C> InnerUser for Encryptor<C>
110where
111    C: BlockCipherEncrypt,
112{
113    type Inner = C;
114}
115
116impl<C> IvSizeUser for Encryptor<C>
117where
118    C: BlockCipherEncrypt,
119{
120    type IvSize = C::BlockSize;
121}
122
123impl<C> InnerIvInit for Encryptor<C>
124where
125    C: BlockCipherEncrypt,
126{
127    #[inline]
128    fn inner_iv_init(cipher: C, iv: &Iv<Self>) -> Self {
129        let mut iv = iv.clone();
130        cipher.encrypt_block(&mut iv);
131        Self { cipher, iv }
132    }
133}
134
135impl<C> IvState for Encryptor<C>
136where
137    C: BlockCipherEncrypt + BlockCipherDecrypt,
138{
139    #[inline]
140    fn iv_state(&self) -> Iv<Self> {
141        let mut res = self.iv.clone();
142        self.cipher.decrypt_block(&mut res);
143        res
144    }
145}
146
147impl<C> SetIvState for Encryptor<C>
148where
149    C: BlockCipherEncrypt + BlockCipherDecrypt,
150{
151    #[inline]
152    fn set_iv(&mut self, iv: &Iv<Self>) {
153        self.iv = iv.clone();
154        self.cipher.encrypt_block(&mut self.iv);
155    }
156}
157
158impl<C> AlgorithmName for Encryptor<C>
159where
160    C: BlockCipherEncrypt + AlgorithmName,
161{
162    fn write_alg_name(f: &mut fmt::Formatter<'_>) -> fmt::Result {
163        f.write_str("cfb::Encryptor<")?;
164        <C as AlgorithmName>::write_alg_name(f)?;
165        f.write_str(">")
166    }
167}
168
169impl<C> fmt::Debug for Encryptor<C>
170where
171    C: BlockCipherEncrypt + AlgorithmName,
172{
173    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
174        f.write_str("cfb::Encryptor<")?;
175        <C as AlgorithmName>::write_alg_name(f)?;
176        f.write_str("> { ... }")
177    }
178}
179
180impl<C: BlockCipherEncrypt> Drop for Encryptor<C> {
181    fn drop(&mut self) {
182        #[cfg(feature = "zeroize")]
183        self.iv.zeroize();
184    }
185}
186
187#[cfg(feature = "zeroize")]
188impl<C: BlockCipherEncrypt + ZeroizeOnDrop> ZeroizeOnDrop for Encryptor<C> {}
189
190struct CbcEncryptBackend<'a, BS, BK>
191where
192    BS: ArraySize,
193    BK: BlockCipherEncBackend<BlockSize = BS>,
194{
195    iv: &'a mut Array<u8, BS>,
196    cipher_backend: &'a BK,
197}
198
199impl<BS, BK> BlockSizeUser for CbcEncryptBackend<'_, BS, BK>
200where
201    BS: ArraySize,
202    BK: BlockCipherEncBackend<BlockSize = BS>,
203{
204    type BlockSize = BS;
205}
206
207impl<BS, BK> ParBlocksSizeUser for CbcEncryptBackend<'_, BS, BK>
208where
209    BS: ArraySize,
210    BK: BlockCipherEncBackend<BlockSize = BS>,
211{
212    type ParBlocksSize = U1;
213}
214
215impl<BS, BK> BlockModeEncBackend for CbcEncryptBackend<'_, BS, BK>
216where
217    BS: ArraySize,
218    BK: BlockCipherEncBackend<BlockSize = BS>,
219{
220    #[inline(always)]
221    fn encrypt_block(&mut self, mut block: InOut<'_, '_, Block<Self>>) {
222        block.xor_in2out(self.iv);
223        let mut t = block.get_out().clone();
224        self.cipher_backend.encrypt_block((&mut t).into());
225        *self.iv = t;
226    }
227}
228
229#[inline(always)]
230fn xor_set1(buf1: &mut [u8], buf2: &mut [u8]) {
231    for (a, b) in buf1.iter_mut().zip(buf2) {
232        let t = *a ^ *b;
233        *a = t;
234        *b = t;
235    }
236}