Skip to main content

capsule_core/crypto/encryption/
stream.rs

1//! Authenticated asset encryption with the AES-256-GCM **STREAM** construction
2//! (Hoang-Reyhanitabar-Rogaway-Vizár 2015), via RustCrypto `aead::stream`.
3//!
4//! Plaintext is split into 65,520-byte chunks, each sealed with AES-256-GCM under a
5//! structured nonce `prefix(7) ‖ counter_be32(4) ‖ last_flag(1)`, producing 64 KiB
6//! ciphertext chunks (16-byte tag each). STREAM detects truncation, reordering, and chunk
7//! deletion. Because each chunk's nonce is derived deterministically from its index, any
8//! chunk decrypts **independently** ([`decrypt_chunk`]) for ranged reads.
9//!
10//! A fresh per-file key (see [`crate::crypto::keys::Amk::derive_file_key`]) lets the
11//! counter safely start at zero. SSoT: [Cryptography — Encryption § STREAM Construction].
12//!
13//! **Bounded memory.** Nothing here needs a whole file in memory. [`encrypt_asset`] and
14//! [`decrypt_asset`] run reader-to-writer one chunk at a time; [`CiphertextReader`] re-derives
15//! any byte range of a ciphertext from its plaintext (a chunk's ciphertext depends only on its
16//! own plaintext, its index and whether it is last), which is what lets an upload resume at any
17//! offset without holding the ciphertext; and [`StreamDecryptor`] opens a ciphertext that
18//! arrives in arbitrary pieces, holding at most two chunks. ADR-0012 records why originals keep
19//! this format rather than a new segmented one.
20//!
21//! [Cryptography — Encryption § STREAM Construction]: https://docs/design/cryptography/encryption/#stream-construction
22
23use std::io::{self, Read, Write};
24
25use aes_gcm::aead::generic_array::GenericArray;
26use aes_gcm::aead::stream::{DecryptorBE32, EncryptorBE32};
27use aes_gcm::aead::{Aead, KeyInit};
28use aes_gcm::{Aes256Gcm, Key, Nonce};
29use thiserror::Error;
30
31use crate::crypto::hash::{Hash32, Sha256Hasher};
32use crate::crypto::rng;
33
34/// Plaintext bytes per STREAM chunk.
35pub const PLAINTEXT_CHUNK: usize = 65_520;
36/// Ciphertext bytes per full STREAM chunk (plaintext chunk + 16-byte GCM tag = 64 KiB).
37pub const CIPHERTEXT_CHUNK: usize = PLAINTEXT_CHUNK + TAG_LEN;
38/// STREAM nonce prefix length (12-byte nonce − 4-byte counter − 1-byte last flag).
39pub const NONCE_PREFIX_LEN: usize = 7;
40/// GCM authentication tag length.
41pub const TAG_LEN: usize = 16;
42
43/// Result of encrypting an asset: everything the [signed manifest] commits to.
44///
45/// [signed manifest]: crate::crypto::provenance
46#[derive(Debug, Clone, PartialEq, Eq)]
47pub struct AssetEncryption {
48    /// SHA-256 over the full produced ciphertext (the content address).
49    pub ciphertext_hash: Hash32,
50    /// Total plaintext byte length.
51    pub plaintext_size: u64,
52    /// Plaintext bytes per chunk (always [`PLAINTEXT_CHUNK`]).
53    pub chunk_size: u32,
54    /// The random STREAM nonce prefix for this file.
55    pub nonce_prefix: [u8; NONCE_PREFIX_LEN],
56}
57
58/// Errors from streaming encrypt/decrypt.
59#[derive(Debug, Error)]
60pub enum StreamError {
61    /// Underlying reader/writer I/O failure.
62    #[error("stream io error: {0}")]
63    Io(#[from] io::Error),
64    /// A chunk failed AEAD authentication (tamper, wrong key, truncation, reorder).
65    #[error("stream authentication failed at chunk {0}")]
66    Auth(u32),
67}
68
69/// The number of STREAM chunks a `plaintext_size`-byte plaintext encrypts to. An empty
70/// plaintext is still one (empty, last) chunk: its ciphertext is a bare tag.
71#[must_use]
72pub const fn chunk_count(plaintext_size: u64) -> u64 {
73    if plaintext_size == 0 {
74        1
75    } else {
76        plaintext_size.div_ceil(PLAINTEXT_CHUNK as u64)
77    }
78}
79
80/// The exact ciphertext length a `plaintext_size`-byte plaintext encrypts to: the plaintext
81/// plus one [`TAG_LEN`] tag per chunk.
82#[must_use]
83pub const fn ciphertext_len(plaintext_size: u64) -> u64 {
84    plaintext_size + chunk_count(plaintext_size) * TAG_LEN as u64
85}
86
87/// The STREAM-BE32 nonce of chunk `index`: `prefix(7) ‖ counter_be32(4) ‖ last_flag(1)`.
88fn chunk_nonce(nonce_prefix: &[u8; NONCE_PREFIX_LEN], index: u32, is_last: bool) -> [u8; 12] {
89    let mut nonce = [0u8; 12];
90    nonce[..NONCE_PREFIX_LEN].copy_from_slice(nonce_prefix);
91    nonce[NONCE_PREFIX_LEN..11].copy_from_slice(&index.to_be_bytes());
92    nonce[11] = u8::from(is_last);
93    nonce
94}
95
96fn read_chunk<R: Read>(reader: &mut R, n: usize) -> io::Result<Vec<u8>> {
97    let mut buf = vec![0u8; n];
98    let mut filled = 0;
99    while filled < n {
100        let k = reader.read(&mut buf[filled..])?;
101        if k == 0 {
102            break;
103        }
104        filled += k;
105    }
106    buf.truncate(filled);
107    Ok(buf)
108}
109
110/// Encrypt `reader` to `writer` under `file_key`, returning the content metadata.
111/// Computes the ciphertext hash incrementally — the whole file is never buffered.
112/// Draws a fresh random nonce prefix.
113pub fn encrypt_asset<R: Read, W: Write>(
114    file_key: &[u8; 32],
115    reader: R,
116    writer: W,
117) -> Result<AssetEncryption, StreamError> {
118    encrypt_asset_with_prefix(
119        file_key,
120        rng::random_array::<NONCE_PREFIX_LEN>(),
121        reader,
122        writer,
123    )
124}
125
126/// As [`encrypt_asset`] but with an explicit nonce prefix, so a client can **regenerate the
127/// exact ciphertext** from the plaintext + file key + the prefix recorded in the manifest
128/// (the client stores plaintext locally; ciphertext is derived for upload/backup).
129pub fn encrypt_asset_with_prefix<R: Read, W: Write>(
130    file_key: &[u8; 32],
131    nonce_prefix: [u8; NONCE_PREFIX_LEN],
132    mut reader: R,
133    mut writer: W,
134) -> Result<AssetEncryption, StreamError> {
135    let cipher = Aes256Gcm::new(Key::<Aes256Gcm>::from_slice(file_key));
136    let mut enc =
137        EncryptorBE32::<Aes256Gcm>::from_aead(cipher, GenericArray::from_slice(&nonce_prefix));
138
139    let mut hasher = Sha256Hasher::new();
140    let mut plaintext_size: u64 = 0;
141    let mut index: u32 = 0;
142
143    // Read one chunk ahead so we know which chunk is the last (it gets the last-block flag).
144    let mut cur = read_chunk(&mut reader, PLAINTEXT_CHUNK)?;
145    loop {
146        let next = read_chunk(&mut reader, PLAINTEXT_CHUNK)?;
147        plaintext_size += cur.len() as u64;
148        if next.is_empty() {
149            let ct = enc
150                .encrypt_last(cur.as_slice())
151                .map_err(|_| StreamError::Auth(index))?;
152            hasher.update(&ct);
153            writer.write_all(&ct)?;
154            break;
155        }
156        let ct = enc
157            .encrypt_next(cur.as_slice())
158            .map_err(|_| StreamError::Auth(index))?;
159        hasher.update(&ct);
160        writer.write_all(&ct)?;
161        cur = next;
162        index += 1;
163    }
164
165    Ok(AssetEncryption {
166        ciphertext_hash: hasher.finalize(),
167        plaintext_size,
168        chunk_size: PLAINTEXT_CHUNK as u32,
169        nonce_prefix,
170    })
171}
172
173/// Decrypt a STREAM ciphertext from `reader` to `writer`. Every chunk's tag is verified;
174/// any tamper/truncation/reorder yields [`StreamError::Auth`].
175pub fn decrypt_asset<R: Read, W: Write>(
176    file_key: &[u8; 32],
177    nonce_prefix: &[u8; NONCE_PREFIX_LEN],
178    mut reader: R,
179    mut writer: W,
180) -> Result<(), StreamError> {
181    let cipher = Aes256Gcm::new(Key::<Aes256Gcm>::from_slice(file_key));
182    let mut dec =
183        DecryptorBE32::<Aes256Gcm>::from_aead(cipher, GenericArray::from_slice(nonce_prefix));
184
185    let mut index: u32 = 0;
186    let mut cur = read_chunk(&mut reader, CIPHERTEXT_CHUNK)?;
187    loop {
188        let next = read_chunk(&mut reader, CIPHERTEXT_CHUNK)?;
189        if next.is_empty() {
190            let pt = dec
191                .decrypt_last(cur.as_slice())
192                .map_err(|_| StreamError::Auth(index))?;
193            writer.write_all(&pt)?;
194            break;
195        }
196        let pt = dec
197            .decrypt_next(cur.as_slice())
198            .map_err(|_| StreamError::Auth(index))?;
199        writer.write_all(&pt)?;
200        cur = next;
201        index += 1;
202    }
203    Ok(())
204}
205
206/// Decrypt a single ciphertext chunk in isolation (ranged read). `index` is the 0-based
207/// chunk number; `is_last` must be true only for the final chunk of the file (it carries
208/// the STREAM last-block flag). Returns [`crate::crypto::CryptoError::Auth`] on tamper.
209pub fn decrypt_chunk(
210    file_key: &[u8; 32],
211    nonce_prefix: &[u8; NONCE_PREFIX_LEN],
212    index: u32,
213    is_last: bool,
214    ct_chunk: &[u8],
215) -> Result<Vec<u8>, crate::crypto::CryptoError> {
216    let nonce = chunk_nonce(nonce_prefix, index, is_last);
217    let cipher = Aes256Gcm::new(Key::<Aes256Gcm>::from_slice(file_key));
218    cipher
219        .decrypt(Nonce::from_slice(&nonce), ct_chunk)
220        .map_err(|_| crate::crypto::CryptoError::Auth("STREAM chunk authentication failed"))
221}
222
223/// Encrypt a single plaintext chunk in isolation: the inverse of [`decrypt_chunk`], and
224/// byte-identical to chunk `index` of [`encrypt_asset_with_prefix`]'s output for the same key
225/// and prefix. `pt_chunk` must be [`PLAINTEXT_CHUNK`] bytes unless `is_last`.
226#[must_use]
227pub fn encrypt_chunk(
228    file_key: &[u8; 32],
229    nonce_prefix: &[u8; NONCE_PREFIX_LEN],
230    index: u32,
231    is_last: bool,
232    pt_chunk: &[u8],
233) -> Vec<u8> {
234    let nonce = chunk_nonce(nonce_prefix, index, is_last);
235    let cipher = Aes256Gcm::new(Key::<Aes256Gcm>::from_slice(file_key));
236    cipher
237        .encrypt(Nonce::from_slice(&nonce), pt_chunk)
238        .expect("AES-GCM encryption of a chunk under 64 KiB cannot fail")
239}
240
241/// Random-access re-derivation of a STREAM ciphertext from its plaintext.
242///
243/// A chunk's ciphertext is a function of the key, the nonce prefix, the chunk's plaintext, its
244/// index and whether it is the last chunk, so any byte range of the ciphertext can be produced
245/// by reading and encrypting only the plaintext chunks that range covers. That is what lets an
246/// upload send — and re-send, on a resume or a realign — any window of an original without the
247/// ciphertext ever existing in memory or on disk.
248///
249/// `plaintext_size` is the size the signed manifest committed to. The reader never reads past
250/// it, and a source shorter than it is an [`io::ErrorKind::UnexpectedEof`] rather than a short
251/// ciphertext.
252pub struct CiphertextReader<R> {
253    file_key: [u8; 32],
254    nonce_prefix: [u8; NONCE_PREFIX_LEN],
255    plaintext: R,
256    plaintext_size: u64,
257}
258
259impl<R> std::fmt::Debug for CiphertextReader<R> {
260    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
261        f.debug_struct("CiphertextReader")
262            .field("file_key", &"<redacted>")
263            .field("plaintext_size", &self.plaintext_size)
264            .finish_non_exhaustive()
265    }
266}
267
268impl<R: Read + io::Seek> CiphertextReader<R> {
269    /// A reader over `plaintext`, which holds `plaintext_size` bytes.
270    pub fn new(
271        file_key: [u8; 32],
272        nonce_prefix: [u8; NONCE_PREFIX_LEN],
273        plaintext: R,
274        plaintext_size: u64,
275    ) -> Self {
276        Self {
277            file_key,
278            nonce_prefix,
279            plaintext,
280            plaintext_size,
281        }
282    }
283
284    /// The ciphertext's total length ([`ciphertext_len`] of the plaintext size).
285    #[must_use]
286    pub fn ciphertext_size(&self) -> u64 {
287        ciphertext_len(self.plaintext_size)
288    }
289
290    /// The ciphertext bytes `[offset, offset + len)`, clamped to the ciphertext's end. Memory is
291    /// the returned window plus one chunk.
292    pub fn read_at(&mut self, offset: u64, len: usize) -> io::Result<Vec<u8>> {
293        let total = self.ciphertext_size();
294        let end = offset.saturating_add(len as u64).min(total);
295        if offset >= end {
296            return Ok(Vec::new());
297        }
298        let mut out = Vec::with_capacity((end - offset) as usize);
299        let last_index = chunk_count(self.plaintext_size) - 1;
300        let first = offset / CIPHERTEXT_CHUNK as u64;
301        let last = (end - 1) / CIPHERTEXT_CHUNK as u64;
302        let mut pt = vec![0u8; PLAINTEXT_CHUNK];
303        for index in first..=last {
304            let pt_start = index * PLAINTEXT_CHUNK as u64;
305            let pt_len = (self.plaintext_size - pt_start).min(PLAINTEXT_CHUNK as u64) as usize;
306            self.plaintext.seek(io::SeekFrom::Start(pt_start))?;
307            self.plaintext.read_exact(&mut pt[..pt_len])?;
308            let counter = u32::try_from(index).map_err(|_| {
309                io::Error::new(io::ErrorKind::InvalidInput, "STREAM chunk counter overflow")
310            })?;
311            let ct = encrypt_chunk(
312                &self.file_key,
313                &self.nonce_prefix,
314                counter,
315                index == last_index,
316                &pt[..pt_len],
317            );
318            let ct_start = index * CIPHERTEXT_CHUNK as u64;
319            let from = offset.saturating_sub(ct_start) as usize;
320            let to = ((end - ct_start) as usize).min(ct.len());
321            out.extend_from_slice(&ct[from..to]);
322        }
323        Ok(out)
324    }
325}
326
327/// Incremental STREAM decryption of a ciphertext that arrives in pieces of any size.
328///
329/// [`update`](Self::update) buffers at most two ciphertext chunks: a chunk is opened as soon as
330/// a byte past it has arrived (proving it is not the last), and [`finish`](Self::finish) opens
331/// the final chunk under the last-block flag. Truncation, reordering, a chunk swapped in from
332/// another file and a toggled last flag all fail authentication, and an empty ciphertext fails
333/// at `finish`. After the first failure every later call fails too.
334///
335/// Plaintext reaches the inner writer chunk by chunk, each chunk authenticated before it is
336/// written; the whole file is authentic only once `finish` returns `Ok`. A caller that writes
337/// to a file must treat it as unverified, and discard it, until then.
338pub struct StreamDecryptor<W> {
339    decryptor: Option<DecryptorBE32<Aes256Gcm>>,
340    pending: Vec<u8>,
341    index: u32,
342    inner: W,
343}
344
345impl<W> std::fmt::Debug for StreamDecryptor<W> {
346    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
347        f.debug_struct("StreamDecryptor")
348            .field("index", &self.index)
349            .field("pending", &self.pending.len())
350            .finish_non_exhaustive()
351    }
352}
353
354impl<W: Write> StreamDecryptor<W> {
355    /// A decryptor writing plaintext to `inner`.
356    pub fn new(file_key: &[u8; 32], nonce_prefix: &[u8; NONCE_PREFIX_LEN], inner: W) -> Self {
357        let cipher = Aes256Gcm::new(Key::<Aes256Gcm>::from_slice(file_key));
358        Self {
359            decryptor: Some(DecryptorBE32::from_aead(
360                cipher,
361                GenericArray::from_slice(nonce_prefix),
362            )),
363            pending: Vec::with_capacity(2 * CIPHERTEXT_CHUNK),
364            index: 0,
365            inner,
366        }
367    }
368
369    /// Feed the next ciphertext bytes.
370    pub fn update(&mut self, mut data: &[u8]) -> Result<(), StreamError> {
371        if self.decryptor.is_none() {
372            return Err(StreamError::Auth(self.index));
373        }
374        while !data.is_empty() {
375            let take = data.len().min(2 * CIPHERTEXT_CHUNK - self.pending.len());
376            self.pending.extend_from_slice(&data[..take]);
377            data = &data[take..];
378            while self.pending.len() > CIPHERTEXT_CHUNK {
379                let decryptor = self
380                    .decryptor
381                    .as_mut()
382                    .ok_or(StreamError::Auth(self.index))?;
383                let opened = decryptor.decrypt_next(&self.pending[..CIPHERTEXT_CHUNK]);
384                let Ok(pt) = opened else {
385                    self.decryptor = None;
386                    return Err(StreamError::Auth(self.index));
387                };
388                self.inner.write_all(&pt)?;
389                self.pending.drain(..CIPHERTEXT_CHUNK);
390                self.index += 1;
391            }
392        }
393        Ok(())
394    }
395
396    /// Open the final chunk and return the inner writer.
397    pub fn finish(mut self) -> Result<W, StreamError> {
398        let decryptor = self.decryptor.take().ok_or(StreamError::Auth(self.index))?;
399        let pt = decryptor
400            .decrypt_last(self.pending.as_slice())
401            .map_err(|_| StreamError::Auth(self.index))?;
402        self.inner.write_all(&pt)?;
403        self.inner.flush()?;
404        Ok(self.inner)
405    }
406}
407
408/// `io::Write` over [`StreamDecryptor::update`], so the decryptor can be the sink of anything
409/// that writes bytes. An authentication failure surfaces as [`io::ErrorKind::InvalidData`].
410impl<W: Write> Write for StreamDecryptor<W> {
411    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
412        self.update(buf).map_err(|error| match error {
413            StreamError::Io(io) => io,
414            auth @ StreamError::Auth(_) => io::Error::new(io::ErrorKind::InvalidData, auth),
415        })?;
416        Ok(buf.len())
417    }
418
419    fn flush(&mut self) -> io::Result<()> {
420        self.inner.flush()
421    }
422}
423
424/// Convenience: encrypt a whole slice in memory, returning (metadata, ciphertext).
425pub fn encrypt_asset_vec(file_key: &[u8; 32], plaintext: &[u8]) -> AssetEncryption {
426    let mut out = Vec::new();
427    // Slice reader + Vec writer are infallible, so the only error path is unreachable.
428    encrypt_asset(file_key, plaintext, &mut out).expect("in-memory encryption is infallible")
429}
430
431/// Convenience: encrypt a whole slice in memory and also return the ciphertext bytes.
432pub fn encrypt_asset_vec_full(file_key: &[u8; 32], plaintext: &[u8]) -> (AssetEncryption, Vec<u8>) {
433    let mut out = Vec::new();
434    let meta = encrypt_asset(file_key, plaintext, &mut out).expect("in-memory encryption");
435    (meta, out)
436}
437
438/// Convenience: encrypt a whole slice in memory with an explicit prefix (deterministic).
439pub fn encrypt_asset_vec_with_prefix(
440    file_key: &[u8; 32],
441    nonce_prefix: [u8; NONCE_PREFIX_LEN],
442    plaintext: &[u8],
443) -> (AssetEncryption, Vec<u8>) {
444    let mut out = Vec::new();
445    let meta = encrypt_asset_with_prefix(file_key, nonce_prefix, plaintext, &mut out)
446        .expect("in-memory encryption");
447    (meta, out)
448}
449
450/// Convenience: decrypt a whole ciphertext slice in memory.
451pub fn decrypt_asset_vec(
452    file_key: &[u8; 32],
453    nonce_prefix: &[u8; NONCE_PREFIX_LEN],
454    ciphertext: &[u8],
455) -> Result<Vec<u8>, StreamError> {
456    let mut out = Vec::new();
457    decrypt_asset(file_key, nonce_prefix, ciphertext, &mut out)?;
458    Ok(out)
459}
460
461#[cfg(test)]
462mod tests;