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,
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> AlgorithmName for Encryptor<C>
148where
149    C: BlockCipherEncrypt + AlgorithmName,
150{
151    fn write_alg_name(f: &mut fmt::Formatter<'_>) -> fmt::Result {
152        f.write_str("cfb::Encryptor<")?;
153        <C as AlgorithmName>::write_alg_name(f)?;
154        f.write_str(">")
155    }
156}
157
158impl<C> fmt::Debug for Encryptor<C>
159where
160    C: BlockCipherEncrypt + AlgorithmName,
161{
162    fn fmt(&self, 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: BlockCipherEncrypt> Drop for Encryptor<C> {
170    fn drop(&mut self) {
171        #[cfg(feature = "zeroize")]
172        self.iv.zeroize();
173    }
174}
175
176#[cfg(feature = "zeroize")]
177impl<C: BlockCipherEncrypt + ZeroizeOnDrop> ZeroizeOnDrop for Encryptor<C> {}
178
179struct CbcEncryptBackend<'a, BS, BK>
180where
181    BS: ArraySize,
182    BK: BlockCipherEncBackend<BlockSize = BS>,
183{
184    iv: &'a mut Array<u8, BS>,
185    cipher_backend: &'a BK,
186}
187
188impl<BS, BK> BlockSizeUser for CbcEncryptBackend<'_, BS, BK>
189where
190    BS: ArraySize,
191    BK: BlockCipherEncBackend<BlockSize = BS>,
192{
193    type BlockSize = BS;
194}
195
196impl<BS, BK> ParBlocksSizeUser for CbcEncryptBackend<'_, BS, BK>
197where
198    BS: ArraySize,
199    BK: BlockCipherEncBackend<BlockSize = BS>,
200{
201    type ParBlocksSize = U1;
202}
203
204impl<BS, BK> BlockModeEncBackend for CbcEncryptBackend<'_, BS, BK>
205where
206    BS: ArraySize,
207    BK: BlockCipherEncBackend<BlockSize = BS>,
208{
209    #[inline(always)]
210    fn encrypt_block(&mut self, mut block: InOut<'_, '_, Block<Self>>) {
211        block.xor_in2out(self.iv);
212        let mut t = block.get_out().clone();
213        self.cipher_backend.encrypt_block((&mut t).into());
214        *self.iv = t;
215    }
216}
217
218#[inline(always)]
219fn xor_set1(buf1: &mut [u8], buf2: &mut [u8]) {
220    for (a, b) in buf1.iter_mut().zip(buf2) {
221        let t = *a ^ *b;
222        *a = t;
223        *b = t;
224    }
225}