Skip to main content

crab_cryptor/
decrypt_reader.rs

1use aead_stream::DecryptorBE32;
2use chacha20poly1305::XChaCha20Poly1305;
3use std::io::{self, Cursor, Read};
4
5const CHUNK_SIZE: usize = 64 * 1024 + 16; // 64KB Data + 16B Tag
6
7pub struct DecryptReader<R: Read> {
8    inner_reader: R,
9
10    decryptor: Option<DecryptorBE32<XChaCha20Poly1305>>,
11
12    plaintext_buffer: Cursor<Vec<u8>>,
13    current_ciphertext: Vec<u8>,
14    finished: bool,
15}
16
17fn read_ciphertext_chunk<R: Read>(reader: &mut R) -> io::Result<Vec<u8>> {
18    let mut chunk = Vec::with_capacity(CHUNK_SIZE);
19    reader.take(CHUNK_SIZE as u64).read_to_end(&mut chunk)?;
20    Ok(chunk)
21}
22
23impl<R: Read> DecryptReader<R> {
24    /// Creates a streaming decrypt reader and preloads the first ciphertext chunk.
25    ///
26    /// # Errors
27    /// Returns the underlying reader error if the initial ciphertext prefetch fails.
28    pub fn new(mut reader: R, decryptor: DecryptorBE32<XChaCha20Poly1305>) -> io::Result<Self> {
29        let first_chunk = read_ciphertext_chunk(&mut reader)?;
30
31        Ok(Self {
32            inner_reader: reader,
33            decryptor: Some(decryptor),
34            plaintext_buffer: Cursor::default(),
35            current_ciphertext: first_chunk,
36            finished: false,
37        })
38    }
39}
40
41impl<R: Read> Read for DecryptReader<R> {
42    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
43        if buf.is_empty() {
44            return Ok(0);
45        }
46
47        loop {
48            let copied = self.plaintext_buffer.read(buf)?;
49            if copied != 0 || self.finished {
50                return Ok(copied);
51            }
52
53            let next_chunk = read_ciphertext_chunk(&mut self.inner_reader)?;
54            let mut decrypted_chunk = std::mem::take(&mut self.current_ciphertext);
55
56            if next_chunk.is_empty() {
57                let decryptor = self
58                    .decryptor
59                    .take()
60                    .ok_or_else(|| io::Error::other("Decryptor logic error: already consumed"))?;
61
62                decryptor
63                    .decrypt_last_in_place(b"", &mut decrypted_chunk)
64                    .map_err(|e| {
65                        io::Error::new(
66                            io::ErrorKind::InvalidData,
67                            format!("Decrypt last failed: {e}"),
68                        )
69                    })?;
70
71                self.finished = true;
72            } else {
73                let decryptor = self
74                    .decryptor
75                    .as_mut()
76                    .ok_or_else(|| io::Error::other("Decryptor missing unexpectedly"))?;
77
78                decryptor
79                    .decrypt_next_in_place(b"", &mut decrypted_chunk)
80                    .map_err(|e| {
81                        io::Error::new(
82                            io::ErrorKind::InvalidData,
83                            format!("Decrypt next failed: {e}"),
84                        )
85                    })?;
86
87                self.current_ciphertext = next_chunk;
88            }
89
90            self.plaintext_buffer = Cursor::new(decrypted_chunk);
91        }
92    }
93}