eme2-extended 0.2.0

EME2-extended (ECB-Mask-ECB) wide-block cipher mode of operation for any block size ciphers
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
use cipher::{
    Block, BlockCipherDecrypt, BlockCipherEncrypt, BlockSizeUser, Iv, Key, KeyInit, KeyIvInit,
    KeySizeUser, IvSizeUser, Array, typenum::{U16, U32, U64, U128, Sum, Unsigned}
};
use hybrid_array::ArraySize;
use core::fmt;

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

/// Error types for EME2 operations.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Error {
    /// The provided data is shorter than the minimum block size.
    DataTooShort,
}

impl fmt::Display for Error {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::DataTooShort => write!(f, "Data must be at least one block size for EME2"),
        }
    }
}

impl core::error::Error for Error {}

#[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;
    }
}

/// A trait for block sizes that support EME2 Galois Field polynomial arithmetic.
pub trait EmePoly: ArraySize {
    /// Multiplies the given value by the polynomial `x` within GF(2^n).
    fn mult_by_two(val: &Array<u8, Self>) -> Array<u8, Self>;
}

// 64-bit Limb GF(2^n) Arithmetic for massive performance gains
macro_rules! impl_eme_poly {
    ($size:ty, $limbs:expr, $mask_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];

                // Load little-endian 64-bit 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);
                }

                // Shift left by 1, carrying overflow to the next limb
                let carry_out = (v[$limbs - 1] >> 63) as u8;
                for i in (1..$limbs).rev() {
                    v[i] = (v[i] << 1) | (v[i - 1] >> 63);
                }
                v[0] <<= 1;

                // Store back to little-endian bytes
                for i in 0..$limbs {
                    res[i * 8..(i + 1) * 8].copy_from_slice(&v[i].to_le_bytes());
                }

                // Apply polynomial mask in a constant-time manner if there was a carry
                let mask_val = 0u8.wrapping_sub(carry_out);
                let mask: &[u8] = &$mask_bytes;
                for (r, &m) in res.iter_mut().zip(mask.iter()) {
                    *r ^= m & mask_val;
                }
                res
            }
        }
    };
}

impl_eme_poly!(U16, 2, [0x87, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]);
impl_eme_poly!(
    U32,
    4,
    [
        0x25, 0x04, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
    ]
);
impl_eme_poly!(
    U64,
    8,
    [
        0x25, 0x01, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
    ]
);
impl_eme_poly!(
    U128,
    16,
    [
        0xa3, 0x03, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
    ]
);

#[inline]
fn encrypt_block<C>(cipher: &C, block: &mut Block<C>)
where
    C: BlockCipherEncrypt + BlockSizeUser,
{
    cipher.encrypt_block(block);
}

#[inline]
fn decrypt_block<C>(cipher: &C, block: &mut Block<C>)
where
    C: BlockCipherDecrypt + BlockSizeUser,
{
    cipher.decrypt_block(block);
}

/// EME2 cipher mode.
#[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 bs = C::BlockSize::USIZE;
        let ks = C::KeySize::USIZE;

        let mut key1 = Key::<C>::default();
        key1.copy_from_slice(&key[..ks]);

        let mut key2 = Block::<C>::default();
        key2.copy_from_slice(&key[ks..ks + bs]);

        let mut key3 = Block::<C>::default();
        key3.copy_from_slice(&key[ks + bs..ks + 2 * bs]);

        let cipher = C::new(&key1);
        let tweak = Block::<C>::default();

        #[cfg(feature = "zeroize")]
        {
            let mut key1_mut = key1;
            key1_mut.zeroize();
        }

        Self {
            cipher,
            key2,
            key3,
            tweak,
        }
    }
}

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_eme2(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("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("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.
    /// Defaults to IEEE P1619.2 (EME2) style.
    pub fn hash_ad(&self, ad: &[u8]) -> Block<C> {
        self.hash_ad_eme2(ad)
    }

    /// Hashes the associated data (T) using Key3 and Key1 to compute T_star (IEEE P1619.2 EME2 style).
    pub fn hash_ad_eme2(&self, ad: &[u8]) -> Block<C> {
        let bs = C::BlockSize::USIZE;
        let mut t_star = Block::<C>::default();
        if ad.is_empty() {
            t_star.copy_from_slice(self.key3.as_slice());
            encrypt_block(&self.cipher, &mut t_star);
            return t_star;
        }

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

        current_key3 = C::BlockSize::mult_by_two(&current_key3);

        for (i, chunk) in chunks.enumerate() {
            let is_last = i == r - 1;
            if !is_last {
                let mut block = Block::<C>::default();
                block.copy_from_slice(chunk);
                xor_into::<C>(&mut block, &current_key3);
                encrypt_block(&self.cipher, &mut block);
                xor_into::<C>(&mut tt, &block);
                current_key3 = C::BlockSize::mult_by_two(&current_key3);
            } else {
                let mut block = Block::<C>::default();
                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);
                }
                xor_into::<C>(&mut block, &current_key3);
                encrypt_block(&self.cipher, &mut block);
                xor_into::<C>(&mut tt, &block);
            }
        }

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

        tt
    }

    /// Hashes the associated data (T) using Key3 and Key1 to compute T_star (EME* style).
    pub fn hash_ad_emestar(&self, ad: &[u8]) -> Block<C> {
        let bs = C::BlockSize::USIZE;
        let mut t_star = Block::<C>::default();
        if ad.is_empty() {
            t_star.copy_from_slice(self.key3.as_slice());
            encrypt_block(&self.cipher, &mut t_star);
            return t_star;
        }

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

        current_key3 = C::BlockSize::mult_by_two(&current_key3);

        for (i, chunk) in chunks.enumerate() {
            let is_last = i == r - 1;
            if !is_last {
                let mut block = Block::<C>::default();
                block.copy_from_slice(chunk);
                xor_into::<C>(&mut block, &current_key3);
                encrypt_block(&self.cipher, &mut block);
                xor_into::<C>(&mut block, &current_key3);
                xor_into::<C>(&mut tt, &block);
                current_key3 = C::BlockSize::mult_by_two(&current_key3);
            } else {
                let mut block = Block::<C>::default();
                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);
                }
                xor_into::<C>(&mut block, &current_key3);
                encrypt_block(&self.cipher, &mut block);
                xor_into::<C>(&mut block, &current_key3);
                xor_into::<C>(&mut tt, &block);
            }
        }

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

        tt
    }

    /// Returns a reference to the current tweak.
    pub fn tweak(&self) -> &Block<C> {
        &self.tweak
    }

    /// Sets the current tweak.
    pub fn set_tweak(&mut self, tweak: Block<C>) {
        self.tweak = tweak;
    }

    /// Encrypts the `data` in-place using EME2 mode with pre-computed tweak.
    /// `data` must be at least one block size.
    pub fn encrypt(&self, data: &mut [u8]) -> Result<(), Error> {
        self.encrypt_core(&self.tweak, data)
    }

    /// Decrypts the `data` in-place using EME2 mode with pre-computed tweak.
    /// `data` must be at least one block size.
    pub fn decrypt(&self, data: &mut [u8]) -> Result<(), Error> {
        self.decrypt_core(&self.tweak, data)
    }

    /// Encrypts the `data` in-place using EME2 mode with arbitrary associated data.
    /// Defaults to IEEE P1619.2 (EME2) style.
    /// `data` must be at least one block size.
    pub fn encrypt_with_ad(&self, associated_data: &[u8], data: &mut [u8]) -> Result<(), Error> {
        self.encrypt_with_ad_eme2(associated_data, data)
    }

    /// Decrypts the `data` in-place using EME2 mode with arbitrary associated data.
    /// Defaults to IEEE P1619.2 (EME2) style.
    /// `data` must be at least one block size.
    pub fn decrypt_with_ad(&self, associated_data: &[u8], data: &mut [u8]) -> Result<(), Error> {
        self.decrypt_with_ad_eme2(associated_data, data)
    }

    /// Encrypts the `data` in-place using EME2 mode with arbitrary associated data (IEEE P1619.2 compliance).
    /// `data` must be at least one block size.
    pub fn encrypt_with_ad_eme2(&self, associated_data: &[u8], data: &mut [u8]) -> Result<(), Error> {
        let t_star = self.hash_ad_eme2(associated_data);
        let res = self.encrypt_core(&t_star, data);

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

        res
    }

    /// Decrypts the `data` in-place using EME2 mode with arbitrary associated data (IEEE P1619.2 compliance).
    /// `data` must be at least one block size.
    pub fn decrypt_with_ad_eme2(&self, associated_data: &[u8], data: &mut [u8]) -> Result<(), Error> {
        let t_star = self.hash_ad_eme2(associated_data);
        let res = self.decrypt_core(&t_star, data);

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

        res
    }

    /// Encrypts the `data` in-place using EME2 mode with arbitrary associated data (EME* compliance).
    /// `data` must be at least one block size.
    pub fn encrypt_with_ad_emestar(&self, associated_data: &[u8], data: &mut [u8]) -> Result<(), Error> {
        let t_star = self.hash_ad_emestar(associated_data);
        let res = self.encrypt_core(&t_star, data);

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

        res
    }

    /// Decrypts the `data` in-place using EME2 mode with arbitrary associated data (EME* compliance).
    /// `data` must be at least one block size.
    pub fn decrypt_with_ad_emestar(&self, associated_data: &[u8], data: &mut [u8]) -> Result<(), Error> {
        let t_star = self.hash_ad_emestar(associated_data);
        let res = self.decrypt_core(&t_star, data);

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

        res
    }

    fn encrypt_core(&self, tweak_block: &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 };

        // PASS 1: data[i] = ppp_i
        let mut l_current = self.key2.clone();

        for i in 0..last_full {
            let block: &mut Block<C> = (&mut data[i * bs..(i + 1) * bs]).try_into().expect("slice bounds match");
            xor_into::<C>(block, &l_current);
            encrypt_block(&self.cipher, 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<C> = (&data[i * bs..(i + 1) * bs]).try_into().expect("slice bounds match");
            xor_into::<C>(&mut sp, ppp_i);
        }
        if last_full < m {
            xor_into::<C>(&mut sp, &ppp_m);
        }

        let ppp_0: &Block<C> = (&data[0..bs]).try_into().expect("slice bounds match");

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

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

        if last_full < m {
            mm.copy_from_slice(&mp_1);
            encrypt_block(&self.cipher, &mut mm);
            mc_1 = mm.clone();
            encrypt_block(&self.cipher, &mut mc_1);

            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;
        } else {
            mc_1 = mp_1.clone();
            encrypt_block(&self.cipher, &mut mc_1);
        }

        let mut m_1 = Block::<C>::default();
        xor_blocks::<C>(&mut m_1, &mp_1, &mc_1);

        let mut current_m_j = m_1.clone();
        let mut current_m_k = m_1.clone();

        // PASS 2: data[i] = ccc_i
        for i in 1..last_full {
            let block: &mut Block<C> = (&mut data[i * bs..(i + 1) * bs]).try_into().expect("slice bounds match");

            let k = i & 127;
            if k == 0 {
                let mut mp_j = Block::<C>::default();
                xor_blocks::<C>(&mut mp_j, block, &m_1);
                let mut mc_j = mp_j.clone();
                encrypt_block(&self.cipher, &mut mc_j);
                xor_blocks::<C>(&mut current_m_j, &mp_j, &mc_j);
                xor_blocks::<C>(block, &mc_j, &m_1);
                current_m_k = current_m_j.clone();

                #[cfg(feature = "zeroize")]
                {
                    mp_j.zeroize();
                    mc_j.zeroize();
                }
            } else {
                current_m_k = C::BlockSize::mult_by_two(&current_m_k);
                xor_into::<C>(block, &current_m_k);
            }
        }

        let mut sc = Block::<C>::default();
        for i in 1..last_full {
            let ccc_i: &Block<C> = (&data[i * bs..(i + 1) * bs]).try_into().expect("slice bounds match");
            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, &mc_1, &sc);
        xor_into::<C>(&mut ccc_0, tweak_block);
        data[0..bs].copy_from_slice(&ccc_0);

        // PASS 3: data[i] = ciphertext
        l_current = self.key2.clone();
        for i in 0..last_full {
            let block: &mut Block<C> = (&mut data[i * bs..(i + 1) * bs]).try_into().expect("slice bounds match");
            encrypt_block(&self.cipher, block);
            xor_into::<C>(block, &l_current);
            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")]
        {
            l_current.zeroize();
            ppp_m.zeroize();
            sp.zeroize();
            mp_1.zeroize();
            mc_1.zeroize();
            ccc_m.zeroize();
            c_m.zeroize();
            m_1.zeroize();
            current_m_j.zeroize();
            current_m_k.zeroize();
            sc.zeroize();
            ccc_0.zeroize();
            mm.zeroize();
        }

        Ok(())
    }

    fn decrypt_core(&self, tweak_block: &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 mut l_current = self.key2.clone();

        // PASS 1: data[i] = ccc_i
        for i in 0..last_full {
            let block: &mut Block<C> = (&mut data[i * bs..(i + 1) * bs]).try_into().expect("slice bounds match");
            xor_into::<C>(block, &l_current);
            decrypt_block(&self.cipher, 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<C> = (&data[i * bs..(i + 1) * bs]).try_into().expect("slice bounds match");
            xor_into::<C>(&mut sc, ccc_i);
        }
        if last_full < m {
            xor_into::<C>(&mut sc, &ccc_m);
        }

        let ccc_0: &Block<C> = (&data[0..bs]).try_into().expect("slice bounds match");
        let mut mc_1 = Block::<C>::default();
        xor_blocks::<C>(&mut mc_1, ccc_0, &sc);
        xor_into::<C>(&mut mc_1, tweak_block);

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

        if last_full < m {
            mm.copy_from_slice(&mc_1);
            decrypt_block(&self.cipher, &mut mm);
            mp_1 = mm.clone();
            decrypt_block(&self.cipher, &mut mp_1);

            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;
        } else {
            mp_1 = mc_1.clone();
            decrypt_block(&self.cipher, &mut mp_1);
        }

        let mut m_1 = Block::<C>::default();
        xor_blocks::<C>(&mut m_1, &mp_1, &mc_1);

        let mut current_m_j = m_1.clone();
        let mut current_m_k = m_1.clone();

        // PASS 2: data[i] = ppp_i
        for i in 1..last_full {
            let block: &mut Block<C> = (&mut data[i * bs..(i + 1) * bs]).try_into().expect("slice bounds match");

            let k = i & 127;
            if k == 0 {
                let mut mc_j = Block::<C>::default();
                xor_blocks::<C>(&mut mc_j, block, &m_1);
                let mut mp_j = mc_j.clone();
                decrypt_block(&self.cipher, &mut mp_j);
                xor_blocks::<C>(&mut current_m_j, &mp_j, &mc_j);
                xor_blocks::<C>(block, &mp_j, &m_1);
                current_m_k = current_m_j.clone();

                #[cfg(feature = "zeroize")]
                {
                    mc_j.zeroize();
                    mp_j.zeroize();
                }
            } else {
                current_m_k = C::BlockSize::mult_by_two(&current_m_k);
                xor_into::<C>(block, &current_m_k);
            }
        }

        let mut sp = Block::<C>::default();
        for i in 1..last_full {
            let ppp_i: &Block<C> = (&data[i * bs..(i + 1) * bs]).try_into().expect("slice bounds match");
            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, &mp_1, &sp);
        xor_into::<C>(&mut ppp_0, tweak_block);
        data[0..bs].copy_from_slice(&ppp_0);

        // PASS 3: data[i] = plaintext
        l_current = self.key2.clone();
        for i in 0..last_full {
            let block: &mut Block<C> = (&mut data[i * bs..(i + 1) * bs]).try_into().expect("slice bounds match");
            decrypt_block(&self.cipher, block);
            xor_into::<C>(block, &l_current);
            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")]
        {
            l_current.zeroize();
            ccc_m.zeroize();
            sc.zeroize();
            mc_1.zeroize();
            mp_1.zeroize();
            ppp_m.zeroize();
            p_m.zeroize();
            m_1.zeroize();
            current_m_j.zeroize();
            current_m_k.zeroize();
            sp.zeroize();
            ppp_0.zeroize();
            mm.zeroize();
        }

        Ok(())
    }
}