eme2 0.1.3

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
use cipher::{
    Block, BlockCipherDecrypt, BlockCipherEncrypt, BlockSizeUser, InnerIvInit, Iv,
    IvSizeUser, consts::U16, common::InnerUser,
};
use core::fmt;

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

const BLOCK_SIZE: usize = 16;

/// Error types for EME2 operations.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Error {
    /// The provided data is shorter than the minimum block size (16 bytes).
    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 16 bytes for EME2"),
        }
    }
}

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

#[inline]
fn xor_blocks(out: &mut [u8; BLOCK_SIZE], a: &[u8; BLOCK_SIZE], b: &[u8; BLOCK_SIZE]) {
    for i in 0..BLOCK_SIZE {
        out[i] = a[i] ^ b[i];
    }
}

#[inline]
fn xor_into(out: &mut [u8; BLOCK_SIZE], b: &[u8; BLOCK_SIZE]) {
    for i in 0..BLOCK_SIZE {
        out[i] ^= b[i];
    }
}

#[inline]
fn mult_by_two(val: &[u8; BLOCK_SIZE]) -> [u8; BLOCK_SIZE] {
    let mut res = [0u8; BLOCK_SIZE];

    // Load as two little-endian 64-bit limbs
    let mut v0 = u64::from_le_bytes(val[0..8].try_into().unwrap());
    let mut v1 = u64::from_le_bytes(val[8..16].try_into().unwrap());
    
    // Check if the most significant bit is set before shifting
    let carry_out = (v1 >> 63) as u8;
    
    // Shift left by 1, carrying the overflow from v0 into v1
    v1 = (v1 << 1) | (v0 >> 63);
    v0 <<= 1;
    
    // Store back into bytes
    res[0..8].copy_from_slice(&v0.to_le_bytes());
    res[8..16].copy_from_slice(&v1.to_le_bytes());
    
    // Apply polynomial mask (x^128 + x^7 + x^2 + x + 1 = 0x87) if carry_out was 1
    if carry_out != 0 {
        res[0] ^= 0x87;
    }
    
    res
}

#[inline]
fn encrypt_block<C>(cipher: &C, block: &mut [u8; 16])
where
    C: BlockCipherEncrypt + BlockSizeUser<BlockSize = U16>,
{
    let mut b: Block<C> = (*block).into();
    cipher.encrypt_block(&mut b);
    *block = b.into();
}

#[inline]
fn decrypt_block<C>(cipher: &C, block: &mut [u8; 16])
where
    C: BlockCipherDecrypt + BlockSizeUser<BlockSize = U16>,
{
    let mut b: Block<C> = (*block).into();
    cipher.decrypt_block(&mut b);
    *block = b.into();
}

/// EME2 cipher mode.
#[derive(Clone)]
#[cfg_attr(feature = "zeroize", derive(ZeroizeOnDrop))]
pub struct Eme2<C>
where
    C: BlockCipherEncrypt + BlockCipherDecrypt + BlockSizeUser<BlockSize = U16>,
{
    #[cfg_attr(feature = "zeroize", zeroize(skip))]
    cipher: C,
    tweak: Block<C>,
}

impl<C> BlockSizeUser for Eme2<C>
where
    C: BlockCipherEncrypt + BlockCipherDecrypt + BlockSizeUser<BlockSize = U16>,
{
    type BlockSize = U16;
}

impl<C> InnerUser for Eme2<C>
where
    C: BlockCipherEncrypt + BlockCipherDecrypt + BlockSizeUser<BlockSize = U16>,
{
    type Inner = C;
}

impl<C> IvSizeUser for Eme2<C>
where
    C: BlockCipherEncrypt + BlockCipherDecrypt + BlockSizeUser<BlockSize = U16>,
{
    type IvSize = U16;
}

impl<C> InnerIvInit for Eme2<C>
where
    C: BlockCipherEncrypt + BlockCipherDecrypt + BlockSizeUser<BlockSize = U16>,
{
    #[inline]
    fn inner_iv_init(cipher: C, iv: &Iv<Self>) -> Self {
        Self {
            cipher,
            tweak: *iv,
        }
    }
}

impl<C> cipher::AlgorithmName for Eme2<C>
where
    C: BlockCipherEncrypt + BlockCipherDecrypt + BlockSizeUser<BlockSize = U16> + cipher::AlgorithmName,
{
    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<BlockSize = U16> + cipher::AlgorithmName,
{
    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<BlockSize = U16>,
{
    /// Encrypts the `data` in-place using EME2 mode.
    /// `data` must be at least 16 bytes.
    pub fn encrypt(&self, data: &mut [u8]) -> Result<(), Error> {
        let len = data.len();
        if len < BLOCK_SIZE {
            return Err(Error::DataTooShort);
        }

        let tweak_slice: &[u8; 16] = self.tweak.as_slice().try_into().expect("slice bounds are mathematically guaranteed to match block size");
        let m = len.div_ceil(BLOCK_SIZE);
        let last_full = if len.is_multiple_of(BLOCK_SIZE) { m } else { m - 1 };

        let mut l_0 = [0u8; BLOCK_SIZE];
        encrypt_block(&self.cipher, &mut l_0);

        // PASS 1: data[i] = ppp_i
        let mut l_current = mult_by_two(&l_0);
        for i in 0..last_full {
            let mut block = [0u8; BLOCK_SIZE];
            block.copy_from_slice(&data[i * BLOCK_SIZE..(i + 1) * BLOCK_SIZE]);
            xor_into(&mut block, &l_current);
            encrypt_block(&self.cipher, &mut block);
            data[i * BLOCK_SIZE..(i + 1) * BLOCK_SIZE].copy_from_slice(&block);
            
            l_current = mult_by_two(&l_current);
        }

        let mut ppp_m = [0u8; BLOCK_SIZE];
        if last_full < m {
            let rem = len % BLOCK_SIZE;
            ppp_m[..rem].copy_from_slice(&data[last_full * BLOCK_SIZE..len]);
            ppp_m[rem] = 0x80;
        }

        let mut sp = [0u8; BLOCK_SIZE];
        for i in 1..last_full {
            let mut ppp_i = [0u8; BLOCK_SIZE];
            ppp_i.copy_from_slice(&data[i * BLOCK_SIZE..(i + 1) * BLOCK_SIZE]);
            xor_into(&mut sp, &ppp_i);
        }
        if last_full < m {
            xor_into(&mut sp, &ppp_m);
        }

        let mut ppp_0 = [0u8; BLOCK_SIZE];
        ppp_0.copy_from_slice(&data[0..BLOCK_SIZE]);

        let mut mp_1 = [0u8; BLOCK_SIZE];
        xor_blocks(&mut mp_1, &ppp_0, &sp);
        xor_into(&mut mp_1, tweak_slice);

        let mut mc_1;
        let mut ccc_m = [0u8; BLOCK_SIZE];
        let mut c_m = [0u8; BLOCK_SIZE];
        let mut mm = [0u8; BLOCK_SIZE];
        
        if last_full < m {
            mm.copy_from_slice(&mp_1);
            encrypt_block(&self.cipher, &mut mm);
            mc_1 = mm;
            encrypt_block(&self.cipher, &mut mc_1);

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

        let mut m_1 = [0u8; BLOCK_SIZE];
        xor_blocks(&mut m_1, &mp_1, &mc_1);

        let mut current_m_j = m_1;
        let mut current_m_k = m_1;

        // PASS 2: data[i] = ccc_i
        for i in 1..last_full {
            let mut ppp_i = [0u8; BLOCK_SIZE];
            ppp_i.copy_from_slice(&data[i * BLOCK_SIZE..(i + 1) * BLOCK_SIZE]);
            let mut ccc_i = [0u8; BLOCK_SIZE];
            
            // [PERFORMANCE FIX]: Bitwise AND for clock cycle efficiency
            let k = i & 127;
            if k == 0 {
                let mut mp_j = [0u8; BLOCK_SIZE];
                xor_blocks(&mut mp_j, &ppp_i, &m_1);
                let mut mc_j = mp_j;
                encrypt_block(&self.cipher, &mut mc_j);
                xor_blocks(&mut current_m_j, &mp_j, &mc_j);
                xor_blocks(&mut ccc_i, &mc_j, &m_1);
                current_m_k = current_m_j;

                // [SECURITY FIX]: Clean up the internal key refresh state
                #[cfg(feature = "zeroize")]
                {
                    mp_j.zeroize();
                    mc_j.zeroize();
                }
            } else {
                current_m_k = mult_by_two(&current_m_k);
                xor_blocks(&mut ccc_i, &ppp_i, &current_m_k);
            }
            data[i * BLOCK_SIZE..(i + 1) * BLOCK_SIZE].copy_from_slice(&ccc_i);
        }

        let mut sc = [0u8; BLOCK_SIZE];
        for i in 1..last_full {
            let mut ccc_i = [0u8; BLOCK_SIZE];
            ccc_i.copy_from_slice(&data[i * BLOCK_SIZE..(i + 1) * BLOCK_SIZE]);
            xor_into(&mut sc, &ccc_i);
        }
        if last_full < m {
            xor_into(&mut sc, &ccc_m);
        }

        let mut ccc_0 = [0u8; BLOCK_SIZE];
        xor_blocks(&mut ccc_0, &mc_1, &sc);
        xor_into(&mut ccc_0, tweak_slice);
        data[0..BLOCK_SIZE].copy_from_slice(&ccc_0);

        // PASS 3: data[i] = ciphertext
        l_current = mult_by_two(&l_0);
        for i in 0..last_full {
            let mut cc_i = [0u8; BLOCK_SIZE];
            cc_i.copy_from_slice(&data[i * BLOCK_SIZE..(i + 1) * BLOCK_SIZE]);
            encrypt_block(&self.cipher, &mut cc_i);
            xor_into(&mut cc_i, &l_current);
            data[i * BLOCK_SIZE..(i + 1) * BLOCK_SIZE].copy_from_slice(&cc_i);
            
            l_current = mult_by_two(&l_current);
        }

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

        #[cfg(feature = "zeroize")]
        {
            l_0.zeroize();
            l_current.zeroize();
            ppp_m.zeroize();
            sp.zeroize();
            ppp_0.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(); // [SECURITY FIX]
        }

        Ok(())
    }

    /// Decrypts the `data` in-place using EME2 mode.
    /// `data` must be at least 16 bytes.
    pub fn decrypt(&self, data: &mut [u8]) -> Result<(), Error> {
        let len = data.len();
        if len < BLOCK_SIZE {
            return Err(Error::DataTooShort);
        }

        let tweak_slice: &[u8; 16] = self.tweak.as_slice().try_into().expect("slice bounds are mathematically guaranteed to match block size");
        let m = len.div_ceil(BLOCK_SIZE);
        let last_full = if len.is_multiple_of(BLOCK_SIZE) { m } else { m - 1 };

        let mut l_0 = [0u8; BLOCK_SIZE];
        encrypt_block(&self.cipher, &mut l_0);

        let mut l_current = mult_by_two(&l_0);
        // PASS 1: data[i] = ccc_i
        for i in 0..last_full {
            let mut block = [0u8; BLOCK_SIZE];
            block.copy_from_slice(&data[i * BLOCK_SIZE..(i + 1) * BLOCK_SIZE]);
            xor_into(&mut block, &l_current);
            decrypt_block(&self.cipher, &mut block); 
            data[i * BLOCK_SIZE..(i + 1) * BLOCK_SIZE].copy_from_slice(&block);
            
            l_current = mult_by_two(&l_current);
        }

        let mut ccc_m = [0u8; BLOCK_SIZE];
        if last_full < m {
            let rem = len % BLOCK_SIZE;
            ccc_m[..rem].copy_from_slice(&data[last_full * BLOCK_SIZE..len]);
            ccc_m[rem] = 0x80;
        }

        let mut sc = [0u8; BLOCK_SIZE];
        for i in 1..last_full {
            let mut ccc_i = [0u8; BLOCK_SIZE];
            ccc_i.copy_from_slice(&data[i * BLOCK_SIZE..(i + 1) * BLOCK_SIZE]);
            xor_into(&mut sc, &ccc_i);
        }
        if last_full < m {
            xor_into(&mut sc, &ccc_m);
        }

        let mut ccc_0 = [0u8; BLOCK_SIZE];
        ccc_0.copy_from_slice(&data[0..BLOCK_SIZE]);

        let mut mc_1 = [0u8; BLOCK_SIZE];
        xor_blocks(&mut mc_1, &ccc_0, &sc);
        xor_into(&mut mc_1, tweak_slice);

        let mut mp_1;
        let mut ppp_m = [0u8; BLOCK_SIZE];
        let mut p_m = [0u8; BLOCK_SIZE];
        let mut mm = [0u8; BLOCK_SIZE];

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

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

        let mut m_1 = [0u8; BLOCK_SIZE];
        xor_blocks(&mut m_1, &mp_1, &mc_1);

        let mut current_m_j = m_1;
        let mut current_m_k = m_1;

        // PASS 2: data[i] = ppp_i
        for i in 1..last_full {
            let mut ccc_i = [0u8; BLOCK_SIZE];
            ccc_i.copy_from_slice(&data[i * BLOCK_SIZE..(i + 1) * BLOCK_SIZE]);
            let mut ppp_i = [0u8; BLOCK_SIZE];

            let k = i & 127;
            if k == 0 {
                let mut mc_j = [0u8; BLOCK_SIZE];
                xor_blocks(&mut mc_j, &ccc_i, &m_1);
                let mut mp_j = mc_j;
                decrypt_block(&self.cipher, &mut mp_j);
                xor_blocks(&mut current_m_j, &mp_j, &mc_j);
                xor_blocks(&mut ppp_i, &mp_j, &m_1);
                current_m_k = current_m_j;

                #[cfg(feature = "zeroize")]
                {
                    mc_j.zeroize();
                    mp_j.zeroize();
                }
            } else {
                current_m_k = mult_by_two(&current_m_k);
                xor_blocks(&mut ppp_i, &ccc_i, &current_m_k);
            }
            data[i * BLOCK_SIZE..(i + 1) * BLOCK_SIZE].copy_from_slice(&ppp_i);
        }

        let mut sp = [0u8; BLOCK_SIZE];
        for i in 1..last_full {
            let mut ppp_i = [0u8; BLOCK_SIZE];
            ppp_i.copy_from_slice(&data[i * BLOCK_SIZE..(i + 1) * BLOCK_SIZE]);
            xor_into(&mut sp, &ppp_i);
        }
        if last_full < m {
            xor_into(&mut sp, &ppp_m);
        }

        let mut ppp_0 = [0u8; BLOCK_SIZE];
        xor_blocks(&mut ppp_0, &mp_1, &sp);
        xor_into(&mut ppp_0, tweak_slice);
        data[0..BLOCK_SIZE].copy_from_slice(&ppp_0);

        // PASS 3: data[i] = plaintext
        l_current = mult_by_two(&l_0);
        for i in 0..last_full {
            let mut pp_i = [0u8; BLOCK_SIZE];
            pp_i.copy_from_slice(&data[i * BLOCK_SIZE..(i + 1) * BLOCK_SIZE]);
            decrypt_block(&self.cipher, &mut pp_i);
            xor_into(&mut pp_i, &l_current);
            data[i * BLOCK_SIZE..(i + 1) * BLOCK_SIZE].copy_from_slice(&pp_i);
            
            l_current = mult_by_two(&l_current);
        }

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

        #[cfg(feature = "zeroize")]
        {
            l_0.zeroize();
            l_current.zeroize();
            ccc_m.zeroize();
            sc.zeroize();
            ccc_0.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(())
    }
}