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
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
//! Traits used to define functionality of [block ciphers][1] and [modes of operation][2].
//!
//! # About block ciphers
//!
//! Block ciphers are keyed, deterministic permutations of a fixed-sized input
//! "block" providing a reversible transformation to/from an encrypted output.
//! They are one of the fundamental structural components of [symmetric cryptography][3].
//!
//! [1]: https://en.wikipedia.org/wiki/Block_cipher
//! [2]: https://en.wikipedia.org/wiki/Block_cipher_mode_of_operation
//! [3]: https://en.wikipedia.org/wiki/Symmetric-key_algorithm

#[cfg(all(feature = "block-padding", feature = "alloc"))]
use alloc::{vec, vec::Vec};
use crypto_common::{Block, BlockSizeUser};
#[cfg(feature = "block-padding")]
use inout::{
    block_padding::{Padding, UnpadError},
    InOutBufReserved, PadError,
};
use inout::{InOut, InOutBuf, NotEqualError};

mod backends;
mod ctx;

use ctx::{BlockCtx, BlocksCtx};

pub use backends::{
    BlockCipherDecBackend, BlockCipherDecClosure, BlockCipherEncBackend, BlockCipherEncClosure,
    BlockModeDecBackend, BlockModeDecClosure, BlockModeEncBackend, BlockModeEncClosure,
};

/// Encrypt-only functionality for block ciphers.
pub trait BlockCipherEncrypt: BlockSizeUser + Sized {
    /// Encrypt data using backend provided to the rank-2 closure.
    fn encrypt_with_backend(&self, f: impl BlockCipherEncClosure<BlockSize = Self::BlockSize>);

    /// Encrypt single `inout` block.
    #[inline]
    fn encrypt_block_inout(&self, block: InOut<'_, '_, Block<Self>>) {
        self.encrypt_with_backend(BlockCtx { block });
    }

    /// Encrypt `inout` blocks.
    #[inline]
    fn encrypt_blocks_inout(&self, blocks: InOutBuf<'_, '_, Block<Self>>) {
        self.encrypt_with_backend(BlocksCtx { blocks });
    }

    /// Encrypt single block in-place.
    #[inline]
    fn encrypt_block(&self, block: &mut Block<Self>) {
        let block = block.into();
        self.encrypt_with_backend(BlockCtx { block });
    }

    /// Encrypt `in_block` and write result to `out_block`.
    #[inline]
    fn encrypt_block_b2b(&self, in_block: &Block<Self>, out_block: &mut Block<Self>) {
        let block = (in_block, out_block).into();
        self.encrypt_with_backend(BlockCtx { block });
    }

    /// Encrypt blocks in-place.
    #[inline]
    fn encrypt_blocks(&self, blocks: &mut [Block<Self>]) {
        let blocks = blocks.into();
        self.encrypt_with_backend(BlocksCtx { blocks });
    }

    /// Encrypt blocks buffer-to-buffer.
    ///
    /// Returns [`NotEqualError`] if provided `in_blocks` and `out_blocks`
    /// have different lengths.
    #[inline]
    fn encrypt_blocks_b2b(
        &self,
        in_blocks: &[Block<Self>],
        out_blocks: &mut [Block<Self>],
    ) -> Result<(), NotEqualError> {
        InOutBuf::new(in_blocks, out_blocks)
            .map(|blocks| self.encrypt_with_backend(BlocksCtx { blocks }))
    }

    /// Pad input and encrypt. Returns resulting ciphertext slice.
    ///
    /// Returns [`PadError`] if length of output buffer is not sufficient.
    #[cfg(feature = "block-padding")]
    #[inline]
    fn encrypt_padded_inout<'out, P: Padding<Self::BlockSize>>(
        &self,
        data: InOutBufReserved<'_, 'out, u8>,
    ) -> Result<&'out [u8], PadError> {
        let mut buf = data.into_padded_blocks::<P, Self::BlockSize>()?;
        self.encrypt_blocks_inout(buf.get_blocks());
        if let Some(block) = buf.get_tail_block() {
            self.encrypt_block_inout(block);
        }
        Ok(buf.into_out())
    }

    /// Pad input and encrypt in-place. Returns resulting ciphertext slice.
    ///
    /// Returns [`PadError`] if length of output buffer is not sufficient.
    #[cfg(feature = "block-padding")]
    #[inline]
    fn encrypt_padded<'a, P: Padding<Self::BlockSize>>(
        &self,
        buf: &'a mut [u8],
        msg_len: usize,
    ) -> Result<&'a [u8], PadError> {
        let buf = InOutBufReserved::from_mut_slice(buf, msg_len).map_err(|_| PadError)?;
        self.encrypt_padded_inout::<P>(buf)
    }

    /// Pad input and encrypt buffer-to-buffer. Returns resulting ciphertext slice.
    ///
    /// Returns [`PadError`] if length of output buffer is not sufficient.
    #[cfg(feature = "block-padding")]
    #[inline]
    fn encrypt_padded_b2b<'a, P: Padding<Self::BlockSize>>(
        &self,
        msg: &[u8],
        out_buf: &'a mut [u8],
    ) -> Result<&'a [u8], PadError> {
        let buf = InOutBufReserved::from_slices(msg, out_buf).map_err(|_| PadError)?;
        self.encrypt_padded_inout::<P>(buf)
    }

    /// Pad input and encrypt into a newly allocated Vec. Returns resulting ciphertext Vec.
    #[cfg(all(feature = "block-padding", feature = "alloc"))]
    #[inline]
    fn encrypt_padded_vec<P: Padding<Self::BlockSize>>(&self, msg: &[u8]) -> Vec<u8> {
        use crypto_common::typenum::Unsigned;
        let bs = Self::BlockSize::USIZE;
        let mut out = vec![0; bs * (msg.len() / bs + 1)];
        let len = self
            .encrypt_padded_b2b::<P>(msg, &mut out)
            .expect("enough space for encrypting is allocated")
            .len();
        out.truncate(len);
        out
    }
}

/// Decrypt-only functionality for block ciphers.
pub trait BlockCipherDecrypt: BlockSizeUser {
    /// Decrypt data using backend provided to the rank-2 closure.
    fn decrypt_with_backend(&self, f: impl BlockCipherDecClosure<BlockSize = Self::BlockSize>);

    /// Decrypt single `inout` block.
    #[inline]
    fn decrypt_block_inout(&self, block: InOut<'_, '_, Block<Self>>) {
        self.decrypt_with_backend(BlockCtx { block });
    }

    /// Decrypt `inout` blocks.
    #[inline]
    fn decrypt_blocks_inout(&self, blocks: InOutBuf<'_, '_, Block<Self>>) {
        self.decrypt_with_backend(BlocksCtx { blocks });
    }

    /// Decrypt single block in-place.
    #[inline]
    fn decrypt_block(&self, block: &mut Block<Self>) {
        let block = block.into();
        self.decrypt_with_backend(BlockCtx { block });
    }

    /// Decrypt `in_block` and write result to `out_block`.
    #[inline]
    fn decrypt_block_b2b(&self, in_block: &Block<Self>, out_block: &mut Block<Self>) {
        let block = (in_block, out_block).into();
        self.decrypt_with_backend(BlockCtx { block });
    }

    /// Decrypt blocks in-place.
    #[inline]
    fn decrypt_blocks(&self, blocks: &mut [Block<Self>]) {
        let blocks = blocks.into();
        self.decrypt_with_backend(BlocksCtx { blocks });
    }

    /// Decrypt blocks buffer-to-buffer.
    ///
    /// Returns [`NotEqualError`] if provided `in_blocks` and `out_blocks`
    /// have different lengths.
    #[inline]
    fn decrypt_blocks_b2b(
        &self,
        in_blocks: &[Block<Self>],
        out_blocks: &mut [Block<Self>],
    ) -> Result<(), NotEqualError> {
        InOutBuf::new(in_blocks, out_blocks)
            .map(|blocks| self.decrypt_with_backend(BlocksCtx { blocks }))
    }

    /// Decrypt input and unpad it. Returns resulting plaintext slice.
    ///
    /// Returns [`UnpadError`] if padding is malformed or if input length is
    /// not multiple of `Self::BlockSize`.
    #[cfg(feature = "block-padding")]
    #[inline]
    fn decrypt_padded_inout<'out, P: Padding<Self::BlockSize>>(
        &self,
        data: InOutBuf<'_, 'out, u8>,
    ) -> Result<&'out [u8], UnpadError> {
        let (mut blocks, tail) = data.into_chunks();
        if !tail.is_empty() {
            return Err(UnpadError);
        }
        self.decrypt_blocks_inout(blocks.reborrow());
        P::unpad_blocks(blocks.into_out())
    }

    /// Decrypt input and unpad it in-place. Returns resulting plaintext slice.
    ///
    /// Returns [`UnpadError`] if padding is malformed or if input length is
    /// not multiple of `Self::BlockSize`.
    #[cfg(feature = "block-padding")]
    #[inline]
    fn decrypt_padded<'a, P: Padding<Self::BlockSize>>(
        &self,
        buf: &'a mut [u8],
    ) -> Result<&'a [u8], UnpadError> {
        self.decrypt_padded_inout::<P>(buf.into())
    }

    /// Decrypt input and unpad it buffer-to-buffer. Returns resulting
    /// plaintext slice.
    ///
    /// Returns [`UnpadError`] if padding is malformed or if input length is
    /// not multiple of `Self::BlockSize`.
    #[cfg(feature = "block-padding")]
    #[inline]
    fn decrypt_padded_b2b<'a, P: Padding<Self::BlockSize>>(
        &self,
        in_buf: &[u8],
        out_buf: &'a mut [u8],
    ) -> Result<&'a [u8], UnpadError> {
        if out_buf.len() < in_buf.len() {
            return Err(UnpadError);
        }
        let n = in_buf.len();
        // note: `new` always returns `Ok` here
        let buf = InOutBuf::new(in_buf, &mut out_buf[..n]).map_err(|_| UnpadError)?;
        self.decrypt_padded_inout::<P>(buf)
    }

    /// Decrypt input and unpad it in a newly allocated Vec. Returns resulting
    /// plaintext `Vec`.
    ///
    /// Returns [`UnpadError`] if padding is malformed or if input length is
    /// not multiple of `Self::BlockSize`.
    #[cfg(all(feature = "block-padding", feature = "alloc"))]
    #[inline]
    fn decrypt_padded_vec<P: Padding<Self::BlockSize>>(
        &self,
        buf: &[u8],
    ) -> Result<Vec<u8>, UnpadError> {
        let mut out = vec![0; buf.len()];
        let len = self.decrypt_padded_b2b::<P>(buf, &mut out)?.len();
        out.truncate(len);
        Ok(out)
    }
}

impl<Alg: BlockCipherEncrypt> BlockCipherEncrypt for &Alg {
    fn encrypt_with_backend(&self, f: impl BlockCipherEncClosure<BlockSize = Self::BlockSize>) {
        Alg::encrypt_with_backend(self, f);
    }
}

impl<Alg: BlockCipherDecrypt> BlockCipherDecrypt for &Alg {
    fn decrypt_with_backend(&self, f: impl BlockCipherDecClosure<BlockSize = Self::BlockSize>) {
        Alg::decrypt_with_backend(self, f);
    }
}

/// Encrypt-only functionality for block ciphers and modes with mutable access to `self`.
///
/// The main use case for this trait is blocks modes, but it also can be used
/// for hardware cryptographic engines which require `&mut self` access to an
/// underlying hardware peripheral.
pub trait BlockModeEncrypt: BlockSizeUser + Sized {
    /// Encrypt data using backend provided to the rank-2 closure.
    fn encrypt_with_backend(&mut self, f: impl BlockModeEncClosure<BlockSize = Self::BlockSize>);

    /// Encrypt single `inout` block.
    #[inline]
    fn encrypt_block_inout(&mut self, block: InOut<'_, '_, Block<Self>>) {
        self.encrypt_with_backend(BlockCtx { block });
    }

    /// Encrypt `inout` blocks.
    #[inline]
    fn encrypt_blocks_inout(&mut self, blocks: InOutBuf<'_, '_, Block<Self>>) {
        self.encrypt_with_backend(BlocksCtx { blocks });
    }

    /// Encrypt single block in-place.
    #[inline]
    fn encrypt_block(&mut self, block: &mut Block<Self>) {
        let block = block.into();
        self.encrypt_with_backend(BlockCtx { block });
    }

    /// Encrypt `in_block` and write result to `out_block`.
    #[inline]
    fn encrypt_block_b2b(&mut self, in_block: &Block<Self>, out_block: &mut Block<Self>) {
        let block = (in_block, out_block).into();
        self.encrypt_with_backend(BlockCtx { block });
    }

    /// Encrypt blocks in-place.
    #[inline]
    fn encrypt_blocks(&mut self, blocks: &mut [Block<Self>]) {
        let blocks = blocks.into();
        self.encrypt_with_backend(BlocksCtx { blocks });
    }

    /// Encrypt blocks buffer-to-buffer.
    ///
    /// Returns [`NotEqualError`] if provided `in_blocks` and `out_blocks`
    /// have different lengths.
    #[inline]
    fn encrypt_blocks_b2b(
        &mut self,
        in_blocks: &[Block<Self>],
        out_blocks: &mut [Block<Self>],
    ) -> Result<(), NotEqualError> {
        InOutBuf::new(in_blocks, out_blocks)
            .map(|blocks| self.encrypt_with_backend(BlocksCtx { blocks }))
    }

    /// Pad input and encrypt. Returns resulting ciphertext slice.
    ///
    /// Returns [`PadError`] if length of output buffer is not sufficient.
    #[cfg(feature = "block-padding")]
    #[inline]
    fn encrypt_padded_inout<'out, P: Padding<Self::BlockSize>>(
        mut self,
        data: InOutBufReserved<'_, 'out, u8>,
    ) -> Result<&'out [u8], PadError> {
        let mut buf = data.into_padded_blocks::<P, Self::BlockSize>()?;
        self.encrypt_blocks_inout(buf.get_blocks());
        if let Some(block) = buf.get_tail_block() {
            self.encrypt_block_inout(block);
        }
        Ok(buf.into_out())
    }

    /// Pad input and encrypt in-place. Returns resulting ciphertext slice.
    ///
    /// Returns [`PadError`] if length of output buffer is not sufficient.
    #[cfg(feature = "block-padding")]
    #[inline]
    fn encrypt_padded<P: Padding<Self::BlockSize>>(
        self,
        buf: &mut [u8],
        msg_len: usize,
    ) -> Result<&[u8], PadError> {
        let buf = InOutBufReserved::from_mut_slice(buf, msg_len).map_err(|_| PadError)?;
        self.encrypt_padded_inout::<P>(buf)
    }

    /// Pad input and encrypt buffer-to-buffer. Returns resulting ciphertext slice.
    ///
    /// Returns [`PadError`] if length of output buffer is not sufficient.
    #[cfg(feature = "block-padding")]
    #[inline]
    fn encrypt_padded_b2b<'a, P: Padding<Self::BlockSize>>(
        self,
        msg: &[u8],
        out_buf: &'a mut [u8],
    ) -> Result<&'a [u8], PadError> {
        let buf = InOutBufReserved::from_slices(msg, out_buf).map_err(|_| PadError)?;
        self.encrypt_padded_inout::<P>(buf)
    }

    /// Pad input and encrypt into a newly allocated Vec. Returns resulting ciphertext Vec.
    #[cfg(all(feature = "block-padding", feature = "alloc"))]
    #[inline]
    fn encrypt_padded_vec<P: Padding<Self::BlockSize>>(self, msg: &[u8]) -> Vec<u8> {
        use crypto_common::typenum::Unsigned;
        let bs = Self::BlockSize::USIZE;
        let mut out = vec![0; bs * (msg.len() / bs + 1)];
        let len = self
            .encrypt_padded_b2b::<P>(msg, &mut out)
            .expect("enough space for encrypting is allocated")
            .len();
        out.truncate(len);
        out
    }
}

/// Decrypt-only functionality for block ciphers and modes with mutable access to `self`.
///
/// The main use case for this trait is blocks modes, but it also can be used
/// for hardware cryptographic engines which require `&mut self` access to an
/// underlying hardware peripheral.
pub trait BlockModeDecrypt: BlockSizeUser + Sized {
    /// Decrypt data using backend provided to the rank-2 closure.
    fn decrypt_with_backend(&mut self, f: impl BlockModeDecClosure<BlockSize = Self::BlockSize>);

    /// Decrypt single `inout` block.
    #[inline]
    fn decrypt_block_inout(&mut self, block: InOut<'_, '_, Block<Self>>) {
        self.decrypt_with_backend(BlockCtx { block });
    }

    /// Decrypt `inout` blocks.
    #[inline]
    fn decrypt_blocks_inout(&mut self, blocks: InOutBuf<'_, '_, Block<Self>>) {
        self.decrypt_with_backend(BlocksCtx { blocks });
    }

    /// Decrypt single block in-place.
    #[inline]
    fn decrypt_block(&mut self, block: &mut Block<Self>) {
        let block = block.into();
        self.decrypt_with_backend(BlockCtx { block });
    }

    /// Decrypt `in_block` and write result to `out_block`.
    #[inline]
    fn decrypt_block_b2b(&mut self, in_block: &Block<Self>, out_block: &mut Block<Self>) {
        let block = (in_block, out_block).into();
        self.decrypt_with_backend(BlockCtx { block });
    }

    /// Decrypt blocks in-place.
    #[inline]
    fn decrypt_blocks(&mut self, blocks: &mut [Block<Self>]) {
        let blocks = blocks.into();
        self.decrypt_with_backend(BlocksCtx { blocks });
    }

    /// Decrypt blocks buffer-to-buffer.
    ///
    /// Returns [`NotEqualError`] if provided `in_blocks` and `out_blocks`
    /// have different lengths.
    #[inline]
    fn decrypt_blocks_b2b(
        &mut self,
        in_blocks: &[Block<Self>],
        out_blocks: &mut [Block<Self>],
    ) -> Result<(), NotEqualError> {
        InOutBuf::new(in_blocks, out_blocks)
            .map(|blocks| self.decrypt_with_backend(BlocksCtx { blocks }))
    }

    /// Decrypt input and unpad it. Returns resulting plaintext slice.
    ///
    /// Returns [`UnpadError`] if padding is malformed or if input length is
    /// not multiple of `Self::BlockSize`.
    #[cfg(feature = "block-padding")]
    #[inline]
    fn decrypt_padded_inout<'out, P: Padding<Self::BlockSize>>(
        mut self,
        data: InOutBuf<'_, 'out, u8>,
    ) -> Result<&'out [u8], UnpadError> {
        let (mut blocks, tail) = data.into_chunks();
        if !tail.is_empty() {
            return Err(UnpadError);
        }
        self.decrypt_blocks_inout(blocks.reborrow());
        P::unpad_blocks(blocks.into_out())
    }

    /// Decrypt input and unpad it in-place. Returns resulting plaintext slice.
    ///
    /// Returns [`UnpadError`] if padding is malformed or if input length is
    /// not multiple of `Self::BlockSize`.
    #[cfg(feature = "block-padding")]
    #[inline]
    fn decrypt_padded<P: Padding<Self::BlockSize>>(
        self,
        buf: &mut [u8],
    ) -> Result<&[u8], UnpadError> {
        self.decrypt_padded_inout::<P>(buf.into())
    }

    /// Decrypt input and unpad it buffer-to-buffer. Returns resulting
    /// plaintext slice.
    ///
    /// Returns [`UnpadError`] if padding is malformed or if input length is
    /// not multiple of `Self::BlockSize`.
    #[cfg(feature = "block-padding")]
    #[inline]
    fn decrypt_padded_b2b<'a, P: Padding<Self::BlockSize>>(
        self,
        in_buf: &[u8],
        out_buf: &'a mut [u8],
    ) -> Result<&'a [u8], UnpadError> {
        if out_buf.len() < in_buf.len() {
            return Err(UnpadError);
        }
        let n = in_buf.len();
        // note: `new` always returns `Ok` here
        let buf = InOutBuf::new(in_buf, &mut out_buf[..n]).map_err(|_| UnpadError)?;
        self.decrypt_padded_inout::<P>(buf)
    }

    /// Decrypt input and unpad it in a newly allocated Vec. Returns resulting
    /// plaintext `Vec`.
    ///
    /// Returns [`UnpadError`] if padding is malformed or if input length is
    /// not multiple of `Self::BlockSize`.
    #[cfg(all(feature = "block-padding", feature = "alloc"))]
    #[inline]
    fn decrypt_padded_vec<P: Padding<Self::BlockSize>>(
        self,
        buf: &[u8],
    ) -> Result<Vec<u8>, UnpadError> {
        let mut out = vec![0; buf.len()];
        let len = self.decrypt_padded_b2b::<P>(buf, &mut out)?.len();
        out.truncate(len);
        Ok(out)
    }
}