eme2 0.3.0

EME2 (ECB-Mask-ECB) wide-block cipher mode of operation
Documentation
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
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
//! Generic EME2 for block sizes beyond the IEEE-standard 128 bits.
//!
//! # ⚠️ Beyond the standard: read before using
//!
//! IEEE Std 1619.2 only defines EME2-AES for 128-bit blocks. This module
//! extends the same algorithm (EME* instantiated over a block cipher `C` and
//! a concrete Key1/Key2/Key3 schedule) to 256-, 512-, and 1024-bit block
//! ciphers such as `Threefish`, via a generic [`EmePoly`] doubling operation.
//! This extension is **not part of any published standard** — no external
//! body has reviewed the GF(2^n) moduli used here for n > 128.
//!
//! What has been checked, and what has not:
//! - Each modulus (128/256/512/1024-bit) was verified **irreducible** over
//!   GF(2) computationally, so the doubling operation stays invertible and
//!   the arithmetic is a genuine field.
//! - EME*'s security proof additionally requires the doubling element to be
//!   **primitive** (multiplicative order exactly `2^n − 1`), which is what
//!   guarantees `2L, 4L, 8L, …` stay distinct across an entire message. This
//!   is the property IEEE's own 128-bit polynomial was specifically chosen
//!   for. Primitivity for the 256/512/1024-bit moduli here is **not
//!   independently verified**: proving it requires the complete prime
//!   factorization of `2^n − 1`, which for n = 1024 is not public knowledge.
//!
//! In practice this means: the 128-bit path (`Threefish` isn't 128-bit, but
//! AES/Serpent-sized ciphers are) rests on the same footing as the base
//! [`crate::Eme2`] type. The 256/512/1024-bit paths are a best-effort,
//! unstandardized extension — treat them as experimental until primitivity
//! is established or these constants are replaced with a citable reference.

use crate::Error;
use cipher::{
    Array, Block, BlockCipherDecrypt, BlockCipherEncrypt, BlockSizeUser, Iv, IvSizeUser, Key,
    KeyInit, KeyIvInit, KeySizeUser,
    typenum::{Sum, U16, U32, U64, U128, Unsigned},
};
use core::fmt;
use hybrid_array::ArraySize;

#[cfg(feature = "zeroize")]
use zeroize::{Zeroize, ZeroizeOnDrop};

/// Doubling (multiplication by the field element `x`) in `GF(2^n)`, where `n`
/// is the block size in bits. Implementations fix the field's reduction
/// polynomial for a given block size.
///
/// See the [module-level warning](self) about the unverified primitivity of
/// the 256/512/1024-bit implementations.
pub trait EmePoly: ArraySize {
    /// Multiplies `val` by the field element `x` (i.e. doubles it) in
    /// `GF(2^n)` under this block size's reduction polynomial.
    fn mult_by_two(val: &Array<u8, Self>) -> Array<u8, Self>;
}

/// Implements [`EmePoly`] for a block size using 64-bit-limb arithmetic:
/// shift the whole block left by one bit, then XOR in `$mod_bytes` (the
/// low-order terms of the reduction polynomial, little-endian) if the
/// shifted-out top bit was set.
macro_rules! impl_eme_poly {
    ($size:ty, $limbs:expr, $mod_bytes:expr) => {
        impl EmePoly for $size {
            #[inline]
            fn mult_by_two(val: &Array<u8, Self>) -> Array<u8, Self> {
                let mut res = Array::<u8, Self>::default();
                let mut v = [0u64; $limbs];

                for i in 0..$limbs {
                    let mut buf = [0u8; 8];
                    buf.copy_from_slice(&val[i * 8..(i + 1) * 8]);
                    v[i] = u64::from_le_bytes(buf);
                }

                let carry_out = v[$limbs - 1] >> 63;
                for i in (1..$limbs).rev() {
                    v[i] = (v[i] << 1) | (v[i - 1] >> 63);
                }
                v[0] <<= 1;

                let mask = 0u64.wrapping_sub(carry_out);
                let mod_bytes: [u8; 8] = $mod_bytes;
                let mod_limb = u64::from_le_bytes(mod_bytes) & mask;
                v[0] ^= mod_limb;

                for i in 0..$limbs {
                    res[i * 8..(i + 1) * 8].copy_from_slice(&v[i].to_le_bytes());
                }
                res
            }
        }
    };
}

// x^128 + x^7 + x^2 + x + 1 (IEEE Std 1619.2, verified irreducible AND primitive).
impl_eme_poly!(U16, 2, [0x87, 0, 0, 0, 0, 0, 0, 0]);
// x^256 + x^10 + x^5 + x^2 + 1 (verified irreducible; primitivity unverified).
impl_eme_poly!(U32, 4, [0x25, 0x04, 0, 0, 0, 0, 0, 0]);
// x^512 + x^8 + x^5 + x^2 + 1 (verified irreducible; primitivity unverified).
impl_eme_poly!(U64, 8, [0x25, 0x01, 0, 0, 0, 0, 0, 0]);
// x^1024 + x^9 + x^8 + x^7 + x^5 + x + 1 (verified irreducible; primitivity unverified).
impl_eme_poly!(U128, 16, [0xa3, 0x03, 0, 0, 0, 0, 0, 0]);

#[inline]
fn xor_blocks<C: BlockSizeUser>(out: &mut Block<C>, a: &Block<C>, b: &Block<C>) {
    for (o, (x, y)) in out.iter_mut().zip(a.iter().zip(b.iter())) {
        *o = *x ^ *y;
    }
}

#[inline]
fn xor_into<C: BlockSizeUser>(out: &mut Block<C>, b: &Block<C>) {
    for (o, x) in out.iter_mut().zip(b.iter()) {
        *o ^= *x;
    }
}

/// Converts an exactly-block-sized byte slice into an owned `Block<C>`.
/// Infallible in practice: every call site here slices `data` in chunks of
/// exactly `C::BlockSize` bytes.
#[inline]
fn block_from_slice<C: BlockSizeUser>(s: &[u8]) -> Block<C> {
    Block::<C>::try_from(s).unwrap_or_else(|_| unreachable!())
}

/// EME2 cipher mode, generalized to any block size with an [`EmePoly`]
/// implementation (128/256/512/1024 bits). See the
/// [module-level warning](self) before using block sizes above 128 bits.
#[derive(Clone)]
#[cfg_attr(feature = "zeroize", derive(ZeroizeOnDrop))]
pub struct Eme2<C>
where
    C: BlockCipherEncrypt + BlockCipherDecrypt + BlockSizeUser + KeySizeUser,
    C::BlockSize: EmePoly + core::ops::Add<C::BlockSize>,
    Sum<C::BlockSize, C::BlockSize>: ArraySize,
{
    #[cfg_attr(feature = "zeroize", zeroize(skip))]
    cipher: C,
    key2: Block<C>,
    key3: Block<C>,
    tweak: Block<C>,
}

impl<C> BlockSizeUser for Eme2<C>
where
    C: BlockCipherEncrypt + BlockCipherDecrypt + BlockSizeUser + KeySizeUser,
    C::BlockSize: EmePoly + core::ops::Add<C::BlockSize>,
    Sum<C::BlockSize, C::BlockSize>: ArraySize,
{
    type BlockSize = C::BlockSize;
}

impl<C> IvSizeUser for Eme2<C>
where
    C: BlockCipherEncrypt + BlockCipherDecrypt + BlockSizeUser + KeySizeUser,
    C::BlockSize: EmePoly + core::ops::Add<C::BlockSize>,
    Sum<C::BlockSize, C::BlockSize>: ArraySize,
{
    type IvSize = C::BlockSize;
}

impl<C> KeySizeUser for Eme2<C>
where
    C: BlockCipherEncrypt + BlockCipherDecrypt + BlockSizeUser + KeySizeUser,
    C::BlockSize: EmePoly + core::ops::Add<C::BlockSize>,
    Sum<C::BlockSize, C::BlockSize>: ArraySize,
    C::KeySize: core::ops::Add<Sum<C::BlockSize, C::BlockSize>>,
    Sum<C::KeySize, Sum<C::BlockSize, C::BlockSize>>: ArraySize,
{
    type KeySize = Sum<C::KeySize, Sum<C::BlockSize, C::BlockSize>>;
}

impl<C> KeyInit for Eme2<C>
where
    C: BlockCipherEncrypt + BlockCipherDecrypt + BlockSizeUser + KeyInit,
    C::BlockSize: EmePoly + core::ops::Add<C::BlockSize>,
    Sum<C::BlockSize, C::BlockSize>: ArraySize,
    C::KeySize: core::ops::Add<Sum<C::BlockSize, C::BlockSize>>,
    Sum<C::KeySize, Sum<C::BlockSize, C::BlockSize>>: ArraySize,
{
    fn new(key: &Key<Self>) -> Self {
        let key_bytes = key.as_slice();
        let ks = C::KeySize::USIZE;
        let bs = C::BlockSize::USIZE;

        let key1 = &key_bytes[..ks];
        let key2 = block_from_slice::<C>(&key_bytes[ks..ks + bs]);
        let key3 = block_from_slice::<C>(&key_bytes[ks + bs..ks + 2 * bs]);
        let cipher = C::new_from_slice(key1).unwrap_or_else(|_| unreachable!());

        let mut mode = Self {
            cipher,
            key2,
            key3,
            tweak: Block::<C>::default(),
        };
        mode.tweak = mode.hash_ad(&[]);
        mode
    }
}

impl<C> KeyIvInit for Eme2<C>
where
    C: BlockCipherEncrypt + BlockCipherDecrypt + BlockSizeUser + KeyInit,
    C::BlockSize: EmePoly + core::ops::Add<C::BlockSize>,
    Sum<C::BlockSize, C::BlockSize>: ArraySize,
    C::KeySize: core::ops::Add<Sum<C::BlockSize, C::BlockSize>>,
    Sum<C::KeySize, Sum<C::BlockSize, C::BlockSize>>: ArraySize,
{
    #[inline]
    fn new(key: &Key<Self>, iv: &Iv<Self>) -> Self {
        let mut mode = <Self as KeyInit>::new(key);
        mode.tweak = mode.hash_ad(iv.as_slice());
        mode
    }
}

impl<C> cipher::AlgorithmName for Eme2<C>
where
    C: BlockCipherEncrypt
        + BlockCipherDecrypt
        + BlockSizeUser
        + KeySizeUser
        + cipher::AlgorithmName,
    C::BlockSize: EmePoly + core::ops::Add<C::BlockSize>,
    Sum<C::BlockSize, C::BlockSize>: ArraySize,
{
    fn write_alg_name(f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str("extended::Eme2<")?;
        <C as cipher::AlgorithmName>::write_alg_name(f)?;
        f.write_str(">")
    }
}

impl<C> fmt::Debug for Eme2<C>
where
    C: BlockCipherEncrypt
        + BlockCipherDecrypt
        + BlockSizeUser
        + KeySizeUser
        + cipher::AlgorithmName,
    C::BlockSize: EmePoly + core::ops::Add<C::BlockSize>,
    Sum<C::BlockSize, C::BlockSize>: ArraySize,
{
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str("extended::Eme2<")?;
        <C as cipher::AlgorithmName>::write_alg_name(f)?;
        f.write_str("> { ... }")
    }
}

impl<C> Eme2<C>
where
    C: BlockCipherEncrypt + BlockCipherDecrypt + BlockSizeUser + KeySizeUser,
    C::BlockSize: EmePoly + core::ops::Add<C::BlockSize>,
    Sum<C::BlockSize, C::BlockSize>: ArraySize,
{
    /// Hashes the associated data (T) using Key3 and Key1 to compute `T_star`.
    pub fn hash_ad(&self, ad: &[u8]) -> Block<C> {
        let bs = C::BlockSize::USIZE;
        if ad.is_empty() {
            let mut t_star = self.key3.clone();
            self.cipher.encrypt_block(&mut t_star);
            return t_star;
        }

        let mut current_key3 = C::BlockSize::mult_by_two(&self.key3);
        let mut tt = Block::<C>::default();
        let chunks = ad.chunks(bs);
        let r = chunks.len();

        for (i, chunk) in chunks.enumerate() {
            let is_last = i == r - 1;
            let mut block = Block::<C>::default();
            if is_last {
                if chunk.len() < bs {
                    block[..chunk.len()].copy_from_slice(chunk);
                    block[chunk.len()] = 0x80;
                    current_key3 = C::BlockSize::mult_by_two(&current_key3);
                } else {
                    block.copy_from_slice(chunk);
                }
            } else {
                block.copy_from_slice(chunk);
            }

            xor_into::<C>(&mut block, &current_key3);
            self.cipher.encrypt_block(&mut block);
            xor_into::<C>(&mut block, &current_key3);
            xor_into::<C>(&mut tt, &block);

            if !is_last {
                current_key3 = C::BlockSize::mult_by_two(&current_key3);
            }
        }

        #[cfg(feature = "zeroize")]
        {
            current_key3.zeroize();
        }

        tt
    }

    /// Returns a reference to the current `T_star` value used directly as the tweak.
    pub const fn t_star(&self) -> &Block<C> {
        &self.tweak
    }

    /// Sets the current `T_star` value used directly as the tweak.
    pub fn set_t_star(&mut self, t_star: Block<C>) {
        self.tweak = t_star;
    }

    /// Encrypts the `data` in-place using EME2 mode with pre-computed tweak.
    /// `data` must be at least one block in length.
    ///
    /// # Errors
    ///
    /// Returns [`Error::DataTooShort`] if `data` is shorter than one block.
    pub fn encrypt(&self, data: &mut [u8]) -> Result<(), Error> {
        let tweak = self.tweak.clone();
        self.encrypt_core(&tweak, data)
    }

    /// Decrypts the `data` in-place using EME2 mode with pre-computed tweak.
    /// `data` must be at least one block in length.
    ///
    /// # Errors
    ///
    /// Returns [`Error::DataTooShort`] if `data` is shorter than one block.
    pub fn decrypt(&self, data: &mut [u8]) -> Result<(), Error> {
        let tweak = self.tweak.clone();
        self.decrypt_core(&tweak, data)
    }

    /// Encrypts the `data` in-place using EME2 mode with arbitrary associated data.
    /// `data` must be at least one block in length.
    ///
    /// # Errors
    ///
    /// Returns [`Error::DataTooShort`] if `data` is shorter than one block.
    pub fn encrypt_with_ad(&self, associated_data: &[u8], data: &mut [u8]) -> Result<(), Error> {
        #[cfg_attr(not(feature = "zeroize"), allow(unused_mut))]
        let mut t_star = self.hash_ad(associated_data);
        let res = self.encrypt_core(&t_star, data);

        #[cfg(feature = "zeroize")]
        {
            t_star.zeroize();
        }

        res
    }

    /// Decrypts the `data` in-place using EME2 mode with arbitrary associated data.
    /// `data` must be at least one block in length.
    ///
    /// # Errors
    ///
    /// Returns [`Error::DataTooShort`] if `data` is shorter than one block.
    pub fn decrypt_with_ad(&self, associated_data: &[u8], data: &mut [u8]) -> Result<(), Error> {
        #[cfg_attr(not(feature = "zeroize"), allow(unused_mut))]
        let mut t_star = self.hash_ad(associated_data);
        let res = self.decrypt_core(&t_star, data);

        #[cfg(feature = "zeroize")]
        {
            t_star.zeroize();
        }

        res
    }

    fn encrypt_core(&self, tweak: &Block<C>, data: &mut [u8]) -> Result<(), Error> {
        let bs = C::BlockSize::USIZE;
        let len = data.len();
        if len < bs {
            return Err(Error::DataTooShort);
        }

        let m = len.div_ceil(bs);
        let last_full = if len.is_multiple_of(bs) { m } else { m - 1 };

        let (mask_cipher_first, mask_delta_first, ccc_m, c_m) =
            self.encrypt_pass1_and_mix(tweak, data, len, bs, m, last_full);
        self.encrypt_pass2_and_3(
            tweak,
            data,
            len,
            bs,
            m,
            last_full,
            mask_cipher_first,
            mask_delta_first,
            ccc_m,
            c_m,
        );

        Ok(())
    }

    /// PASS 1 (first ECB pass) and the intermediate mixing step of encryption.
    /// Returns `(mask_cipher_first, mask_delta_first, ccc_m, c_m)` for
    /// [`Self::encrypt_pass2_and_3`].
    #[allow(clippy::too_many_arguments)]
    fn encrypt_pass1_and_mix(
        &self,
        tweak: &Block<C>,
        data: &mut [u8],
        len: usize,
        bs: usize,
        m: usize,
        last_full: usize,
    ) -> (Block<C>, Block<C>, Block<C>, Block<C>) {
        let mut l_current = self.key2.clone();

        for i in 0..last_full {
            let mut block = block_from_slice::<C>(&data[i * bs..(i + 1) * bs]);
            xor_into::<C>(&mut block, &l_current);
            self.cipher.encrypt_block(&mut block);
            data[i * bs..(i + 1) * bs].copy_from_slice(&block);

            l_current = C::BlockSize::mult_by_two(&l_current);
        }

        let mut ppp_m = Block::<C>::default();
        if last_full < m {
            let rem = len % bs;
            ppp_m[..rem].copy_from_slice(&data[last_full * bs..len]);
            ppp_m[rem] = 0x80;
        }

        let mut sp = Block::<C>::default();
        for i in 1..last_full {
            let ppp_i = block_from_slice::<C>(&data[i * bs..(i + 1) * bs]);
            xor_into::<C>(&mut sp, &ppp_i);
        }
        if last_full < m {
            xor_into::<C>(&mut sp, &ppp_m);
        }

        let ppp_0 = block_from_slice::<C>(&data[0..bs]);

        let mut mask_plain_first = Block::<C>::default();
        xor_blocks::<C>(&mut mask_plain_first, &ppp_0, &sp);
        xor_into::<C>(&mut mask_plain_first, tweak);

        let mut ccc_m = Block::<C>::default();
        let mut c_m = Block::<C>::default();
        let mut mm = Block::<C>::default();

        let mask_cipher_first = if last_full < m {
            mm.copy_from_slice(mask_plain_first.as_slice());
            self.cipher.encrypt_block(&mut mm);
            let mut mask_cipher_first = mm.clone();
            self.cipher.encrypt_block(&mut mask_cipher_first);

            let rem = len % bs;
            for i in 0..rem {
                c_m[i] = data[last_full * bs + i] ^ mm[i];
            }
            ccc_m[..rem].copy_from_slice(&c_m[..rem]);
            ccc_m[rem] = 0x80;
            mask_cipher_first
        } else {
            let mut mask_cipher_first = mask_plain_first.clone();
            self.cipher.encrypt_block(&mut mask_cipher_first);
            mask_cipher_first
        };

        let mut mask_delta_first = Block::<C>::default();
        xor_blocks::<C>(&mut mask_delta_first, &mask_plain_first, &mask_cipher_first);

        #[cfg(feature = "zeroize")]
        {
            l_current.zeroize();
            ppp_m.zeroize();
            sp.zeroize();
            mask_plain_first.zeroize();
            mm.zeroize();
        }

        (mask_cipher_first, mask_delta_first, ccc_m, c_m)
    }

    /// PASS 2 (masking chain) and PASS 3 (second ECB pass) of encryption.
    #[allow(clippy::too_many_arguments)]
    fn encrypt_pass2_and_3(
        &self,
        tweak: &Block<C>,
        data: &mut [u8],
        len: usize,
        bs: usize,
        m: usize,
        last_full: usize,
        #[cfg_attr(not(feature = "zeroize"), allow(unused_mut))] mut mask_cipher_first: Block<C>,
        #[cfg_attr(not(feature = "zeroize"), allow(unused_mut))] mut mask_delta_first: Block<C>,
        #[cfg_attr(not(feature = "zeroize"), allow(unused_mut))] mut ccc_m: Block<C>,
        #[cfg_attr(not(feature = "zeroize"), allow(unused_mut))] mut c_m: Block<C>,
    ) {
        let mut current_m_j = mask_delta_first.clone();
        let mut current_m_k = mask_delta_first.clone();

        for i in 1..last_full {
            let ppp_i = block_from_slice::<C>(&data[i * bs..(i + 1) * bs]);
            let mut ccc_i = Block::<C>::default();

            let k = i & 127;
            if k == 0 {
                let mut mask_plain_block = Block::<C>::default();
                xor_blocks::<C>(&mut mask_plain_block, &ppp_i, &mask_delta_first);
                let mut mask_cipher_block = mask_plain_block.clone();
                self.cipher.encrypt_block(&mut mask_cipher_block);
                xor_blocks::<C>(&mut current_m_j, &mask_plain_block, &mask_cipher_block);
                xor_blocks::<C>(&mut ccc_i, &mask_cipher_block, &mask_delta_first);
                current_m_k = current_m_j.clone();

                #[cfg(feature = "zeroize")]
                {
                    mask_plain_block.zeroize();
                    mask_cipher_block.zeroize();
                }
            } else {
                current_m_k = C::BlockSize::mult_by_two(&current_m_k);
                xor_blocks::<C>(&mut ccc_i, &ppp_i, &current_m_k);
            }
            data[i * bs..(i + 1) * bs].copy_from_slice(&ccc_i);
        }

        let mut sc = Block::<C>::default();
        for i in 1..last_full {
            let ccc_i = block_from_slice::<C>(&data[i * bs..(i + 1) * bs]);
            xor_into::<C>(&mut sc, &ccc_i);
        }
        if last_full < m {
            xor_into::<C>(&mut sc, &ccc_m);
        }

        let mut ccc_0 = Block::<C>::default();
        xor_blocks::<C>(&mut ccc_0, &mask_cipher_first, &sc);
        xor_into::<C>(&mut ccc_0, tweak);
        data[0..bs].copy_from_slice(&ccc_0);

        let mut l_current = self.key2.clone();
        for i in 0..last_full {
            let mut cc_i = block_from_slice::<C>(&data[i * bs..(i + 1) * bs]);
            self.cipher.encrypt_block(&mut cc_i);
            xor_into::<C>(&mut cc_i, &l_current);
            data[i * bs..(i + 1) * bs].copy_from_slice(&cc_i);

            l_current = C::BlockSize::mult_by_two(&l_current);
        }

        if last_full < m {
            let rem = len % bs;
            data[last_full * bs..len].copy_from_slice(&c_m[..rem]);
        }

        #[cfg(feature = "zeroize")]
        {
            mask_cipher_first.zeroize();
            ccc_m.zeroize();
            c_m.zeroize();
            mask_delta_first.zeroize();
            current_m_j.zeroize();
            current_m_k.zeroize();
            sc.zeroize();
            ccc_0.zeroize();
            l_current.zeroize();
        }
    }

    fn decrypt_core(&self, tweak: &Block<C>, data: &mut [u8]) -> Result<(), Error> {
        let bs = C::BlockSize::USIZE;
        let len = data.len();
        if len < bs {
            return Err(Error::DataTooShort);
        }

        let m = len.div_ceil(bs);
        let last_full = if len.is_multiple_of(bs) { m } else { m - 1 };

        let (mask_plain_first, mask_delta_first, ppp_m, p_m) =
            self.decrypt_pass1_and_mix(tweak, data, len, bs, m, last_full);
        self.decrypt_pass2_and_3(
            tweak,
            data,
            len,
            bs,
            m,
            last_full,
            mask_plain_first,
            mask_delta_first,
            ppp_m,
            p_m,
        );

        Ok(())
    }

    /// PASS 1 (first ECB pass) and the intermediate mixing step of decryption.
    /// Returns `(mask_plain_first, mask_delta_first, ppp_m, p_m)` for
    /// [`Self::decrypt_pass2_and_3`].
    #[allow(clippy::too_many_arguments)]
    fn decrypt_pass1_and_mix(
        &self,
        tweak: &Block<C>,
        data: &mut [u8],
        len: usize,
        bs: usize,
        m: usize,
        last_full: usize,
    ) -> (Block<C>, Block<C>, Block<C>, Block<C>) {
        let mut l_current = self.key2.clone();

        for i in 0..last_full {
            let mut block = block_from_slice::<C>(&data[i * bs..(i + 1) * bs]);
            xor_into::<C>(&mut block, &l_current);
            self.cipher.decrypt_block(&mut block);
            data[i * bs..(i + 1) * bs].copy_from_slice(&block);

            l_current = C::BlockSize::mult_by_two(&l_current);
        }

        let mut ccc_m = Block::<C>::default();
        if last_full < m {
            let rem = len % bs;
            ccc_m[..rem].copy_from_slice(&data[last_full * bs..len]);
            ccc_m[rem] = 0x80;
        }

        let mut sc = Block::<C>::default();
        for i in 1..last_full {
            let ccc_i = block_from_slice::<C>(&data[i * bs..(i + 1) * bs]);
            xor_into::<C>(&mut sc, &ccc_i);
        }
        if last_full < m {
            xor_into::<C>(&mut sc, &ccc_m);
        }

        let ccc_0 = block_from_slice::<C>(&data[0..bs]);

        let mut mask_cipher_first = Block::<C>::default();
        xor_blocks::<C>(&mut mask_cipher_first, &ccc_0, &sc);
        xor_into::<C>(&mut mask_cipher_first, tweak);

        let mut ppp_m = Block::<C>::default();
        let mut p_m = Block::<C>::default();
        let mut mm = Block::<C>::default();

        let mask_plain_first = if last_full < m {
            mm.copy_from_slice(mask_cipher_first.as_slice());
            self.cipher.decrypt_block(&mut mm);
            let mut mask_plain_first = mm.clone();
            self.cipher.decrypt_block(&mut mask_plain_first);

            let rem = len % bs;
            for i in 0..rem {
                p_m[i] = data[last_full * bs + i] ^ mm[i];
            }
            ppp_m[..rem].copy_from_slice(&p_m[..rem]);
            ppp_m[rem] = 0x80;
            mask_plain_first
        } else {
            let mut mask_plain_first = mask_cipher_first.clone();
            self.cipher.decrypt_block(&mut mask_plain_first);
            mask_plain_first
        };

        let mut mask_delta_first = Block::<C>::default();
        xor_blocks::<C>(&mut mask_delta_first, &mask_plain_first, &mask_cipher_first);

        #[cfg(feature = "zeroize")]
        {
            l_current.zeroize();
            ccc_m.zeroize();
            sc.zeroize();
            mask_cipher_first.zeroize();
            mm.zeroize();
        }

        (mask_plain_first, mask_delta_first, ppp_m, p_m)
    }

    /// PASS 2 (masking chain) and PASS 3 (second ECB pass) of decryption.
    #[allow(clippy::too_many_arguments)]
    fn decrypt_pass2_and_3(
        &self,
        tweak: &Block<C>,
        data: &mut [u8],
        len: usize,
        bs: usize,
        m: usize,
        last_full: usize,
        #[cfg_attr(not(feature = "zeroize"), allow(unused_mut))] mut mask_plain_first: Block<C>,
        #[cfg_attr(not(feature = "zeroize"), allow(unused_mut))] mut mask_delta_first: Block<C>,
        #[cfg_attr(not(feature = "zeroize"), allow(unused_mut))] mut ppp_m: Block<C>,
        #[cfg_attr(not(feature = "zeroize"), allow(unused_mut))] mut p_m: Block<C>,
    ) {
        let mut current_m_j = mask_delta_first.clone();
        let mut current_m_k = mask_delta_first.clone();

        for i in 1..last_full {
            let ccc_i = block_from_slice::<C>(&data[i * bs..(i + 1) * bs]);
            let mut ppp_i = Block::<C>::default();

            let k = i & 127;
            if k == 0 {
                let mut mask_cipher_block = Block::<C>::default();
                xor_blocks::<C>(&mut mask_cipher_block, &ccc_i, &mask_delta_first);
                let mut mask_plain_block = mask_cipher_block.clone();
                self.cipher.decrypt_block(&mut mask_plain_block);
                xor_blocks::<C>(&mut current_m_j, &mask_plain_block, &mask_cipher_block);
                xor_blocks::<C>(&mut ppp_i, &mask_plain_block, &mask_delta_first);
                current_m_k = current_m_j.clone();

                #[cfg(feature = "zeroize")]
                {
                    mask_cipher_block.zeroize();
                    mask_plain_block.zeroize();
                }
            } else {
                current_m_k = C::BlockSize::mult_by_two(&current_m_k);
                xor_blocks::<C>(&mut ppp_i, &ccc_i, &current_m_k);
            }
            data[i * bs..(i + 1) * bs].copy_from_slice(&ppp_i);
        }

        let mut sp = Block::<C>::default();
        for i in 1..last_full {
            let ppp_i = block_from_slice::<C>(&data[i * bs..(i + 1) * bs]);
            xor_into::<C>(&mut sp, &ppp_i);
        }
        if last_full < m {
            xor_into::<C>(&mut sp, &ppp_m);
        }

        let mut ppp_0 = Block::<C>::default();
        xor_blocks::<C>(&mut ppp_0, &mask_plain_first, &sp);
        xor_into::<C>(&mut ppp_0, tweak);
        data[0..bs].copy_from_slice(&ppp_0);

        let mut l_current = self.key2.clone();
        for i in 0..last_full {
            let mut pp_i = block_from_slice::<C>(&data[i * bs..(i + 1) * bs]);
            self.cipher.decrypt_block(&mut pp_i);
            xor_into::<C>(&mut pp_i, &l_current);
            data[i * bs..(i + 1) * bs].copy_from_slice(&pp_i);

            l_current = C::BlockSize::mult_by_two(&l_current);
        }

        if last_full < m {
            let rem = len % bs;
            data[last_full * bs..len].copy_from_slice(&p_m[..rem]);
        }

        #[cfg(feature = "zeroize")]
        {
            mask_plain_first.zeroize();
            ppp_m.zeroize();
            p_m.zeroize();
            mask_delta_first.zeroize();
            current_m_j.zeroize();
            current_m_k.zeroize();
            sp.zeroize();
            ppp_0.zeroize();
            l_current.zeroize();
        }
    }
}