tc_aead_cipher 0.1.1

AEAD contracts and the GCM, GCM-SIV, CCM, KCCM, EAX and OCB modes over any tc_block_cipher engine.
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
//! GCM authenticated-encryption engine.

use super::{BLOCK_BYTES, MAX_MAC_BYTES, MIN_MAC_BYTES, Multiplier};
#[cfg(feature = "alloc")]
use crate::ParamsWithAeadOwned;
use crate::ParamsWithAeadRef;
use crate::{
    AeadBlockCipher, AeadCipher, AeadCipherInit, AeadError, AeadInitError, InitialAadParams,
    MacSizeParams, NonceParams,
};
use core::fmt;
use core::fmt::{Display, Formatter};
use tc_block_cipher::{BlockCipher, BlockCipherInit, CipherDirection, KeyParams};
use tc_constant_time::fixed_time_eq;
use tc_zeroize::Zeroize;

const MAX_BLOCKS: u32 = u32::MAX - 1;
const MAX_BUFFER_BYTES: usize = BLOCK_BYTES + MAX_MAC_BYTES;

#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
enum State {
    #[default]
    Uninitialized,
    Encrypt,
    Decrypt,
    Finalized(CipherDirection),
}

/// Galois/Counter Mode authenticated encryption over a 16-byte block cipher.
///
/// The implementation uses a portable, fixed-work GHASH multiplier. It does
/// not expose the obsolete multiplier or exponentiator injection interfaces
/// found in older Bouncy Castle APIs.
///
/// Encryption refuses an `init` whose key and nonce match the previous `init`
/// of the same instance. Nothing tracks nonces across instances or restarts,
/// so the caller must still never reuse a nonce under one key.
///
/// Constant time exactly when the cipher is: GHASH multiplies bit by bit with
/// masks, and neither the counter increment nor the tag comparison branches on
/// data. Only public lengths decide how much work is done.
///
/// # Example
///
/// ```
/// use tc_aead_cipher::{AeadCipher, AeadCipherInit, AeadParamsRef, GcmBlockCipher};
/// use tc_aes::AesEngine;
/// use tc_block_cipher::CipherDirection;
///
/// let (key, nonce) = ([0x42; 16], [0x24; 12]);
/// let params = AeadParamsRef::new(&key, &nonce, 16, b"header");
/// let plaintext = b"attack at dawn";
/// let mut cipher = GcmBlockCipher::new(AesEngine::new());
///
/// cipher.init(CipherDirection::Encrypt, &params)?;
/// let mut sealed = vec![0; cipher.output_len(plaintext.len())?];
/// let mut sealed_len = cipher.process_bytes(plaintext, &mut sealed)?;
/// sealed_len += cipher.do_final(&mut sealed[sealed_len..])?;
///
/// cipher.init(CipherDirection::Decrypt, &params)?;
/// let mut opened = vec![0; cipher.output_len(sealed_len)?];
/// let mut opened_len = cipher.process_bytes(&sealed[..sealed_len], &mut opened)?;
/// opened_len += cipher.do_final(&mut opened[opened_len..])?;
/// assert_eq!(&opened[..opened_len], plaintext);
/// # Ok::<(), Box<dyn core::error::Error>>(())
/// ```
pub struct GcmBlockCipher<C> {
    cipher: C,
    state: State,
    mac_size: usize,
    // H and J0 of the last successful init, compared to refuse nonce reuse.
    has_key_nonce: bool,
    multiplier: Multiplier,
    j0: [u8; BLOCK_BYTES],
    counter: [u8; BLOCK_BYTES],
    blocks_remaining: u32,
    buffer: [u8; MAX_BUFFER_BYTES],
    buffer_pos: usize,
    total_length: u64,
    hash: [u8; BLOCK_BYTES],
    aad_hash: [u8; BLOCK_BYTES],
    aad_block: [u8; BLOCK_BYTES],
    aad_block_pos: usize,
    aad_length: u64,
    aad_finalized: bool,
    data_started: bool,
    initial_aad_hash: [u8; BLOCK_BYTES],
    initial_aad_block: [u8; BLOCK_BYTES],
    initial_aad_block_pos: usize,
    initial_aad_length: u64,
    mac: Option<[u8; MAX_MAC_BYTES]>,
}

impl<C> GcmBlockCipher<C> {
    /// Creates an uninitialized GCM engine around `cipher`. Constant time.
    pub const fn new(cipher: C) -> Self {
        Self {
            cipher,
            state: State::Uninitialized,
            mac_size: 0,
            has_key_nonce: false,
            multiplier: Multiplier::new([0; BLOCK_BYTES]),
            j0: [0; BLOCK_BYTES],
            counter: [0; BLOCK_BYTES],
            blocks_remaining: 0,
            buffer: [0; MAX_BUFFER_BYTES],
            buffer_pos: 0,
            total_length: 0,
            hash: [0; BLOCK_BYTES],
            aad_hash: [0; BLOCK_BYTES],
            aad_block: [0; BLOCK_BYTES],
            aad_block_pos: 0,
            aad_length: 0,
            aad_finalized: false,
            data_started: false,
            initial_aad_hash: [0; BLOCK_BYTES],
            initial_aad_block: [0; BLOCK_BYTES],
            initial_aad_block_pos: 0,
            initial_aad_length: 0,
            mac: None,
        }
    }

    fn direction<E>(&self) -> Result<CipherDirection, AeadError<E>> {
        match self.state {
            State::Encrypt => Ok(CipherDirection::Encrypt),
            State::Decrypt => Ok(CipherDirection::Decrypt),
            State::Finalized(_) => Err(AeadError::AlreadyFinalized),
            State::Uninitialized => Err(AeadError::NotInitialized),
        }
    }

    fn is_decrypting(&self) -> bool {
        matches!(
            self.state,
            State::Decrypt | State::Finalized(CipherDirection::Decrypt)
        )
    }

    fn buffer_capacity(&self) -> usize {
        if self.is_decrypting() {
            BLOCK_BYTES + self.mac_size
        } else {
            BLOCK_BYTES
        }
    }

    fn reset_blank(&mut self) {
        self.counter = self.j0;
        self.blocks_remaining = MAX_BLOCKS;
        self.buffer.fill(0);
        self.buffer_pos = 0;
        self.total_length = 0;
        self.hash.fill(0);
        self.aad_hash.fill(0);
        self.aad_block.fill(0);
        self.aad_block_pos = 0;
        self.aad_length = 0;
        self.aad_finalized = false;
        self.data_started = false;
    }

    fn restore_initial_state(&mut self) {
        self.reset_blank();
        self.aad_hash = self.initial_aad_hash;
        self.aad_block = self.initial_aad_block;
        self.aad_block_pos = self.initial_aad_block_pos;
        self.aad_length = self.initial_aad_length;
    }

    fn save_initial_aad_state(&mut self) {
        self.initial_aad_hash = self.aad_hash;
        self.initial_aad_block = self.aad_block;
        self.initial_aad_block_pos = self.aad_block_pos;
        self.initial_aad_length = self.aad_length;
    }

    fn feed_aad(&mut self, mut input: &[u8]) {
        if self.aad_block_pos != 0 {
            let take = (BLOCK_BYTES - self.aad_block_pos).min(input.len());
            self.aad_block[self.aad_block_pos..self.aad_block_pos + take]
                .copy_from_slice(&input[..take]);
            self.aad_block_pos += take;
            input = &input[take..];
            if self.aad_block_pos < BLOCK_BYTES {
                return;
            }
            ghash_block(&self.multiplier, &mut self.aad_hash, &self.aad_block);
            self.aad_block.fill(0);
            self.aad_block_pos = 0;
        }

        while input.len() >= BLOCK_BYTES {
            let block: &[u8; BLOCK_BYTES] = input[..BLOCK_BYTES].try_into().unwrap();
            ghash_block(&self.multiplier, &mut self.aad_hash, block);
            input = &input[BLOCK_BYTES..];
        }

        self.aad_block[..input.len()].copy_from_slice(input);
        self.aad_block_pos = input.len();
    }

    fn start_data(&mut self) {
        if self.aad_finalized {
            return;
        }

        if self.aad_block_pos != 0 {
            let mut block = [0u8; BLOCK_BYTES];
            block[..self.aad_block_pos].copy_from_slice(&self.aad_block[..self.aad_block_pos]);
            ghash_block(&self.multiplier, &mut self.aad_hash, &block);
        }
        self.hash = self.aad_hash;
        self.aad_finalized = true;
    }
}

impl<C> GcmBlockCipher<C>
where
    C: BlockCipher,
{
    fn calculate_j0(multiplier: &Multiplier, nonce: &[u8]) -> [u8; BLOCK_BYTES] {
        if nonce.len() == 12 {
            let mut j0 = [0u8; BLOCK_BYTES];
            j0[..12].copy_from_slice(nonce);
            j0[15] = 1;
            return j0;
        }

        let nonce_bits = u64::try_from(nonce.len()).unwrap() * 8;
        let mut j0 = [0u8; BLOCK_BYTES];
        let mut remaining = nonce;
        while remaining.len() >= BLOCK_BYTES {
            let block: &[u8; BLOCK_BYTES] = remaining[..BLOCK_BYTES].try_into().unwrap();
            ghash_block(multiplier, &mut j0, block);
            remaining = &remaining[BLOCK_BYTES..];
        }
        if !remaining.is_empty() {
            let mut block = [0u8; BLOCK_BYTES];
            block[..remaining.len()].copy_from_slice(remaining);
            ghash_block(multiplier, &mut j0, &block);
        }

        let mut length_block = [0u8; BLOCK_BYTES];
        length_block[8..].copy_from_slice(&nonce_bits.to_be_bytes());
        ghash_block(multiplier, &mut j0, &length_block);
        j0
    }

    fn check_block_count(&self, block_count: usize) -> Result<(), AeadError<C::Error>> {
        let available = usize::try_from(self.blocks_remaining).unwrap_or(usize::MAX);
        if block_count > available {
            return Err(AeadError::InputTooLong);
        }
        Ok(())
    }

    fn next_counter_block(&mut self) -> Result<[u8; BLOCK_BYTES], AeadError<C::Error>> {
        if self.blocks_remaining == 0 {
            return Err(AeadError::InputTooLong);
        }
        self.blocks_remaining -= 1;

        let value = u32::from_be_bytes(self.counter[12..].try_into().unwrap()).wrapping_add(1);
        self.counter[12..].copy_from_slice(&value.to_be_bytes());
        let mut output = [0u8; BLOCK_BYTES];
        self.cipher
            .process_block(&self.counter, &mut output)
            .map_err(AeadError::Cipher)?;
        Ok(output)
    }

    fn process_full_block(
        &mut self,
        direction: CipherDirection,
        input: &[u8; BLOCK_BYTES],
        output: &mut [u8],
    ) -> Result<(), AeadError<C::Error>> {
        self.start_data();
        let counter = self.next_counter_block()?;
        match direction {
            CipherDirection::Encrypt => {
                let ciphertext = core::array::from_fn(|index| input[index] ^ counter[index]);
                output[..BLOCK_BYTES].copy_from_slice(&ciphertext);
                ghash_block(&self.multiplier, &mut self.hash, &ciphertext);
            }
            CipherDirection::Decrypt => {
                ghash_block(&self.multiplier, &mut self.hash, input);
                for index in 0..BLOCK_BYTES {
                    output[index] = input[index] ^ counter[index];
                }
            }
        }
        self.total_length += BLOCK_BYTES as u64;
        Ok(())
    }

    fn calculate_tag(&mut self) -> Result<[u8; MAX_MAC_BYTES], AeadError<C::Error>> {
        let aad_bits = self
            .aad_length
            .checked_mul(8)
            .ok_or(AeadError::InputTooLong)?;
        let data_bits = self
            .total_length
            .checked_mul(8)
            .ok_or(AeadError::InputTooLong)?;
        let mut length_block = [0u8; BLOCK_BYTES];
        length_block[..8].copy_from_slice(&aad_bits.to_be_bytes());
        length_block[8..].copy_from_slice(&data_bits.to_be_bytes());
        ghash_block(&self.multiplier, &mut self.hash, &length_block);

        let mut tag_mask = [0u8; BLOCK_BYTES];
        self.cipher
            .process_block(&self.j0, &mut tag_mask)
            .map_err(AeadError::Cipher)?;
        Ok(core::array::from_fn(|index| {
            tag_mask[index] ^ self.hash[index]
        }))
    }
}

impl<C> Display for GcmBlockCipher<C>
where
    C: BlockCipher + Display,
{
    /// Writes the cipher's name followed by `/GCM`. Constant time: no key
    /// material is inspected.
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        self.cipher.fmt(f)?;
        f.write_str("/GCM")
    }
}

impl<C> AeadCipher for GcmBlockCipher<C>
where
    C: BlockCipher,
    C::Error: 'static,
{
    type Error = AeadError<C::Error>;

    /// Authenticates `input` as associated data. Constant time exactly when the
    /// cipher is: only its length decides the work.
    fn process_aad_bytes(&mut self, input: &[u8]) -> Result<(), Self::Error> {
        self.direction()?;
        if self.data_started {
            return Err(AeadError::AadAfterData);
        }
        let input_len = u64::try_from(input.len()).map_err(|_| AeadError::InputTooLong)?;
        let new_length = self
            .aad_length
            .checked_add(input_len)
            .filter(|length| *length <= u64::MAX / 8)
            .ok_or(AeadError::InputTooLong)?;

        self.mac = None;
        self.feed_aad(input);
        self.aad_length = new_length;
        Ok(())
    }

    /// Encrypts or decrypts the input that is ready and holds back the rest.
    /// Constant time exactly when the cipher is: only the input length decides
    /// the work.
    fn process_bytes(&mut self, input: &[u8], output: &mut [u8]) -> Result<usize, Self::Error> {
        let direction = self.direction()?;
        let required = self.update_output_len(input.len())?;
        if output.len() < required {
            return Err(AeadError::OutputTooShort {
                required,
                available: output.len(),
            });
        }
        self.check_block_count(required / BLOCK_BYTES)?;
        if input.is_empty() {
            return Ok(0);
        }

        self.mac = None;
        self.data_started = true;
        let capacity = self.buffer_capacity();
        let mut written = 0;
        for &byte in input {
            self.buffer[self.buffer_pos] = byte;
            self.buffer_pos += 1;
            if self.buffer_pos == capacity {
                let block: [u8; BLOCK_BYTES] = self.buffer[..BLOCK_BYTES].try_into().unwrap();
                self.process_full_block(direction, &block, &mut output[written..])?;
                written += BLOCK_BYTES;

                if direction == CipherDirection::Decrypt {
                    self.buffer.copy_within(BLOCK_BYTES..capacity, 0);
                    self.buffer_pos = self.mac_size;
                } else {
                    self.buffer_pos = 0;
                }
            }
        }
        Ok(written)
    }

    /// Processes the rest of the message and appends or verifies the tag.
    /// Constant time exactly when the cipher is: the tag is compared in fixed
    /// time, and only the result reveals whether it matched.
    fn do_final(&mut self, output: &mut [u8]) -> Result<usize, Self::Error> {
        let direction = self.direction()?;
        let extra = match direction {
            CipherDirection::Encrypt => self.buffer_pos,
            CipherDirection::Decrypt => {
                if self.buffer_pos < self.mac_size {
                    return Err(AeadError::CiphertextTooShort {
                        minimum: self.mac_size,
                        actual: self.buffer_pos,
                    });
                }
                self.buffer_pos - self.mac_size
            }
        };
        let required = if direction == CipherDirection::Encrypt {
            extra + self.mac_size
        } else {
            extra
        };
        if output.len() < required {
            return Err(AeadError::OutputTooShort {
                required,
                available: output.len(),
            });
        }
        self.check_block_count(usize::from(extra != 0))?;

        self.mac = None;
        self.start_data();
        let result = (|| {
            let mut final_plaintext = [0u8; BLOCK_BYTES];
            if extra != 0 {
                let counter = self.next_counter_block()?;
                let mut ciphertext = [0u8; BLOCK_BYTES];
                ciphertext[..extra].copy_from_slice(&self.buffer[..extra]);
                match direction {
                    CipherDirection::Encrypt => {
                        for index in 0..extra {
                            ciphertext[index] ^= counter[index];
                        }
                        output[..extra].copy_from_slice(&ciphertext[..extra]);
                    }
                    CipherDirection::Decrypt => {
                        for index in 0..extra {
                            final_plaintext[index] = ciphertext[index] ^ counter[index];
                        }
                    }
                }
                ghash_block(&self.multiplier, &mut self.hash, &ciphertext);
                self.total_length += extra as u64;
            }

            let tag = self.calculate_tag()?;
            match direction {
                CipherDirection::Encrypt => {
                    output[extra..extra + self.mac_size].copy_from_slice(&tag[..self.mac_size]);
                }
                CipherDirection::Decrypt => {
                    let received = &self.buffer[extra..extra + self.mac_size];
                    if !fixed_time_eq(&tag[..self.mac_size], received) {
                        return Err(AeadError::AuthenticationFailed);
                    }
                    output[..extra].copy_from_slice(&final_plaintext[..extra]);
                }
            }
            self.mac = Some(tag);
            Ok(required)
        })();

        self.state = State::Finalized(direction);
        self.buffer.fill(0);
        self.buffer_pos = 0;
        if result.is_err() {
            self.mac = None;
        }
        result
    }

    /// Returns the tag of the last successful `do_final`. Constant time.
    fn mac(&self) -> Option<&[u8]> {
        self.mac.as_ref().map(|mac| &mac[..self.mac_size])
    }

    /// Restarts the message when the nonce allows, as described on
    /// `AeadCipher::reset`. Constant time: it restores fixed-size state and
    /// wipes the buffers.
    fn reset(&mut self) {
        self.mac = None;
        self.state = match self.state {
            State::Encrypt if self.data_started => State::Finalized(CipherDirection::Encrypt),
            State::Encrypt => {
                self.restore_initial_state();
                State::Encrypt
            }
            State::Decrypt | State::Finalized(CipherDirection::Decrypt) => {
                self.restore_initial_state();
                State::Decrypt
            }
            State::Finalized(CipherDirection::Encrypt) => {
                self.restore_initial_state();
                State::Finalized(CipherDirection::Encrypt)
            }
            State::Uninitialized => State::Uninitialized,
        };
    }

    /// Returns the length the next `process_bytes` writes. Constant time:
    /// depends only on public lengths.
    fn update_output_len(&self, input_len: usize) -> Result<usize, Self::Error> {
        let mut total = self
            .buffer_pos
            .checked_add(input_len)
            .ok_or(AeadError::InputTooLong)?;
        // A decryption shorter than the tag outputs nothing yet; do_final
        // reports it.
        if self.is_decrypting() {
            total = total.saturating_sub(self.mac_size);
        }
        Ok(total - total % BLOCK_BYTES)
    }

    /// Returns the length `process_bytes` and `do_final` write together.
    /// Constant time: depends only on public lengths.
    fn output_len(&self, input_len: usize) -> Result<usize, Self::Error> {
        let total = self
            .buffer_pos
            .checked_add(input_len)
            .ok_or(AeadError::InputTooLong)?;
        if self.is_decrypting() {
            Ok(total.saturating_sub(self.mac_size))
        } else {
            total
                .checked_add(self.mac_size)
                .ok_or(AeadError::InputTooLong)
        }
    }
}

impl<C> AeadBlockCipher for GcmBlockCipher<C>
where
    C: BlockCipher,
    C::Error: 'static,
{
    type Cipher = C;

    /// Returns the wrapped block cipher. Constant time.
    fn underlying_cipher(&self) -> &Self::Cipher {
        &self.cipher
    }
}

impl<C> GcmBlockCipher<C>
where
    C: BlockCipher,
{
    /// Initializes GCM from separate cipher parameters, nonce, initial AAD,
    /// and tag size.
    ///
    /// This entry point lets constructions such as GMAC reuse the caller's
    /// original block-cipher parameter type without introducing a wrapper type
    /// that the underlying cipher would also have to support.
    ///
    /// Constant time exactly when the cipher's key setup and block encryption
    /// are, as for `init`.
    pub fn init_with_parts<P>(
        &mut self,
        direction: CipherDirection,
        cipher_params: &P,
        nonce: &[u8],
        initial_aad: &[u8],
        mac_size: usize,
    ) -> Result<(), AeadInitError<<C as BlockCipherInit<P>>::Error>>
    where
        C: BlockCipherInit<P>,
        P: KeyParams + ?Sized,
    {
        self.state = State::Uninitialized;
        self.mac = None;
        if self.cipher.block_size() != BLOCK_BYTES {
            return Err(AeadInitError::InvalidBlockSize {
                actual: self.cipher.block_size(),
                required: BLOCK_BYTES,
            });
        }

        if nonce.is_empty()
            || u64::try_from(nonce.len())
                .ok()
                .and_then(|length| length.checked_mul(8))
                .is_none()
        {
            return Err(AeadInitError::InvalidNonceLength {
                actual: nonce.len(),
            });
        }
        if !(MIN_MAC_BYTES..=MAX_MAC_BYTES).contains(&mac_size) {
            return Err(AeadInitError::InvalidMacSize { actual: mac_size });
        }
        let initial_aad_len = u64::try_from(initial_aad.len())
            .ok()
            .filter(|length| *length <= u64::MAX / 8)
            .ok_or(AeadInitError::InvalidInitialAadLength {
                actual: initial_aad.len(),
            })?;

        self.cipher
            .init(CipherDirection::Encrypt, cipher_params)
            .map_err(AeadInitError::Cipher)?;
        // The cipher was just keyed and has 16-byte blocks, so encrypting one
        // block can fail only if the cipher breaks its own contract.
        let mut h = [0u8; BLOCK_BYTES];
        self.cipher
            .process_block(&[0; BLOCK_BYTES], &mut h)
            .map_err(|_| AeadInitError::InternalFailure)?;
        let multiplier = Multiplier::new(h);
        h.zeroize();
        let mut j0 = Self::calculate_j0(&multiplier, nonce);

        // Reuse means the same H and J0, which is what breaks GCM; unlike the
        // raw key and nonce, these have a fixed size and need no allocation.
        if direction == CipherDirection::Encrypt
            && self.has_key_nonce
            && fixed_time_eq(multiplier.h(), self.multiplier.h()) & fixed_time_eq(&j0, &self.j0)
        {
            j0.zeroize();
            return Err(AeadInitError::NonceReuse);
        }

        self.mac_size = mac_size;
        self.multiplier = multiplier;
        self.j0 = j0;
        self.has_key_nonce = true;

        self.reset_blank();
        self.aad_length = initial_aad_len;
        self.feed_aad(initial_aad);
        self.save_initial_aad_state();
        self.state = match direction {
            CipherDirection::Encrypt => State::Encrypt,
            CipherDirection::Decrypt => State::Decrypt,
        };
        Ok(())
    }
}

impl<C> Drop for GcmBlockCipher<C> {
    fn drop(&mut self) {
        self.j0.zeroize();
        self.counter.zeroize();
        self.buffer.zeroize();
        self.hash.zeroize();
        self.aad_hash.zeroize();
        self.aad_block.zeroize();
        self.initial_aad_hash.zeroize();
        self.initial_aad_block.zeroize();
        self.mac.zeroize();
    }
}

impl<C, P> AeadCipherInit<P> for GcmBlockCipher<C>
where
    C: BlockCipher + BlockCipherInit<P>,
    <C as BlockCipherInit<P>>::Error: 'static,
    P: KeyParams + NonceParams + InitialAadParams + MacSizeParams + ?Sized,
{
    type Error = AeadInitError<<C as BlockCipherInit<P>>::Error>;

    /// Keys the cipher and starts a message, as described on
    /// `AeadCipherInit::init`. Constant time exactly when the cipher's key
    /// setup and block encryption are: validation reads only public lengths,
    /// and the nonce-reuse check compares a key-derived block in fixed time.
    fn init(&mut self, direction: CipherDirection, params: &P) -> Result<(), Self::Error> {
        self.init_with_parts(
            direction,
            params,
            params.nonce(),
            params.initial_aad(),
            params.mac_size(),
        )
    }
}

impl<'a, C, P> AeadCipherInit<ParamsWithAeadRef<'a, P>> for GcmBlockCipher<C>
where
    C: BlockCipher + BlockCipherInit<P>,
    <C as BlockCipherInit<P>>::Error: 'static,
    P: KeyParams + ?Sized,
{
    type Error = AeadInitError<<C as BlockCipherInit<P>>::Error>;

    /// Keys the cipher with the inner parameters alone and starts a message
    /// with the nonce, tag size and initial associated data, as with the
    /// parameters over `KeyParams`. Constant time exactly when the cipher's
    /// key setup and block encryption are, as for that `init`.
    fn init(
        &mut self,
        direction: CipherDirection,
        params: &ParamsWithAeadRef<'a, P>,
    ) -> Result<(), Self::Error> {
        self.init_with_parts(
            direction,
            params.params(),
            params.nonce(),
            params.initial_aad(),
            params.mac_size(),
        )
    }
}

#[cfg(feature = "alloc")]
impl<C, P> AeadCipherInit<ParamsWithAeadOwned<P>> for GcmBlockCipher<C>
where
    C: BlockCipher + BlockCipherInit<P>,
    <C as BlockCipherInit<P>>::Error: 'static,
    P: KeyParams,
{
    type Error = AeadInitError<<C as BlockCipherInit<P>>::Error>;

    /// Keys the cipher with the inner parameters alone and starts a message
    /// with the nonce, tag size and initial associated data, as with the
    /// parameters over `KeyParams`. Constant time exactly when the cipher's
    /// key setup and block encryption are, as for that `init`.
    fn init(
        &mut self,
        direction: CipherDirection,
        params: &ParamsWithAeadOwned<P>,
    ) -> Result<(), Self::Error> {
        self.init_with_parts(
            direction,
            params.params(),
            params.nonce(),
            params.initial_aad(),
            params.mac_size(),
        )
    }
}

fn ghash_block(multiplier: &Multiplier, state: &mut [u8; BLOCK_BYTES], block: &[u8; BLOCK_BYTES]) {
    for index in 0..BLOCK_BYTES {
        state[index] ^= block[index];
    }
    multiplier.multiply_h(state);
}