pgp 0.20.0

OpenPGP implementation in Rust
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
//! Decryption for SEIPDv1 encrypted data packets and SED legacy encrypted data packets.
//!
//! See <https://www.rfc-editor.org/rfc/rfc9580#name-version-1-symmetrically-enc>
//! and <https://www.rfc-editor.org/rfc/rfc9580#name-symmetrically-encrypted-dat>

use std::io::{self, BufRead, Read};

use aes::{Aes128, Aes192, Aes256};
use blowfish::Blowfish;
use bytes::{Buf, BytesMut};
use camellia::{Camellia128, Camellia192, Camellia256};
use cast5::Cast5;
use cfb_mode::{cipher::KeyIvInit, BufDecryptor};
use cipher::{BlockCipher, BlockDecrypt, BlockEncryptMut, BlockSizeUser};
use des::TdesEde3;
use idea::Idea;
use log::debug;
use sha1::{Digest, Sha1};
use subtle::ConstantTimeEq;
use twofish::Twofish;
use zeroize::Zeroizing;

use crate::{
    crypto::sym::SymmetricKeyAlgorithm,
    errors::{bail, Error, Result},
    parsing_reader::BufReadParsing,
    types::Seipdv1ReadMode,
    util::{fill_buffer, fill_buffer_bytes},
};

const MDC_LEN: usize = 22;
const BUFFER_SIZE: usize = 1024 * 8;

#[derive(Debug)]
#[allow(clippy::large_enum_variant)]
pub enum StreamDecryptor<R>
where
    R: BufRead,
{
    Idea(StreamDecryptorInner<Idea, R>),
    TripleDes(StreamDecryptorInner<TdesEde3, R>),
    Cast5(StreamDecryptorInner<Cast5, R>),
    Blowfish(StreamDecryptorInner<Blowfish, R>),
    Aes128(StreamDecryptorInner<Aes128, R>),
    Aes192(StreamDecryptorInner<Aes192, R>),
    Aes256(StreamDecryptorInner<Aes256, R>),
    Twofish(StreamDecryptorInner<Twofish, R>),
    Camellia128(StreamDecryptorInner<Camellia128, R>),
    Camellia192(StreamDecryptorInner<Camellia192, R>),
    Camellia256(StreamDecryptorInner<Camellia256, R>),
}

impl<R> BufRead for StreamDecryptor<R>
where
    R: BufRead,
{
    fn fill_buf(&mut self) -> io::Result<&[u8]> {
        match self {
            Self::Idea(i) => i.fill_buf(),
            Self::TripleDes(i) => i.fill_buf(),
            Self::Cast5(i) => i.fill_buf(),
            Self::Blowfish(i) => i.fill_buf(),
            Self::Aes128(i) => i.fill_buf(),
            Self::Aes192(i) => i.fill_buf(),
            Self::Aes256(i) => i.fill_buf(),
            Self::Twofish(i) => i.fill_buf(),
            Self::Camellia128(i) => i.fill_buf(),
            Self::Camellia192(i) => i.fill_buf(),
            Self::Camellia256(i) => i.fill_buf(),
        }
    }

    fn consume(&mut self, amt: usize) {
        match self {
            Self::Idea(i) => i.consume(amt),
            Self::TripleDes(i) => i.consume(amt),
            Self::Cast5(i) => i.consume(amt),
            Self::Blowfish(i) => i.consume(amt),
            Self::Aes128(i) => i.consume(amt),
            Self::Aes192(i) => i.consume(amt),
            Self::Aes256(i) => i.consume(amt),
            Self::Twofish(i) => i.consume(amt),
            Self::Camellia128(i) => i.consume(amt),
            Self::Camellia192(i) => i.consume(amt),
            Self::Camellia256(i) => i.consume(amt),
        }
    }
}

impl<R> Read for StreamDecryptor<R>
where
    R: BufRead,
{
    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
        match self {
            Self::Idea(i) => i.read(buf),
            Self::TripleDes(i) => i.read(buf),
            Self::Cast5(i) => i.read(buf),
            Self::Blowfish(i) => i.read(buf),
            Self::Aes128(i) => i.read(buf),
            Self::Aes192(i) => i.read(buf),
            Self::Aes256(i) => i.read(buf),
            Self::Twofish(i) => i.read(buf),
            Self::Camellia128(i) => i.read(buf),
            Self::Camellia192(i) => i.read(buf),
            Self::Camellia256(i) => i.read(buf),
        }
    }
    fn read_to_end(&mut self, buf: &mut Vec<u8>) -> io::Result<usize> {
        match self {
            Self::Idea(i) => i.read_to_end(buf),
            Self::TripleDes(i) => i.read_to_end(buf),
            Self::Cast5(i) => i.read_to_end(buf),
            Self::Blowfish(i) => i.read_to_end(buf),
            Self::Aes128(i) => i.read_to_end(buf),
            Self::Aes192(i) => i.read_to_end(buf),
            Self::Aes256(i) => i.read_to_end(buf),
            Self::Twofish(i) => i.read_to_end(buf),
            Self::Camellia128(i) => i.read_to_end(buf),
            Self::Camellia192(i) => i.read_to_end(buf),
            Self::Camellia256(i) => i.read_to_end(buf),
        }
    }
}

impl<R> StreamDecryptor<R>
where
    R: BufRead,
{
    pub fn new(
        alg: SymmetricKeyAlgorithm,
        protected: bool,
        seipdv1_read_mode: Seipdv1ReadMode,
        key: &[u8],
        ciphertext: R,
    ) -> Result<Self> {
        match alg {
            SymmetricKeyAlgorithm::Plaintext => {
                bail!("'Plaintext' is not a legal cipher for encrypted data")
            }
            SymmetricKeyAlgorithm::IDEA => Ok(StreamDecryptor::Idea(StreamDecryptorInner::new(
                protected,
                seipdv1_read_mode,
                ciphertext,
                key,
            )?)),
            SymmetricKeyAlgorithm::TripleDES => Ok(StreamDecryptor::TripleDes(
                StreamDecryptorInner::new(protected, seipdv1_read_mode, ciphertext, key)?,
            )),
            SymmetricKeyAlgorithm::CAST5 => Ok(StreamDecryptor::Cast5(StreamDecryptorInner::new(
                protected,
                seipdv1_read_mode,
                ciphertext,
                key,
            )?)),
            SymmetricKeyAlgorithm::Blowfish => Ok(StreamDecryptor::Blowfish(
                StreamDecryptorInner::new(protected, seipdv1_read_mode, ciphertext, key)?,
            )),
            SymmetricKeyAlgorithm::AES128 => Ok(StreamDecryptor::Aes128(
                StreamDecryptorInner::new(protected, seipdv1_read_mode, ciphertext, key)?,
            )),
            SymmetricKeyAlgorithm::AES192 => Ok(StreamDecryptor::Aes192(
                StreamDecryptorInner::new(protected, seipdv1_read_mode, ciphertext, key)?,
            )),
            SymmetricKeyAlgorithm::AES256 => Ok(StreamDecryptor::Aes256(
                StreamDecryptorInner::new(protected, seipdv1_read_mode, ciphertext, key)?,
            )),
            SymmetricKeyAlgorithm::Twofish => Ok(StreamDecryptor::Twofish(
                StreamDecryptorInner::new(protected, seipdv1_read_mode, ciphertext, key)?,
            )),
            SymmetricKeyAlgorithm::Camellia128 => Ok(StreamDecryptor::Camellia128(
                StreamDecryptorInner::new(protected, seipdv1_read_mode, ciphertext, key)?,
            )),
            SymmetricKeyAlgorithm::Camellia192 => Ok(StreamDecryptor::Camellia192(
                StreamDecryptorInner::new(protected, seipdv1_read_mode, ciphertext, key)?,
            )),
            SymmetricKeyAlgorithm::Camellia256 => Ok(StreamDecryptor::Camellia256(
                StreamDecryptorInner::new(protected, seipdv1_read_mode, ciphertext, key)?,
            )),
            SymmetricKeyAlgorithm::Private10 | SymmetricKeyAlgorithm::Other(_) => {
                bail!("SymmetricKeyAlgorithm {} is unsupported", u8::from(alg))
            }
        }
    }

    pub fn into_inner(self) -> R {
        match self {
            Self::Idea(i) => i.into_inner(),
            Self::TripleDes(i) => i.into_inner(),
            Self::Cast5(i) => i.into_inner(),
            Self::Blowfish(i) => i.into_inner(),
            Self::Aes128(i) => i.into_inner(),
            Self::Aes192(i) => i.into_inner(),
            Self::Aes256(i) => i.into_inner(),
            Self::Twofish(i) => i.into_inner(),
            Self::Camellia128(i) => i.into_inner(),
            Self::Camellia192(i) => i.into_inner(),
            Self::Camellia256(i) => i.into_inner(),
        }
    }

    pub fn get_ref(&self) -> &R {
        match self {
            Self::Idea(i) => i.get_ref(),
            Self::TripleDes(i) => i.get_ref(),
            Self::Cast5(i) => i.get_ref(),
            Self::Blowfish(i) => i.get_ref(),
            Self::Aes128(i) => i.get_ref(),
            Self::Aes192(i) => i.get_ref(),
            Self::Aes256(i) => i.get_ref(),
            Self::Twofish(i) => i.get_ref(),
            Self::Camellia128(i) => i.get_ref(),
            Self::Camellia192(i) => i.get_ref(),
            Self::Camellia256(i) => i.get_ref(),
        }
    }

    pub fn get_mut(&mut self) -> &mut R {
        match self {
            Self::Idea(i) => i.get_mut(),
            Self::TripleDes(i) => i.get_mut(),
            Self::Cast5(i) => i.get_mut(),
            Self::Blowfish(i) => i.get_mut(),
            Self::Aes128(i) => i.get_mut(),
            Self::Aes192(i) => i.get_mut(),
            Self::Aes256(i) => i.get_mut(),
            Self::Twofish(i) => i.get_mut(),
            Self::Camellia128(i) => i.get_mut(),
            Self::Camellia192(i) => i.get_mut(),
            Self::Camellia256(i) => i.get_mut(),
        }
    }
}

#[derive(derive_more::Debug)]
pub enum MaybeProtected {
    /// In "CheckFirst" mode, the message is first decrypted in full, to check the integrity
    /// protection.
    ///
    /// The maximum message size (in bytes) must be specified. If an encrypted message exceeds
    /// this limit, decryption returns an error (to avoid running out of memory).
    ProtectedCheckFirst {
        /// We use regular sha1 for MDC, not sha1_checked.
        /// Collisions are not currently a concern with MDC.
        hasher: Sha1,

        max_message_size: usize,
    },

    /// Decrypt the message in streaming mode, which releases plaintext before the message's
    /// integrity has been checked.
    ProtectedStreaming {
        /// We use regular sha1 for MDC, not sha1_checked.
        /// Collisions are not currently a concern with MDC.
        hasher: Sha1,
    },

    /// Encrypted message without integrity protection (using the legacy "Symmetrically Encrypted
    /// Data" packet)
    Unprotected { key: Zeroizing<Vec<u8>> },
}

/// State machine that reads from the encrypted input stream and performs decryption.
///
///
/// StreamDecryptorInner support three modes of operation:
/// - SEIPDv1 packets are read in "check first" mode by default (`Seipdv1ReadMode::CheckFirst`).
///   This mode only ever releases plaintext after the MDC check.
/// - SEIPDv1 packets can be read in "streaming" mode (`Seipdv1ReadMode::Streaming`).
///   This may release unauthenticated plaintext before the MDC check.
/// - SED packets are always read in streaming mode (`Unprotected`).
///
/// The state models which part of the input stream is currently being read:
///
/// - In the `Prefix` state, the block-size sized random octets plus two repeated octets are read
///   for SEIPDv1 (or the "random prefix" for SED).
/// - In the `Data` state, the encrypted plaintext is read from the input stream.
/// - In the `Done` state, the input stream has been fully processed.
///   For SEIPDv1 packets, in this state, the MDC has also been read and checked.
///
/// The decrypted plaintext can be obtained by a caller when reading from this object via
/// `std::io::Read`.
/// This happens only in the `Done` state for non-streaming SEIPDv1 mode.
/// In streaming modes, reading can happen in both the `Data` and `Done` states.
///
/// If any decrypted plaintext is currently available, it is stored in `buffer`, and can be
/// consumed by the reader from there.
#[derive(derive_more::Debug)]
pub enum StreamDecryptorInner<M, R>
where
    M: BlockDecrypt + BlockEncryptMut + BlockCipher,
    BufDecryptor<M>: KeyIvInit,
    R: BufRead,
{
    Prefix {
        #[debug("BufDecryptor")]
        decryptor: BufDecryptor<M>,
        prefix: BytesMut,
        source: R,
        protected: MaybeProtected,
    },
    Data {
        /// How much data has been decrypted and hashed and is available
        /// in the `buffer`, without MDC.
        data_available: usize,
        #[debug("BufDecryptor")]
        decryptor: BufDecryptor<M>,
        buffer: BytesMut,
        source: R,
        protected: MaybeProtected,
    },
    Done {
        buffer: BytesMut,
        source: R,
    },
    Error,
}

impl<M, R> StreamDecryptorInner<M, R>
where
    M: BlockDecrypt + BlockEncryptMut + BlockCipher,
    BufDecryptor<M>: KeyIvInit,
    R: BufRead,
{
    fn new(
        protected: bool,
        seipdv1_read_mode: Seipdv1ReadMode,
        source: R,
        key: &[u8],
    ) -> Result<Self> {
        debug!("protected decrypt stream");

        let bs = <M as BlockSizeUser>::block_size();

        // IV is all zeroes
        let iv_vec = vec![0u8; bs];

        let decryptor = BufDecryptor::<M>::new_from_slices(key, &iv_vec)?;
        let prefix_len = bs + 2;

        let protected = if protected {
            // checksum over unencrypted data
            let hasher = Sha1::default();

            match seipdv1_read_mode {
                Seipdv1ReadMode::CheckFirst { max_message_size } => {
                    MaybeProtected::ProtectedCheckFirst {
                        hasher,
                        max_message_size,
                    }
                }
                Seipdv1ReadMode::Streaming => MaybeProtected::ProtectedStreaming { hasher },
            }
        } else {
            MaybeProtected::Unprotected {
                key: key.to_vec().into(),
            }
        };

        Ok(Self::Prefix {
            decryptor,
            prefix: BytesMut::zeroed(prefix_len),
            source,
            protected,
        })
    }

    fn into_inner(self) -> R {
        match self {
            Self::Prefix { source, .. } => source,
            Self::Data { source, .. } => source,
            Self::Done { source, .. } => source,
            Self::Error => panic!("error state"),
        }
    }

    fn get_ref(&self) -> &R {
        match self {
            Self::Prefix { source, .. } => source,
            Self::Data { source, .. } => source,
            Self::Done { source, .. } => source,
            Self::Error => panic!("error state"),
        }
    }

    fn get_mut(&mut self) -> &mut R {
        match self {
            Self::Prefix { source, .. } => source,
            Self::Data { source, .. } => source,
            Self::Done { source, .. } => source,
            Self::Error => panic!("error state"),
        }
    }

    fn fill_inner(&mut self) -> io::Result<()> {
        if matches!(self, Self::Prefix { .. }) {
            self.advance_prefix()?;
        }
        match self {
            Self::Prefix { .. } => unreachable!("advance_prefix must transition away from Prefix"),
            Self::Data { .. } => match self.fill_data() {
                Ok(is_last_read) => {
                    if is_last_read {
                        self.finalize_data()?;
                    }
                }
                Err(e) => {
                    *self = Self::Error;
                    return Err(e);
                }
            },
            Self::Done { .. } => {}
            Self::Error => return Err(io::Error::other("decryptor is in error state")),
        }
        Ok(())
    }

    /// Reads and decrypts the CFB prefix, then transitions to the `Data` state.
    fn advance_prefix(&mut self) -> io::Result<()> {
        match std::mem::replace(self, Self::Error) {
            Self::Prefix {
                mut decryptor,
                mut prefix,
                mut source,
                mut protected,
            } => {
                let bs = <M as BlockSizeUser>::block_size();

                let read = fill_buffer(&mut source, &mut prefix, Some(bs + 2))?;
                if read < bs + 2 {
                    return Err(io::Error::new(
                        io::ErrorKind::UnexpectedEof,
                        "missing quick check",
                    ));
                }

                match protected {
                    MaybeProtected::Unprotected { ref key } => {
                        // legacy resyncing
                        let encrypted_prefix = prefix[2..].to_vec();
                        decryptor.decrypt(&mut prefix);
                        decryptor = BufDecryptor::<M>::new_from_slices(key, &encrypted_prefix)
                            .map_err(|e| io::Error::new(io::ErrorKind::InvalidInput, e))?;
                    }
                    MaybeProtected::ProtectedStreaming { ref mut hasher, .. }
                    | MaybeProtected::ProtectedCheckFirst { ref mut hasher, .. } => {
                        decryptor.decrypt(&mut prefix);
                        hasher.update(&prefix);
                    }
                }

                *self = Self::Data {
                    data_available: 0,
                    decryptor,
                    buffer: BytesMut::with_capacity(BUFFER_SIZE),
                    source,
                    protected,
                };
                Ok(())
            }
            _ => unreachable!("advance_prefix called in non-prefix state"),
        }
    }

    /// Fills the buffer with the next chunk of decrypted data.
    ///
    /// Returns `true` if the source is exhausted (last read).
    fn fill_data(&mut self) -> io::Result<bool> {
        let Self::Data {
            data_available,
            decryptor,
            buffer,
            source,
            protected,
        } = self
        else {
            unreachable!("fill_data called in non-data state")
        };

        // In streaming modes, if we have enough buffered data, don't read more now.
        match protected {
            MaybeProtected::ProtectedStreaming { .. } => {
                // For `Seipdv1Streaming`, keep at least MDC_LEN bytes back for the MDC check at the end
                if buffer.remaining() > MDC_LEN {
                    return Ok(false);
                }
            }
            MaybeProtected::Unprotected { .. } => {
                // For SED any amount is enough
                if buffer.has_remaining() {
                    return Ok(false);
                }
            }
            MaybeProtected::ProtectedCheckFirst { .. } => {}
        }

        let current_len = buffer.remaining();

        let is_last_read = match protected {
            MaybeProtected::ProtectedCheckFirst {
                max_message_size, ..
            } => {
                // Non-Streaming decryption: Read the entire input stream in one go.

                // Note: BytesMut grows as needed to hold all the data.
                let read = fill_buffer_bytes(&mut *source, buffer, *max_message_size)?;

                if read == *max_message_size {
                    // If the source yields more data, the message exceeds the supported size
                    // and we error out
                    if source.read_u8().is_ok() {
                        return Err(io::Error::other(
                            "Input stream too long for ProtectedCheckFirst mode",
                        ));
                    }
                }

                true
            }

            _ => {
                // Streaming decryption: read until `buffer` contains BUFFER_SIZE bytes
                let buf_size = BUFFER_SIZE;
                let to_read = buf_size - current_len;
                let read = fill_buffer_bytes(source, buffer, buf_size)?;

                read < to_read
            }
        };

        decryptor.decrypt(&mut buffer[current_len..]);

        match protected {
            MaybeProtected::ProtectedCheckFirst { ref mut hasher, .. }
            | MaybeProtected::ProtectedStreaming { ref mut hasher, .. } => {
                // For any valid input, the buffer must contain at least MDC_LEN bytes here
                if buffer.remaining() < MDC_LEN {
                    return Err(io::Error::other(Error::MdcError));
                }

                let start = *data_available;
                debug_assert!(buffer.len() >= MDC_LEN);
                let end = buffer.len() - MDC_LEN;
                if start < end {
                    hasher.update(&buffer[start..end]);

                    if !is_last_read {
                        *data_available += end - start;
                    }
                }
            }
            MaybeProtected::Unprotected { .. } => {
                if !is_last_read {
                    let start = *data_available;
                    let end = buffer.len();
                    if start < end {
                        *data_available += end - start;
                    }
                }
            }
        }

        Ok(is_last_read)
    }

    /// Verifies the MDC and transitions from the `Data` state to `Done`.
    fn finalize_data(&mut self) -> io::Result<()> {
        match std::mem::replace(self, Self::Error) {
            Self::Data {
                mut buffer,
                source,
                protected,
                ..
            } => {
                match protected {
                    MaybeProtected::ProtectedCheckFirst { mut hasher, .. }
                    | MaybeProtected::ProtectedStreaming { mut hasher, .. } => {
                        // Check the validity of the MDC in the message

                        // The MDC as found in the message.
                        // MDC is: 1 byte packet tag, 1 byte length prefix and 20 bytes SHA1 hash.
                        let msg_mdc = buffer.split_off(buffer.len() - MDC_LEN);

                        hasher.update(&msg_mdc[..2]);
                        let hash: [u8; 20] = hasher.finalize().into();

                        // Constant-time comparison of MDC from message against expected values
                        let mdc_ok = msg_mdc[0].ct_eq(&0xD3) // MDC tag
                            & msg_mdc[1].ct_eq(&0x14) // MDC length
                            & msg_mdc[2..].ct_eq(hash.as_slice());
                        if bool::from(!mdc_ok) {
                            return Err(io::Error::other(Error::MdcError));
                        }
                    }

                    MaybeProtected::Unprotected { .. } => {
                        // nothing to check
                    }
                }

                *self = Self::Done { buffer, source };
                Ok(())
            }
            _ => unreachable!("finalize_data called in non-Data state"),
        }
    }
}

impl<M, R> BufRead for StreamDecryptorInner<M, R>
where
    M: BlockDecrypt + BlockEncryptMut + BlockCipher,
    BufDecryptor<M>: KeyIvInit,
    R: BufRead,
{
    fn fill_buf(&mut self) -> io::Result<&[u8]> {
        self.fill_inner()?;
        match self {
            Self::Prefix { .. } => panic!("invalid state"),
            Self::Data {
                buffer,
                data_available,
                ..
            } => Ok(&buffer[..*data_available]),
            Self::Done { buffer, .. } => Ok(&buffer[..]),
            Self::Error => unreachable!("error state "),
        }
    }

    fn consume(&mut self, amt: usize) {
        match self {
            Self::Prefix { .. } => panic!("invalid state"),
            Self::Data {
                buffer,
                data_available,
                ..
            } => {
                buffer.advance(amt);
                *data_available -= amt;
            }
            Self::Done { buffer, .. } => {
                buffer.advance(amt);
            }
            Self::Error => unreachable!("error state "),
        }
    }
}

impl<M, R> Read for StreamDecryptorInner<M, R>
where
    M: BlockDecrypt + BlockEncryptMut + BlockCipher,
    BufDecryptor<M>: KeyIvInit,
    R: BufRead,
{
    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
        self.fill_inner()?;
        match self {
            Self::Prefix { .. } => panic!("invalid state"),
            Self::Data {
                buffer,
                data_available,
                ..
            } => {
                let to_write = (*data_available).min(buf.len());
                buffer.copy_to_slice(&mut buf[..to_write]);
                *data_available -= to_write;
                Ok(to_write)
            }
            Self::Done { buffer, .. } => {
                let to_write = buffer.remaining().min(buf.len());
                buffer.copy_to_slice(&mut buf[..to_write]);
                Ok(to_write)
            }
            Self::Error => unreachable!("error state"),
        }
    }

    fn read_to_end(&mut self, buf: &mut Vec<u8>) -> io::Result<usize> {
        let mut read = 0;

        loop {
            self.fill_inner()?;
            match self {
                Self::Prefix { .. } => panic!("invalid state"),
                Self::Data {
                    buffer,
                    data_available,
                    ..
                } => {
                    let to_write = *data_available;
                    buf.extend_from_slice(&buffer[..to_write]);
                    buffer.advance(to_write);
                    *data_available -= to_write;
                    read += to_write;
                }
                Self::Done { buffer, .. } => {
                    let to_write = buffer.remaining();
                    buf.extend_from_slice(buffer);
                    buffer.clear();
                    read += to_write;
                    break;
                }
                Self::Error => unreachable!("error state "),
            }
        }
        Ok(read)
    }
}