capsule_core/crypto/encryption/
stream.rs1use 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
34pub const PLAINTEXT_CHUNK: usize = 65_520;
36pub const CIPHERTEXT_CHUNK: usize = PLAINTEXT_CHUNK + TAG_LEN;
38pub const NONCE_PREFIX_LEN: usize = 7;
40pub const TAG_LEN: usize = 16;
42
43#[derive(Debug, Clone, PartialEq, Eq)]
47pub struct AssetEncryption {
48 pub ciphertext_hash: Hash32,
50 pub plaintext_size: u64,
52 pub chunk_size: u32,
54 pub nonce_prefix: [u8; NONCE_PREFIX_LEN],
56}
57
58#[derive(Debug, Error)]
60pub enum StreamError {
61 #[error("stream io error: {0}")]
63 Io(#[from] io::Error),
64 #[error("stream authentication failed at chunk {0}")]
66 Auth(u32),
67}
68
69#[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#[must_use]
83pub const fn ciphertext_len(plaintext_size: u64) -> u64 {
84 plaintext_size + chunk_count(plaintext_size) * TAG_LEN as u64
85}
86
87fn 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
110pub 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
126pub 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 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
173pub 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
206pub 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#[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
241pub 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 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 #[must_use]
286 pub fn ciphertext_size(&self) -> u64 {
287 ciphertext_len(self.plaintext_size)
288 }
289
290 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
327pub 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 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 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 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
408impl<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
424pub fn encrypt_asset_vec(file_key: &[u8; 32], plaintext: &[u8]) -> AssetEncryption {
426 let mut out = Vec::new();
427 encrypt_asset(file_key, plaintext, &mut out).expect("in-memory encryption is infallible")
429}
430
431pub 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
438pub 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
450pub 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;