Skip to content

armgit / ente

Public Imported from GitHub
0

πŸ’š End-to-end encrypted cloud for everything.

Reshape stream: Encryptor/Decryptor with finish(), Md5Writer in core io

Manav Rathiaf080786a693
diff --git a/rust/apps/cli/src/commands/export.rs b/rust/apps/cli/src/commands/export.rs
index 9425689212..787734d7de 100644
--- a/rust/apps/cli/src/commands/export.rs
+++ b/rust/apps/cli/src/commands/export.rs
@@ -712,19 +712,25 @@ async fn export_account(storage: &Storage, account: &Account, filter: &ExportFil
// Decrypt the file data using streaming XChaCha20-Poly1305
// Use chunked decryption for large files
- let decrypted =
- match crypto::stream::decrypt_file_data(&encrypted_data, &file_nonce, &file_key) {
- Ok(data) => data,
- Err(e) => {
- log::error!("Failed to decrypt file {}: {}", file.id, e);
- log::debug!(
- "File size: {}, header length: {}",
- encrypted_data.len(),
- file_nonce.len()
- );
- continue;
- }
- };
+ let decrypt_result = crypto::Header::try_from_slice(&file_nonce).and_then(|header| {
+ crypto::stream::decrypt_file_data(
+ &encrypted_data,
+ &header,
+ &crypto::Key::try_from_slice(&file_key)?,
+ )
+ });
+ let decrypted = match decrypt_result {
+ Ok(data) => data,
+ Err(e) => {
+ log::error!("Failed to decrypt file {}: {}", file.id, e);
+ log::debug!(
+ "File size: {}, header length: {}",
+ encrypted_data.len(),
+ file_nonce.len()
+ );
+ continue;
+ }
+ };
// Check if this is a live photo that needs extraction
let is_live_photo = metadata
@@ -1067,7 +1073,11 @@ fn decrypt_file_metadata(
let header_bytes = BASE64.decode(&file.metadata.decryption_header)?;
// Decrypt the metadata using streaming XChaCha20-Poly1305
- let decrypted = crypto::stream::decrypt(&encrypted_bytes, &header_bytes, file_key)?;
+ let decrypted = crypto::blob::decrypt(
+ &encrypted_bytes,
+ &crypto::Header::try_from_slice(&header_bytes)?,
+ &crypto::Key::try_from_slice(file_key)?,
+ )?;
// Parse JSON metadata
let metadata: FileMetadata = serde_json::from_slice(&decrypted)?;
@@ -1090,7 +1100,11 @@ fn decrypt_magic_metadata(
let header_bytes = BASE64.decode(&magic_metadata.header)?;
// Decrypt the metadata using streaming XChaCha20-Poly1305
- let decrypted = crypto::stream::decrypt(&encrypted_bytes, &header_bytes, file_key)?;
+ let decrypted = crypto::blob::decrypt(
+ &encrypted_bytes,
+ &crypto::Header::try_from_slice(&header_bytes)?,
+ &crypto::Key::try_from_slice(file_key)?,
+ )?;
// Parse as generic JSON since magic metadata structure can vary
let metadata: serde_json::Value = serde_json::from_slice(&decrypted)?;
diff --git a/rust/apps/cli/src/commands/paste.rs b/rust/apps/cli/src/commands/paste.rs
index cbe52e0ebd..661f8a3ed5 100644
--- a/rust/apps/cli/src/commands/paste.rs
+++ b/rust/apps/cli/src/commands/paste.rs
@@ -988,8 +988,7 @@ mod tests {
let kdf_secret = key_reference.kdf_secret(password).unwrap();
// Minimal-cost KDF params: the kdf secret is already high-entropy (it
// is not a human-chosen password), and tests need to be fast.
- let key_encryption_key =
- argon::derive_key(&kdf_secret, &salt, argon::Params::MIN).unwrap();
+ let key_encryption_key = argon::derive_key(&kdf_secret, &salt, argon::Params::MIN).unwrap();
let encrypted_paste_key = secretbox::encrypt(paste_key.as_bytes(), &key_encryption_key);
PastePayload {
diff --git a/rust/apps/cli/src/commands/sync.rs b/rust/apps/cli/src/commands/sync.rs
index c93f45ab51..99daaa7eaf 100644
--- a/rust/apps/cli/src/commands/sync.rs
+++ b/rust/apps/cli/src/commands/sync.rs
@@ -336,7 +336,15 @@ async fn prepare_download_tasks(
let encrypted_bytes = BASE64.decode(&file.metadata.encrypted_data)?;
let header_bytes = BASE64.decode(&file.metadata.decryption_header)?;
- match crypto::stream::decrypt(&encrypted_bytes, &header_bytes, &file_key) {
+ let decrypted =
+ crypto::Header::try_from_slice(&header_bytes).and_then(|header| {
+ crypto::blob::decrypt(
+ &encrypted_bytes,
+ &header,
+ &crypto::Key::try_from_slice(&file_key)?,
+ )
+ });
+ match decrypted {
Ok(decrypted) => serde_json::from_slice::<FileMetadata>(&decrypted).ok(),
Err(e) => {
log::warn!("Failed to decrypt metadata for file {}: {}", file.id, e);
@@ -356,7 +364,15 @@ async fn prepare_download_tasks(
let encrypted_bytes = BASE64.decode(&magic.data)?;
let header_bytes = BASE64.decode(&magic.header)?;
- match crypto::stream::decrypt(&encrypted_bytes, &header_bytes, &file_key) {
+ let decrypted =
+ crypto::Header::try_from_slice(&header_bytes).and_then(|header| {
+ crypto::blob::decrypt(
+ &encrypted_bytes,
+ &header,
+ &crypto::Key::try_from_slice(&file_key)?,
+ )
+ });
+ match decrypted {
Ok(decrypted) => {
serde_json::from_slice::<serde_json::Value>(&decrypted).ok()
}
diff --git a/rust/apps/cli/src/sync/download.rs b/rust/apps/cli/src/sync/download.rs
index d5e737b0ea..e44cb5e6c4 100644
--- a/rust/apps/cli/src/sync/download.rs
+++ b/rust/apps/cli/src/sync/download.rs
@@ -279,7 +279,11 @@ impl DownloadManager {
// Decrypt file data using file key (Streaming XChaCha20-Poly1305)
let file_nonce = BASE64.decode(&file.file.decryption_header)?;
- let decrypted = crypto::stream::decrypt_file_data(encrypted_data, &file_nonce, &file_key)?;
+ let decrypted = crypto::stream::decrypt_file_data(
+ encrypted_data,
+ &crypto::Header::try_from_slice(&file_nonce)?,
+ &crypto::Key::try_from_slice(&file_key)?,
+ )?;
Ok(decrypted)
}
diff --git a/rust/bindings/ffi/crypto/src/lib.rs b/rust/bindings/ffi/crypto/src/lib.rs
index 6492e921e6..1312b436f0 100644
--- a/rust/bindings/ffi/crypto/src/lib.rs
+++ b/rust/bindings/ffi/crypto/src/lib.rs
@@ -228,9 +228,12 @@ pub unsafe extern "C" fn ente_crypto_secretstream_decrypt_b64(
let encrypted_data = decode_b64(&encrypted_data_b64, "encrypted_data_b64")?;
let decryption_header = decode_b64(&decryption_header_b64, "decryption_header_b64")?;
let key = decode_b64(&key_b64, "key_b64")?;
- let plaintext =
- crypto::stream::decrypt_file_data(&encrypted_data, &decryption_header, &key)
- .map_err(|e| e.to_string())?;
+ let plaintext = crypto::stream::decrypt_file_data(
+ &encrypted_data,
+ &crypto::Header::try_from_slice(&decryption_header).map_err(|e| e.to_string())?,
+ &crypto::Key::try_from_slice(&key).map_err(|e| e.to_string())?,
+ )
+ .map_err(|e| e.to_string())?;
unsafe {
c_output(
diff --git a/rust/bindings/wasm/ente-wasm/src/crypto.rs b/rust/bindings/wasm/ente-wasm/src/crypto.rs
index 1f32fdea81..d505c2b0c2 100644
--- a/rust/bindings/wasm/ente-wasm/src/crypto.rs
+++ b/rust/bindings/wasm/ente-wasm/src/crypto.rs
@@ -93,7 +93,7 @@ pub fn crypto_generate_stream_key() -> String {
/// the caller to upload.
#[wasm_bindgen]
pub struct CryptoStreamEncryptor {
- encryptor: core_crypto::stream::StreamEncryptor,
+ encryptor: core_crypto::stream::Encryptor,
key: String,
decryption_header: String,
}
@@ -102,13 +102,13 @@ pub struct CryptoStreamEncryptor {
impl CryptoStreamEncryptor {
#[wasm_bindgen(constructor)]
pub fn new() -> Result<CryptoStreamEncryptor, CryptoError> {
- let key = core_crypto::Key::generate().as_bytes().to_vec();
- let encryptor = core_crypto::stream::StreamEncryptor::new(&key)?;
- let decryption_header = core_crypto::encode_b64(&encryptor.header);
+ let key = core_crypto::Key::generate();
+ let encryptor = core_crypto::stream::Encryptor::new(&key);
+ let decryption_header = core_crypto::encode_b64(encryptor.header().as_bytes());
Ok(Self {
encryptor,
- key: core_crypto::encode_b64(&key),
+ key: core_crypto::encode_b64(key.as_bytes()),
decryption_header,
})
}
@@ -137,7 +137,7 @@ impl CryptoStreamEncryptor {
/// Incremental chunk decryptor for large file downloads.
#[wasm_bindgen]
pub struct CryptoStreamDecryptor {
- decryptor: core_crypto::stream::StreamDecryptor,
+ decryptor: core_crypto::stream::Decryptor,
finalized: bool,
}
@@ -150,7 +150,10 @@ impl CryptoStreamDecryptor {
) -> Result<CryptoStreamDecryptor, CryptoError> {
let header = core_crypto::decode_b64(decryption_header_b64)?;
let key = core_crypto::decode_b64(key_b64)?;
- let decryptor = core_crypto::stream::StreamDecryptor::new(&header, &key)?;
+ let decryptor = core_crypto::stream::Decryptor::new(
+ &core_crypto::Header::try_from_slice(&header)?,
+ &core_crypto::Key::try_from_slice(&key)?,
+ );
Ok(Self {
decryptor,
@@ -169,8 +172,8 @@ impl CryptoStreamDecryptor {
}
pub fn decrypt_chunk(&mut self, ciphertext: Vec<u8>) -> Result<Vec<u8>, CryptoError> {
- let (plaintext, tag) = self.decryptor.pull(&ciphertext)?;
- self.finalized = tag == core_crypto::stream::TAG_FINAL;
+ let (plaintext, is_final) = self.decryptor.pull(&ciphertext)?;
+ self.finalized = is_final;
Ok(plaintext)
}
}
@@ -371,7 +374,11 @@ pub fn crypto_decrypt_stream(
let header = core_crypto::decode_b64(decryption_header_b64)?;
let key = core_crypto::decode_b64(key_b64)?;
- let plaintext = core_crypto::stream::decrypt_file_data(&ciphertext, &header, &key)?;
+ let plaintext = core_crypto::stream::decrypt_file_data(
+ &ciphertext,
+ &core_crypto::Header::try_from_slice(&header)?,
+ &core_crypto::Key::try_from_slice(&key)?,
+ )?;
Ok(core_crypto::encode_b64(&plaintext))
}
@@ -497,17 +504,18 @@ impl EncryptedStreamResult {
pub fn crypto_encrypt_stream(data_b64: &str) -> Result<EncryptedStreamResult, CryptoError> {
let plaintext = core_crypto::decode_b64(data_b64)?;
+ let key = core_crypto::Key::generate();
let mut reader = std::io::Cursor::new(&plaintext);
- let mut writer = Vec::new();
+ let mut writer = ente_core::io::Md5Writer::new(Vec::new());
- let (key, header, md5) =
- core_crypto::stream::encrypt_file_with_md5(&mut reader, &mut writer, None)?;
+ let header = core_crypto::stream::encrypt_file(&mut reader, &mut writer, &key)?;
+ let (encrypted, md5) = writer.finalize();
Ok(EncryptedStreamResult {
- encrypted_data: core_crypto::encode_b64(&writer),
- decryption_header: core_crypto::encode_b64(&header),
+ encrypted_data: core_crypto::encode_b64(&encrypted),
+ decryption_header: core_crypto::encode_b64(header.as_bytes()),
md5_hash: core_crypto::encode_b64(&md5),
- key: core_crypto::encode_b64(&key),
+ key: core_crypto::encode_b64(key.as_bytes()),
})
}
@@ -521,19 +529,19 @@ pub fn crypto_encrypt_stream_with_key(
key_b64: &str,
) -> Result<EncryptedStreamResult, CryptoError> {
let plaintext = core_crypto::decode_b64(data_b64)?;
- let key = core_crypto::decode_b64(key_b64)?;
+ let key = core_crypto::Key::try_from_slice(&core_crypto::decode_b64(key_b64)?)?;
let mut reader = std::io::Cursor::new(&plaintext);
- let mut writer = Vec::new();
+ let mut writer = ente_core::io::Md5Writer::new(Vec::new());
- let (out_key, header, md5) =
- core_crypto::stream::encrypt_file_with_md5(&mut reader, &mut writer, Some(&key))?;
+ let header = core_crypto::stream::encrypt_file(&mut reader, &mut writer, &key)?;
+ let (encrypted, md5) = writer.finalize();
Ok(EncryptedStreamResult {
- encrypted_data: core_crypto::encode_b64(&writer),
- decryption_header: core_crypto::encode_b64(&header),
+ encrypted_data: core_crypto::encode_b64(&encrypted),
+ decryption_header: core_crypto::encode_b64(header.as_bytes()),
md5_hash: core_crypto::encode_b64(&md5),
- key: core_crypto::encode_b64(&out_key),
+ key: core_crypto::encode_b64(key.as_bytes()),
})
}
diff --git a/rust/crates/core/src/crypto/blob.rs b/rust/crates/core/src/crypto/blob.rs
index d7ccc6e6f7..8410229265 100644
--- a/rust/crates/core/src/crypto/blob.rs
+++ b/rust/crates/core/src/crypto/blob.rs
@@ -12,7 +12,7 @@
//! - Combined ([`encrypt_combined`] / [`decrypt_combined`]): a single
//! self-contained `header β€– ciphertext` buffer.
-use super::stream::{StreamDecryptor, StreamEncryptor, TAG_FINAL};
+use super::stream::{Decryptor, Encryptor};
use crate::crypto::{CryptoError, Header, Key, Result};
/// Size of the encryption key in bytes.
@@ -45,8 +45,8 @@ impl EncryptedBlob {
/// This is suitable for encrypting metadata and small files. Use [`decrypt`]
/// or [`EncryptedBlob::decrypt`] to decrypt the result.
pub fn encrypt(data: &[u8], key: &Key) -> Result<EncryptedBlob> {
- let mut encryptor = StreamEncryptor::new(key.as_bytes())?;
- let decryption_header = Header::try_from_slice(&encryptor.header)?;
+ let mut encryptor = Encryptor::new(key);
+ let decryption_header = *encryptor.header();
let encrypted_data = encryptor.push(data, true)?;
Ok(EncryptedBlob {
@@ -61,8 +61,8 @@ pub fn encrypt(data: &[u8], key: &Key) -> Result<EncryptedBlob> {
/// payloads are rejected with `CryptoError::StreamTruncated`. For older data
/// written without the final tag, use [`decrypt_legacy`].
pub fn decrypt(data: &[u8], header: &Header, key: &Key) -> Result<Vec<u8>> {
- let (plaintext, tag) = decrypt_impl(data, header, key)?;
- if tag != TAG_FINAL {
+ let (plaintext, is_final) = decrypt_impl(data, header, key)?;
+ if !is_final {
return Err(CryptoError::StreamTruncated);
}
Ok(plaintext)
@@ -76,7 +76,7 @@ pub fn decrypt_legacy(data: &[u8], header: &Header, key: &Key) -> Result<Vec<u8>
Ok(decrypt_impl(data, header, key)?.0)
}
-fn decrypt_impl(data: &[u8], header: &Header, key: &Key) -> Result<(Vec<u8>, u8)> {
+fn decrypt_impl(data: &[u8], header: &Header, key: &Key) -> Result<(Vec<u8>, bool)> {
if data.len() < ABYTES {
return Err(CryptoError::CiphertextTooShort {
minimum: ABYTES,
@@ -84,7 +84,7 @@ fn decrypt_impl(data: &[u8], header: &Header, key: &Key) -> Result<(Vec<u8>, u8)
});
}
- let mut decryptor = StreamDecryptor::new(header.as_bytes(), key.as_bytes())?;
+ let mut decryptor = Decryptor::new(header, key);
decryptor.pull(data)
}
@@ -160,8 +160,8 @@ mod tests {
#[test]
fn test_decrypt_requires_final_tag() {
let key = Key::generate();
- let mut encryptor = StreamEncryptor::new(key.as_bytes()).unwrap();
- let header = Header::try_from_slice(&encryptor.header).unwrap();
+ let mut encryptor = Encryptor::new(&key);
+ let header = *encryptor.header();
let ciphertext = encryptor.push(b"partial", false).unwrap();
assert!(matches!(
@@ -173,8 +173,8 @@ mod tests {
#[test]
fn test_decrypt_legacy_tolerates_missing_final_tag() {
let key = Key::generate();
- let mut encryptor = StreamEncryptor::new(key.as_bytes()).unwrap();
- let header = Header::try_from_slice(&encryptor.header).unwrap();
+ let mut encryptor = Encryptor::new(&key);
+ let header = *encryptor.header();
let ciphertext = encryptor.push(b"partial", false).unwrap();
let decrypted = decrypt_legacy(&ciphertext, &header, &key).unwrap();
diff --git a/rust/crates/core/src/crypto/stream.rs b/rust/crates/core/src/crypto/stream.rs
index 2288439834..f27318d8c4 100644
--- a/rust/crates/core/src/crypto/stream.rs
+++ b/rust/crates/core/src/crypto/stream.rs
@@ -1,27 +1,35 @@
//! XChaCha20-Poly1305 secretstream implementation.
//!
-//! Uses the `crypto_secretstream` crate which provides a pure Rust implementation
-//! of libsodium's crypto_secretstream_xchacha20poly1305 API.
+//! Uses the `crypto_secretstream` crate which provides a pure Rust
+//! implementation of libsodium's crypto_secretstream_xchacha20poly1305 API.
+//! This is the chunked encryption used for file contents; for single-message
+//! payloads see [`super::blob`].
//!
//! # Wire Format
//! - Header: 24 bytes
-//! - Each message: ciphertext (len + 17 bytes with tag embedded)
+//! - Each message: `ciphertext β€– MAC β€– tag` (plaintext length + [`ABYTES`])
-use crypto_secretstream::{Header, Key, PullStream, PushStream, Stream, Tag};
-use md5::{Digest, Md5};
+use crypto_secretstream::{
+ Header as UpstreamHeader, Key as UpstreamKey, PullStream, PushStream, Stream, Tag,
+};
use rand_core::OsRng;
-use std::convert::TryFrom;
use std::io::{Read, Write};
-use crate::crypto::{CryptoError, Result};
+use crate::crypto::{CryptoError, Header, Key, Result};
-/// Size of the stream header in bytes (from upstream crypto_secretstream).
+// The typed Key/Header sizes must match the upstream secretstream sizes; the
+// conversions below rely on it.
+const _: () = assert!(Key::BYTES == UpstreamKey::BYTES);
+const _: () = assert!(Header::BYTES == UpstreamHeader::BYTES);
+
+/// Size of the stream header in bytes.
pub const HEADER_BYTES: usize = Header::BYTES;
-/// Size of the encryption key in bytes (from upstream crypto_secretstream).
+/// Size of the encryption key in bytes.
pub const KEY_BYTES: usize = Key::BYTES;
-/// Size of additional authenticated data bytes (tag + MAC, from upstream crypto_secretstream).
+/// Overhead (MAC + tag) added to each message (from upstream
+/// crypto_secretstream).
pub const ABYTES: usize = Stream::ABYTES;
/// Plaintext chunk size for streaming file encryption (4 MB).
@@ -30,294 +38,118 @@ pub const ENCRYPTION_CHUNK_SIZE: usize = 4 * 1024 * 1024;
/// Ciphertext chunk size for streaming file decryption (4 MB + overhead).
pub const DECRYPTION_CHUNK_SIZE: usize = ENCRYPTION_CHUNK_SIZE + ABYTES;
-/// Tag for a regular message.
-pub const TAG_MESSAGE: u8 = 0x00;
-
-/// Tag for end of a set of messages (but not end of stream).
-pub const TAG_PUSH: u8 = 0x01;
-
-/// Tag to trigger rekeying for forward secrecy.
-pub const TAG_REKEY: u8 = 0x02;
-
-/// Tag indicating end of stream.
-pub const TAG_FINAL: u8 = 0x03;
-
-/// Stream message tag enum for type-safe tag handling.
-///
-/// This enum provides a more ergonomic interface than raw tag bytes,
-/// and exposes all four libsodium secretstream tags.
-#[derive(Debug, Clone, Copy, PartialEq, Eq)]
-pub enum StreamTag {
- /// Normal message, no state change.
- Message,
- /// Marks end of a set of messages, but not end of stream.
- Push,
- /// Triggers key rotation for forward secrecy.
- Rekey,
- /// Marks end of stream.
- Final,
-}
-
-impl StreamTag {
- /// Convert to raw byte representation.
- #[inline]
- pub const fn as_byte(self) -> u8 {
- match self {
- StreamTag::Message => TAG_MESSAGE,
- StreamTag::Push => TAG_PUSH,
- StreamTag::Rekey => TAG_REKEY,
- StreamTag::Final => TAG_FINAL,
- }
- }
-
- /// Check if this is the final tag.
- #[inline]
- pub const fn is_final(self) -> bool {
- matches!(self, StreamTag::Final)
- }
-}
-
-impl From<StreamTag> for u8 {
- fn from(tag: StreamTag) -> u8 {
- tag.as_byte()
- }
-}
-
-impl TryFrom<u8> for StreamTag {
- type Error = CryptoError;
-
- fn try_from(byte: u8) -> std::result::Result<Self, Self::Error> {
- match byte {
- TAG_MESSAGE => Ok(StreamTag::Message),
- TAG_PUSH => Ok(StreamTag::Push),
- TAG_REKEY => Ok(StreamTag::Rekey),
- TAG_FINAL => Ok(StreamTag::Final),
- _ => Err(CryptoError::StreamPullFailed),
- }
- }
-}
-
-impl From<Tag> for StreamTag {
- fn from(tag: Tag) -> Self {
- match tag {
- Tag::Message => StreamTag::Message,
- Tag::Push => StreamTag::Push,
- Tag::Rekey => StreamTag::Rekey,
- Tag::Final => StreamTag::Final,
- }
- }
-}
-
-impl From<StreamTag> for Tag {
- fn from(tag: StreamTag) -> Self {
- match tag {
- StreamTag::Message => Tag::Message,
- StreamTag::Push => Tag::Push,
- StreamTag::Rekey => Tag::Rekey,
- StreamTag::Final => Tag::Final,
- }
- }
+fn upstream_key(key: &Key) -> UpstreamKey {
+ UpstreamKey::from(*key.as_bytes())
}
-/// Result of stream encryption.
-#[derive(Debug, Clone)]
-pub struct EncryptedStream {
- /// The encrypted data.
- pub encrypted_data: Vec<u8>,
- /// The decryption header.
- pub decryption_header: Vec<u8>,
-}
-
-/// Streaming encryptor for XChaCha20-Poly1305.
-pub struct StreamEncryptor {
+/// Stateful chunk-by-chunk encryptor.
+///
+/// Encrypt each chunk with [`push`](Self::push), marking the last one with
+/// `is_final`. The [`header`](Self::header) must be preserved for decryption.
+pub struct Encryptor {
stream: PushStream,
- /// The encryption header (24 bytes).
- pub header: Vec<u8>,
+ header: Header,
}
-impl StreamEncryptor {
+impl Encryptor {
/// Create a new encryptor with a random header.
- pub fn new(key: &[u8]) -> Result<Self> {
- if key.len() != KEY_BYTES {
- return Err(CryptoError::InvalidKeyLength {
- expected: KEY_BYTES,
- actual: key.len(),
- });
- }
-
- let key = Key::try_from(key).map_err(|_| CryptoError::StreamPushFailed)?;
- let (header, stream) = PushStream::init(OsRng, &key);
-
- Ok(Self {
+ pub fn new(key: &Key) -> Self {
+ let (header, stream) = PushStream::init(OsRng, &upstream_key(key));
+ Self {
stream,
- header: header.as_ref().to_vec(),
- })
+ header: Header::from_bytes(*header.as_ref()),
+ }
}
- /// Encrypt a message.
- #[inline]
- pub fn push(&mut self, plaintext: &[u8], is_final: bool) -> Result<Vec<u8>> {
- self.push_with_ad(plaintext, &[], is_final)
+ /// The decryption header. Required for decryption; not secret.
+ pub fn header(&self) -> &Header {
+ &self.header
}
- /// Encrypt a message with additional authenticated data.
- ///
- /// This allocates a new buffer. For zero-copy encryption, use [`push_in_place`].
- pub fn push_with_ad(&mut self, plaintext: &[u8], ad: &[u8], is_final: bool) -> Result<Vec<u8>> {
- let mut buffer = Vec::with_capacity(plaintext.len() + ABYTES);
- buffer.extend_from_slice(plaintext);
- self.push_in_place(&mut buffer, ad, is_final)?;
+ /// Encrypt a chunk, marking it final if it is the last one.
+ pub fn push(&mut self, data: &[u8], is_final: bool) -> Result<Vec<u8>> {
+ let mut buffer = Vec::with_capacity(data.len() + ABYTES);
+ buffer.extend_from_slice(data);
+ self.push_in_place(&mut buffer, is_final)?;
Ok(buffer)
}
- /// Encrypt a message in-place.
- ///
- /// The buffer should contain the plaintext. After this call, it will contain
- /// the ciphertext (plaintext.len() + ABYTES bytes).
- #[inline]
- pub fn push_in_place(&mut self, buffer: &mut Vec<u8>, ad: &[u8], is_final: bool) -> Result<()> {
+ /// Encrypt a chunk in-place: the buffer's plaintext is replaced by
+ /// ciphertext (growing by [`ABYTES`]).
+ fn push_in_place(&mut self, buffer: &mut Vec<u8>, is_final: bool) -> Result<()> {
let tag = if is_final { Tag::Final } else { Tag::Message };
self.stream
- .push(buffer, ad, tag)
- .map_err(|_| CryptoError::StreamPushFailed)?;
- Ok(())
+ .push(buffer, &[], tag)
+ .map_err(|_| CryptoError::StreamPushFailed)
}
}
-/// Streaming decryptor for XChaCha20-Poly1305.
-pub struct StreamDecryptor {
+/// Stateful chunk-by-chunk decryptor.
+///
+/// Decrypt each chunk with [`pull`](Self::pull). After the last chunk, call
+/// [`finish`](Self::finish) β€” it fails if the stream's final tag was never
+/// seen, which is how truncation at a chunk boundary is detected.
+pub struct Decryptor {
stream: PullStream,
+ seen_final: bool,
}
-impl StreamDecryptor {
- /// Create a new decryptor from a header.
- pub fn new(header: &[u8], key: &[u8]) -> Result<Self> {
- if header.len() != HEADER_BYTES {
- return Err(CryptoError::InvalidHeaderLength {
- expected: HEADER_BYTES,
- actual: header.len(),
- });
- }
- if key.len() != KEY_BYTES {
- return Err(CryptoError::InvalidKeyLength {
- expected: KEY_BYTES,
- actual: key.len(),
- });
+impl Decryptor {
+ /// Create a new decryptor from the header that was produced during
+ /// encryption.
+ pub fn new(header: &Header, key: &Key) -> Self {
+ let header = UpstreamHeader::from(*header.as_bytes());
+ let stream = PullStream::init(header, &upstream_key(key));
+ Self {
+ stream,
+ seen_final: false,
}
-
- let key = Key::try_from(key).map_err(|_| CryptoError::StreamPullFailed)?;
- let header = Header::try_from(header).map_err(|_| CryptoError::StreamPullFailed)?;
- let stream = PullStream::init(header, &key);
-
- Ok(Self { stream })
}
- /// Decrypt a message.
- #[inline]
- pub fn pull(&mut self, ciphertext: &[u8]) -> Result<(Vec<u8>, u8)> {
- self.pull_with_ad(ciphertext, &[])
- }
-
- /// Decrypt a message with additional authenticated data.
+ /// Decrypt a chunk.
///
- /// This allocates a new buffer. For zero-copy decryption, use [`pull_in_place`].
- pub fn pull_with_ad(&mut self, ciphertext: &[u8], ad: &[u8]) -> Result<(Vec<u8>, u8)> {
- let mut buffer = ciphertext.to_vec();
- let tag = self.pull_in_place(&mut buffer, ad)?;
- Ok((buffer, tag))
+ /// Returns the plaintext and whether this was the final chunk.
+ pub fn pull(&mut self, data: &[u8]) -> Result<(Vec<u8>, bool)> {
+ let mut buffer = data.to_vec();
+ let is_final = self.pull_in_place(&mut buffer)?;
+ Ok((buffer, is_final))
}
- /// Decrypt a message in-place.
- ///
- /// The buffer should contain the ciphertext. After this call, it will contain
- /// the plaintext (ciphertext.len() - ABYTES bytes).
- ///
- /// Returns the tag byte (TAG_MESSAGE or TAG_FINAL).
- pub fn pull_in_place(&mut self, buffer: &mut Vec<u8>, ad: &[u8]) -> Result<u8> {
+ /// Decrypt a chunk in-place: the buffer's ciphertext is replaced by
+ /// plaintext (shrinking by [`ABYTES`]). Returns whether this was the
+ /// final chunk.
+ fn pull_in_place(&mut self, buffer: &mut Vec<u8>) -> Result<bool> {
if buffer.len() < ABYTES {
return Err(CryptoError::StreamPullFailed);
}
let tag = self
.stream
- .pull(buffer, ad)
+ .pull(buffer, &[])
.map_err(|_| CryptoError::StreamPullFailed)?;
- let tag_byte = match tag {
- Tag::Message => TAG_MESSAGE,
- Tag::Push => TAG_PUSH,
- Tag::Rekey => TAG_REKEY,
- Tag::Final => TAG_FINAL,
- };
-
- Ok(tag_byte)
- }
-
- /// Decrypt a message, returning a typed [`StreamTag`].
- #[inline]
- pub fn pull_typed(&mut self, ciphertext: &[u8]) -> Result<(Vec<u8>, StreamTag)> {
- self.pull_typed_with_ad(ciphertext, &[])
- }
-
- /// Decrypt a message with additional authenticated data, returning a typed [`StreamTag`].
- pub fn pull_typed_with_ad(
- &mut self,
- ciphertext: &[u8],
- ad: &[u8],
- ) -> Result<(Vec<u8>, StreamTag)> {
- let mut buffer = ciphertext.to_vec();
- let tag = self.pull_in_place_typed(&mut buffer, ad)?;
- Ok((buffer, tag))
- }
-
- /// Decrypt a message in-place, returning a typed [`StreamTag`].
- pub fn pull_in_place_typed(&mut self, buffer: &mut Vec<u8>, ad: &[u8]) -> Result<StreamTag> {
- if buffer.len() < ABYTES {
- return Err(CryptoError::StreamPullFailed);
+ let is_final = matches!(tag, Tag::Final);
+ if is_final {
+ self.seen_final = true;
}
-
- let tag = self
- .stream
- .pull(buffer, ad)
- .map_err(|_| CryptoError::StreamPullFailed)?;
-
- Ok(tag.into())
+ Ok(is_final)
}
-}
-
-/// Encrypt data in a single chunk (convenience function).
-pub fn encrypt(plaintext: &[u8], key: &[u8]) -> Result<EncryptedStream> {
- let mut encryptor = StreamEncryptor::new(key)?;
- let header = encryptor.header.clone();
- let ciphertext = encryptor.push(plaintext, true)?;
- Ok(EncryptedStream {
- encrypted_data: ciphertext,
- decryption_header: header,
- })
-}
-/// Decrypt data encrypted with [`encrypt`].
-///
-/// # Errors
-/// Returns `CryptoError::StreamTruncated` if the ciphertext does not have TAG_FINAL.
-/// This ensures the one-shot helper only accepts complete single-chunk streams.
-pub fn decrypt(ciphertext: &[u8], header: &[u8], key: &[u8]) -> Result<Vec<u8>> {
- let mut decryptor = StreamDecryptor::new(header, key)?;
- let (plaintext, tag) = decryptor.pull(ciphertext)?;
- if tag != TAG_FINAL {
- return Err(CryptoError::StreamTruncated);
+ /// Verify that the stream was complete.
+ ///
+ /// Returns `CryptoError::StreamTruncated` if no final-tagged chunk was
+ /// pulled, which means the ciphertext was truncated at a chunk boundary.
+ pub fn finish(self) -> Result<()> {
+ if self.seen_final {
+ Ok(())
+ } else {
+ Err(CryptoError::StreamTruncated)
+ }
}
- Ok(plaintext)
-}
-
-/// Decrypt data encrypted with [`encrypt`] using a stream wrapper.
-pub fn decrypt_stream(encrypted: &EncryptedStream, key: &[u8]) -> Result<Vec<u8>> {
- decrypt(&encrypted.encrypted_data, &encrypted.decryption_header, key)
}
-/// Estimate encrypted size for chunked secretstream encryption.
-///
-/// Estimate ciphertext size (excluding header) for chunked secretstream encryption.
+/// Estimate ciphertext size (excluding header) for chunked secretstream
+/// encryption.
///
/// The stream is split into `ENCRYPTION_CHUNK_SIZE` chunks. The last chunk is
/// tagged FINAL; if the plaintext is empty, a single empty FINAL chunk is
@@ -352,10 +184,11 @@ pub fn estimate_encrypted_size(plaintext_len: usize) -> usize {
}
}
-/// Validate that plaintext and ciphertext sizes match chunked secretstream encryption.
+/// Validate that plaintext and ciphertext sizes match chunked secretstream
+/// encryption.
///
-/// Returns `true` if the ciphertext size matches what [`estimate_encrypted_size`]
-/// would produce for the given plaintext size.
+/// Returns `true` if the ciphertext size matches what
+/// [`estimate_encrypted_size`] would produce for the given plaintext size.
///
/// **Note**: This validates ciphertext size only, NOT including the header.
#[inline]
@@ -372,7 +205,7 @@ pub fn validate_sizes(plaintext_len: usize, ciphertext_len: usize) -> bool {
/// Keeps the last full plaintext chunk in memory so it can be tagged FINAL
/// without emitting an extra empty FINAL chunk on exact chunk boundaries.
pub struct StreamingEncryptor<W: Write> {
- encryptor: StreamEncryptor,
+ encryptor: Encryptor,
writer: W,
/// Remainder bytes (< chunk size).
buffer: Vec<u8>,
@@ -383,9 +216,11 @@ pub struct StreamingEncryptor<W: Write> {
impl<W: Write> StreamingEncryptor<W> {
/// Create a new streaming encryptor.
- pub fn new(key: &[u8], mut writer: W) -> Result<Self> {
- let encryptor = StreamEncryptor::new(key)?;
- writer.write_all(&encryptor.header)?;
+ ///
+ /// The decryption header is written to the writer before any ciphertext.
+ pub fn new(key: &Key, mut writer: W) -> Result<Self> {
+ let encryptor = Encryptor::new(key);
+ writer.write_all(encryptor.header().as_bytes())?;
Ok(Self {
encryptor,
writer,
@@ -399,8 +234,7 @@ impl<W: Write> StreamingEncryptor<W> {
return Ok(());
}
- self.encryptor
- .push_in_place(&mut self.pending, &[], is_final)?;
+ self.encryptor.push_in_place(&mut self.pending, is_final)?;
self.writer.write_all(&self.pending)?;
self.pending.clear();
Ok(())
@@ -459,7 +293,7 @@ impl<W: Write> StreamingEncryptor<W> {
}
}
- self.encryptor.push_in_place(&mut self.buffer, &[], true)?;
+ self.encryptor.push_in_place(&mut self.buffer, true)?;
self.writer.write_all(&self.buffer)?;
Ok(self.writer)
}
@@ -472,12 +306,14 @@ impl<W: Write> StreamingEncryptor<W> {
/// - Decryption happens in-place (buffer shrinks by ABYTES)
/// - Plaintext is served via indices into the same buffer
///
-/// This eliminates the extra copies that would occur with separate read/decrypt/output buffers.
+/// This eliminates the extra copies that would occur with separate
+/// read/decrypt/output buffers.
pub struct StreamingDecryptor<R: Read> {
- decryptor: StreamDecryptor,
+ decryptor: Decryptor,
reader: R,
- /// Single buffer: holds ciphertext during read, then plaintext after decryption.
- /// Unconsumed plaintext is at indices `data_start..buffer.len()`.
+ /// Single buffer: holds ciphertext during read, then plaintext after
+ /// decryption. Unconsumed plaintext is at indices
+ /// `data_start..buffer.len()`.
buffer: Vec<u8>,
/// Start index of unconsumed plaintext in buffer.
data_start: usize,
@@ -501,13 +337,11 @@ fn ensure_reader_exhausted<R: Read>(reader: &mut R) -> Result<()> {
impl<R: Read> StreamingDecryptor<R> {
/// Create a new streaming decryptor.
///
- /// Uses a single-buffer strategy: ciphertext is read into the buffer,
- /// decrypted in-place, and plaintext is served via indices. This minimizes
- /// memory copies compared to using separate read/decrypt/output buffers.
- pub fn new(key: &[u8], mut reader: R) -> Result<Self> {
- let mut header = [0u8; HEADER_BYTES];
+ /// The decryption header is read from the reader before any ciphertext.
+ pub fn new(key: &Key, mut reader: R) -> Result<Self> {
+ let mut header = [0u8; Header::BYTES];
reader.read_exact(&mut header)?;
- let decryptor = StreamDecryptor::new(&header, key)?;
+ let decryptor = Decryptor::new(&Header::from_bytes(header), key);
Ok(Self {
decryptor,
reader,
@@ -520,16 +354,10 @@ impl<R: Read> StreamingDecryptor<R> {
/// Read and decrypt data into the provided buffer.
/// Returns the number of bytes read, or 0 if EOF.
- ///
- /// Uses a single-buffer strategy with index-based tracking to avoid
- /// O(n) front-drain operations and eliminate extra memory copies:
- /// - Ciphertext is read directly into `buffer`
- /// - Decryption happens in-place (buffer shrinks by ABYTES)
- /// - Plaintext is served via `data_start` index into the same buffer
pub fn read(&mut self, buf: &mut [u8]) -> Result<usize> {
// If we have buffered plaintext, return it first (O(1) via index)
// This must be checked BEFORE the finished flag, since we may have
- // buffered data remaining after seeing TAG_FINAL.
+ // buffered data remaining after seeing the final tag.
let buffered_remaining = self.buffer.len() - self.data_start;
if buffered_remaining > 0 {
let to_copy = std::cmp::min(buf.len(), buffered_remaining);
@@ -581,9 +409,9 @@ impl<R: Read> StreamingDecryptor<R> {
// Truncate buffer to actual bytes read, then decrypt in-place
self.buffer.truncate(total_read);
- let tag = self.decryptor.pull_in_place(&mut self.buffer, &[])?;
+ let is_final = self.decryptor.pull_in_place(&mut self.buffer)?;
- if tag == TAG_FINAL {
+ if is_final {
self.seen_final = true;
ensure_reader_exhausted(&mut self.reader)?;
self.finished = true;
@@ -621,21 +449,31 @@ impl<R: Read> StreamingDecryptor<R> {
}
}
-type EncryptFileResult = Result<(Vec<u8>, Vec<u8>, Option<Vec<u8>>)>;
-
-fn encrypt_file_internal<R: Read, W: Write>(
+/// Encrypt a file from a reader to a writer.
+///
+/// Returns the decryption header. The header is NOT written to the writer;
+/// it travels separately (e.g. as part of the file's server-side metadata).
+///
+/// # Output Format
+///
+/// This function produces output consistent with [`StreamingEncryptor`]:
+/// - Full chunks are encrypted with MESSAGE tags
+/// - The last chunk is tagged FINAL (empty FINAL chunk only for empty
+/// plaintext)
+///
+/// Use [`estimate_encrypted_size`] to predict the ciphertext size (excluding
+/// header).
+///
+/// This function uses reusable buffers and in-place encryption to avoid
+/// allocating fresh memory per chunk. Memory usage is bounded to ~2x chunk
+/// size.
+pub fn encrypt_file<R: Read, W: Write>(
reader: &mut R,
writer: &mut W,
- key: Option<&[u8]>,
- mut md5_state: Option<Md5>,
-) -> EncryptFileResult {
- let key = match key {
- Some(k) => k.to_vec(),
- None => crate::crypto::Key::generate().as_bytes().to_vec(),
- };
-
- let mut encryptor = StreamEncryptor::new(&key)?;
- let header = encryptor.header.clone();
+ key: &Key,
+) -> Result<Header> {
+ let mut encryptor = Encryptor::new(key);
+ let header = *encryptor.header();
let mut read_chunk = |buf: &mut [u8]| -> Result<usize> {
let mut total_read = 0;
@@ -662,14 +500,9 @@ fn encrypt_file_internal<R: Read, W: Write>(
if curr_len == 0 {
// Empty file: single empty FINAL chunk
encrypt_buffer.clear();
- encryptor.push_in_place(&mut encrypt_buffer, &[], true)?;
- if let Some(state) = md5_state.as_mut() {
- state.update(&encrypt_buffer);
- }
+ encryptor.push_in_place(&mut encrypt_buffer, true)?;
writer.write_all(&encrypt_buffer)?;
-
- let md5 = md5_state.map(|state| state.finalize().as_slice().to_vec());
- return Ok((key, header, md5));
+ return Ok(header);
}
loop {
@@ -677,10 +510,7 @@ fn encrypt_file_internal<R: Read, W: Write>(
// Last chunk is partial
encrypt_buffer.clear();
encrypt_buffer.extend_from_slice(&curr[..curr_len]);
- encryptor.push_in_place(&mut encrypt_buffer, &[], true)?;
- if let Some(state) = md5_state.as_mut() {
- state.update(&encrypt_buffer);
- }
+ encryptor.push_in_place(&mut encrypt_buffer, true)?;
writer.write_all(&encrypt_buffer)?;
break;
}
@@ -690,10 +520,7 @@ fn encrypt_file_internal<R: Read, W: Write>(
encrypt_buffer.clear();
encrypt_buffer.extend_from_slice(&curr[..curr_len]);
- encryptor.push_in_place(&mut encrypt_buffer, &[], is_final)?;
- if let Some(state) = md5_state.as_mut() {
- state.update(&encrypt_buffer);
- }
+ encryptor.push_in_place(&mut encrypt_buffer, is_final)?;
writer.write_all(&encrypt_buffer)?;
if is_final {
@@ -704,68 +531,30 @@ fn encrypt_file_internal<R: Read, W: Write>(
curr_len = next_len;
}
- let md5 = md5_state.map(|state| state.finalize().as_slice().to_vec());
-
- Ok((key, header, md5))
-}
-
-/// Encrypt a file from a reader to a writer.
-///
-/// If `key` is `None`, a random key is generated.
-/// Returns `(key, header)` for use in decryption.
-///
-/// # Output Format
-///
-/// This function produces output consistent with [`StreamingEncryptor`]:
-/// - Full chunks are encrypted with MESSAGE tags
-/// - The last chunk is tagged FINAL (empty FINAL chunk only for empty plaintext)
-///
-/// Use [`estimate_encrypted_size`] to predict the ciphertext size (excluding header).
-///
-/// This function uses reusable buffers and in-place encryption to avoid
-/// allocating fresh memory per chunk. Memory usage is bounded to ~2x chunk size.
-pub fn encrypt_file<R: Read, W: Write>(
- reader: &mut R,
- writer: &mut W,
- key: Option<&[u8]>,
-) -> Result<(Vec<u8>, Vec<u8>)> {
- let (key, header, _md5) = encrypt_file_internal(reader, writer, key, None)?;
- Ok((key, header))
-}
-
-/// Encrypt a file from a reader to a writer and compute MD5 of the ciphertext.
-///
-/// This is a convenience wrapper around [`encrypt_file`], returning the MD5
-/// digest of the encrypted output (excluding the header).
-pub fn encrypt_file_with_md5<R: Read, W: Write>(
- reader: &mut R,
- writer: &mut W,
- key: Option<&[u8]>,
-) -> Result<(Vec<u8>, Vec<u8>, Vec<u8>)> {
- let (key, header, md5) = encrypt_file_internal(reader, writer, key, Some(Md5::new()))?;
- let md5 = md5.ok_or(CryptoError::HashFailed)?;
- Ok((key, header, md5))
+ Ok(header)
}
/// Decrypt a file from a reader to a writer.
///
-/// The reader should contain encrypted data (without the header).
-/// The header and key should be provided separately.
+/// The reader should contain encrypted data (without the header). The header
+/// and key are provided separately.
///
/// This function uses reusable buffers and in-place decryption to avoid
-/// allocating fresh memory per chunk. Memory usage is bounded to ~2x chunk size.
+/// allocating fresh memory per chunk. Memory usage is bounded to ~2x chunk
+/// size.
///
/// # Errors
-/// Returns `CryptoError::StreamTruncated` if EOF is reached without seeing TAG_FINAL.
-/// This prevents silent truncation attacks at chunk boundaries.
-/// Returns `CryptoError::StreamTrailingData` if bytes remain after a TAG_FINAL chunk.
+/// Returns `CryptoError::StreamTruncated` if EOF is reached without seeing the
+/// final tag. This prevents silent truncation attacks at chunk boundaries.
+/// Returns `CryptoError::StreamTrailingData` if bytes remain after the final
+/// chunk.
pub fn decrypt_file<R: Read, W: Write>(
reader: &mut R,
writer: &mut W,
- header: &[u8],
- key: &[u8],
+ header: &Header,
+ key: &Key,
) -> Result<()> {
- let mut decryptor = StreamDecryptor::new(header, key)?;
+ let mut decryptor = Decryptor::new(header, key);
// Reusable read buffer - sized for ciphertext chunks
let mut read_buffer = vec![0u8; DECRYPTION_CHUNK_SIZE];
// Reusable decrypt buffer for in-place decryption (avoids per-chunk allocation)
@@ -784,18 +573,17 @@ pub fn decrypt_file<R: Read, W: Write>(
}
if total_read == 0 {
- // EOF reached without seeing TAG_FINAL - stream was truncated
- // (if we had seen TAG_FINAL, we would have exited the loop via break below)
- return Err(CryptoError::StreamTruncated);
+ // EOF reached without seeing the final tag - stream was truncated
+ return decryptor.finish();
}
// Copy to decrypt buffer and decrypt in-place (reuses buffer each iteration)
decrypt_buffer.clear();
decrypt_buffer.extend_from_slice(&read_buffer[..total_read]);
- let tag = decryptor.pull_in_place(&mut decrypt_buffer, &[])?;
+ let is_final = decryptor.pull_in_place(&mut decrypt_buffer)?;
writer.write_all(&decrypt_buffer)?;
- if tag == TAG_FINAL {
+ if is_final {
// Successfully decrypted the final chunk - stream is complete
ensure_reader_exhausted(reader)?;
return Ok(());
@@ -805,9 +593,9 @@ pub fn decrypt_file<R: Read, W: Write>(
/// Decrypt file data that's already in memory.
///
-/// This is a convenience function for when you have the entire encrypted file in a buffer.
-/// The header (decryption nonce) and key must be provided separately.
-pub fn decrypt_file_data(encrypted_data: &[u8], header: &[u8], key: &[u8]) -> Result<Vec<u8>> {
+/// This is a convenience function for when you have the entire encrypted file
+/// in a buffer. The header and key must be provided separately.
+pub fn decrypt_file_data(encrypted_data: &[u8], header: &Header, key: &Key) -> Result<Vec<u8>> {
use std::io::Cursor;
let mut reader = Cursor::new(encrypted_data);
@@ -819,16 +607,15 @@ pub fn decrypt_file_data(encrypted_data: &[u8], header: &[u8], key: &[u8]) -> Re
#[cfg(test)]
mod tests {
use super::*;
- use md5::{Digest, Md5};
use std::io::Cursor;
- fn generate_test_key() -> [u8; KEY_BYTES] {
- [0x42u8; KEY_BYTES]
+ fn test_key() -> Key {
+ Key::from_bytes([0x42u8; Key::BYTES])
}
#[test]
fn test_streaming_roundtrip() {
- let key = generate_test_key();
+ let key = test_key();
let plaintext = b"Hello, world! This is a test message.";
// Encrypt
@@ -851,14 +638,11 @@ mod tests {
#[test]
fn test_truncation_detection_empty_stream() {
- let key = generate_test_key();
+ let key = test_key();
// Create a stream with just the header, no encrypted data
- let encryptor = StreamEncryptor::new(&key).expect("encryptor creation failed");
- let header = encryptor.header;
-
- // Don't write any encrypted chunks - just the header
- let truncated_data = header;
+ let encryptor = Encryptor::new(&key);
+ let truncated_data = encryptor.header().as_bytes().to_vec();
let reader = Cursor::new(&truncated_data);
let mut decryptor =
@@ -874,16 +658,13 @@ mod tests {
#[test]
fn test_truncation_detection_missing_final() {
- let key = generate_test_key();
+ let key = test_key();
let plaintext = b"Hello, world!";
// Encrypt with non-final tag only
- let mut encryptor = StreamEncryptor::new(&key).expect("encryptor creation failed");
- let header = encryptor.header.clone();
- let encrypted_chunk = encryptor.push(plaintext, false).expect("push failed"); // Note: is_final = false
-
- // Create truncated stream: header + non-final chunk
- let mut truncated_data = header;
+ let mut encryptor = Encryptor::new(&key);
+ let mut truncated_data = encryptor.header().as_bytes().to_vec();
+ let encrypted_chunk = encryptor.push(plaintext, false).expect("push failed");
truncated_data.extend_from_slice(&encrypted_chunk);
let reader = Cursor::new(&truncated_data);
@@ -900,16 +681,12 @@ mod tests {
#[test]
fn test_valid_stream_with_final_tag() {
- let key = generate_test_key();
+ let key = test_key();
let plaintext = b"Hello, world!";
- // Encrypt properly with final tag
- let mut encryptor = StreamEncryptor::new(&key).expect("encryptor creation failed");
- let header = encryptor.header.clone();
+ let mut encryptor = Encryptor::new(&key);
+ let mut data = encryptor.header().as_bytes().to_vec();
let encrypted_chunk = encryptor.push(plaintext, true).expect("push failed");
-
- // Create proper stream: header + final chunk
- let mut data = header;
data.extend_from_slice(&encrypted_chunk);
let reader = Cursor::new(&data);
@@ -920,11 +697,49 @@ mod tests {
assert_eq!(plaintext.as_slice(), decrypted.as_slice());
}
+ #[test]
+ fn test_decryptor_finish_detects_missing_final_tag() {
+ // Manual chunk-by-chunk decryption succeeds per-chunk, but finish()
+ // must catch a stream that never carried the final tag.
+ let key = test_key();
+
+ let mut encryptor = Encryptor::new(&key);
+ let header = *encryptor.header();
+ let chunk1 = encryptor.push(b"chunk one", false).unwrap();
+ let chunk2 = encryptor.push(b"chunk two", false).unwrap();
+
+ let mut decryptor = Decryptor::new(&header, &key);
+ let (pt1, is_final1) = decryptor.pull(&chunk1).unwrap();
+ let (pt2, is_final2) = decryptor.pull(&chunk2).unwrap();
+ assert_eq!(pt1, b"chunk one");
+ assert_eq!(pt2, b"chunk two");
+ assert!(!is_final1 && !is_final2);
+
+ assert!(matches!(
+ decryptor.finish(),
+ Err(CryptoError::StreamTruncated)
+ ));
+ }
+
+ #[test]
+ fn test_decryptor_finish_accepts_complete_stream() {
+ let key = test_key();
+
+ let mut encryptor = Encryptor::new(&key);
+ let header = *encryptor.header();
+ let chunk = encryptor.push(b"only chunk", true).unwrap();
+
+ let mut decryptor = Decryptor::new(&header, &key);
+ let (_, is_final) = decryptor.pull(&chunk).unwrap();
+ assert!(is_final);
+ decryptor.finish().unwrap();
+ }
+
#[test]
fn test_small_buffer_reads_no_quadratic() {
// Regression test: ensure small-buffer reads don't cause O(nΒ²) behavior.
// Uses index-based buffering instead of Vec::drain() to achieve O(n) total.
- let key = generate_test_key();
+ let key = test_key();
// Use a larger plaintext to make the test meaningful
let plaintext: Vec<u8> = (0..10000).map(|i| (i % 256) as u8).collect();
@@ -957,7 +772,7 @@ mod tests {
#[test]
fn test_varied_buffer_sizes() {
// Test with various buffer sizes to ensure correctness
- let key = generate_test_key();
+ let key = test_key();
let plaintext: Vec<u8> = (0..5000).map(|i| (i % 256) as u8).collect();
// Encrypt
@@ -995,10 +810,7 @@ mod tests {
#[test]
fn test_large_slice_write_no_quadratic() {
// Regression test: verify StreamingEncryptor::write() is O(n) for large slices.
- // The optimization processes full chunks directly from input slice without
- // buffering them first, and buffers only the remainder (< chunk size).
- // This avoids O(nΒ²) behavior that would occur with copy_within compaction.
- let key = generate_test_key();
+ let key = test_key();
// Create data spanning multiple chunks to exercise the optimization
// 3 full chunks + partial = tests the direct slice processing path
@@ -1033,7 +845,7 @@ mod tests {
fn test_write_with_partial_buffer_then_large_slice() {
// Regression test: verify optimization handles partial buffer correctly.
// Write small data (partial buffer), then large data that spans chunks.
- let key = generate_test_key();
+ let key = test_key();
let mut encrypted = Vec::new();
{
@@ -1079,25 +891,10 @@ mod tests {
}
}
- // Expanded unit tests
-
- #[test]
- fn test_empty_input() {
- // Test encryption/decryption of empty data
- let key = generate_test_key();
- let plaintext = b"";
-
- let encrypted = encrypt(plaintext, &key).expect("encrypt failed");
- let decrypted = decrypt_stream(&encrypted, &key).expect("decrypt failed");
-
- assert_eq!(plaintext.as_slice(), decrypted.as_slice());
- assert_eq!(encrypted.encrypted_data.len(), ABYTES); // Just the tag overhead
- }
-
#[test]
fn test_empty_streaming() {
// Test streaming encryption/decryption of empty data
- let key = generate_test_key();
+ let key = test_key();
// Encrypt empty data
let mut encrypted = Vec::new();
@@ -1122,18 +919,16 @@ mod tests {
#[test]
fn test_multi_chunk_roundtrip() {
- // Test with data larger than ENCRYPTION_CHUNK_SIZE
- let key = generate_test_key();
- // Create data that spans multiple chunks (use smaller chunks for test speed)
- let chunk_size = 1024; // Smaller for test
+ // Test with data larger than a (test-sized) chunk
+ let key = test_key();
+ let chunk_size = 1024; // Smaller for test speed
let num_chunks = 3;
let plaintext: Vec<u8> = (0..(chunk_size * num_chunks + 500))
.map(|i| (i % 256) as u8)
.collect();
- // Use low-level encryptor to test multi-chunk
- let mut encryptor = StreamEncryptor::new(&key).expect("encryptor creation failed");
- let header = encryptor.header.clone();
+ let mut encryptor = Encryptor::new(&key);
+ let header = *encryptor.header();
let mut ciphertext = Vec::new();
let mut offset = 0;
@@ -1148,34 +943,34 @@ mod tests {
}
// Decrypt chunk by chunk
- let mut decryptor = StreamDecryptor::new(&header, &key).expect("decryptor creation failed");
+ let mut decryptor = Decryptor::new(&header, &key);
let mut decrypted = Vec::new();
let mut ct_offset = 0;
- while ct_offset < ciphertext.len() {
+ loop {
let chunk_end = std::cmp::min(ct_offset + chunk_size + ABYTES, ciphertext.len());
- let (chunk_pt, tag) = decryptor
+ let (chunk_pt, is_final) = decryptor
.pull(&ciphertext[ct_offset..chunk_end])
.expect("pull failed");
decrypted.extend_from_slice(&chunk_pt);
ct_offset = chunk_end;
- if tag == TAG_FINAL {
+ if is_final {
break;
}
}
+ decryptor.finish().expect("finish failed");
assert_eq!(plaintext, decrypted);
}
#[test]
fn test_tamper_detection_ciphertext() {
- // Test that tampering with ciphertext is detected
- let key = generate_test_key();
+ let key = test_key();
let plaintext = b"Secret message that should not be tampered with";
- let mut encryptor = StreamEncryptor::new(&key).expect("encryptor creation failed");
- let header = encryptor.header.clone();
+ let mut encryptor = Encryptor::new(&key);
+ let header = *encryptor.header();
let mut ciphertext = encryptor.push(plaintext, true).expect("push failed");
// Tamper with the ciphertext (flip a bit in the middle)
@@ -1183,7 +978,7 @@ mod tests {
ciphertext[mid] ^= 0x01;
// Decryption should fail
- let mut decryptor = StreamDecryptor::new(&header, &key).expect("decryptor creation failed");
+ let mut decryptor = Decryptor::new(&header, &key);
let result = decryptor.pull(&ciphertext);
assert!(
@@ -1195,19 +990,18 @@ mod tests {
#[test]
fn test_tamper_detection_header() {
- // Test that tampering with header causes decryption failure
- let key = generate_test_key();
+ let key = test_key();
let plaintext = b"Secret message";
- let mut encryptor = StreamEncryptor::new(&key).expect("encryptor creation failed");
- let mut header = encryptor.header.clone();
+ let mut encryptor = Encryptor::new(&key);
+ let mut header_bytes = *encryptor.header().as_bytes();
let ciphertext = encryptor.push(plaintext, true).expect("push failed");
// Tamper with header
- header[0] ^= 0x01;
+ header_bytes[0] ^= 0x01;
// Decryption should fail
- let mut decryptor = StreamDecryptor::new(&header, &key).expect("decryptor creation failed");
+ let mut decryptor = Decryptor::new(&Header::from_bytes(header_bytes), &key);
let result = decryptor.pull(&ciphertext);
assert!(
@@ -1219,19 +1013,18 @@ mod tests {
#[test]
fn test_tamper_detection_mac() {
- // Test that tampering with MAC (last 16 bytes) is detected
- let key = generate_test_key();
+ let key = test_key();
let plaintext = b"Secret message";
- let mut encryptor = StreamEncryptor::new(&key).expect("encryptor creation failed");
- let header = encryptor.header.clone();
+ let mut encryptor = Encryptor::new(&key);
+ let header = *encryptor.header();
let mut ciphertext = encryptor.push(plaintext, true).expect("push failed");
// Tamper with MAC (last byte)
let last = ciphertext.len() - 1;
ciphertext[last] ^= 0x01;
- let mut decryptor = StreamDecryptor::new(&header, &key).expect("decryptor creation failed");
+ let mut decryptor = Decryptor::new(&header, &key);
let result = decryptor.pull(&ciphertext);
assert!(
@@ -1243,17 +1036,15 @@ mod tests {
#[test]
fn test_wrong_key() {
- // Test that wrong key fails decryption
- let key = generate_test_key();
- let wrong_key = [0x43u8; KEY_BYTES];
+ let key = test_key();
+ let wrong_key = Key::from_bytes([0x43u8; Key::BYTES]);
let plaintext = b"Secret message";
- let mut encryptor = StreamEncryptor::new(&key).expect("encryptor creation failed");
- let header = encryptor.header.clone();
+ let mut encryptor = Encryptor::new(&key);
+ let header = *encryptor.header();
let ciphertext = encryptor.push(plaintext, true).expect("push failed");
- let mut decryptor =
- StreamDecryptor::new(&header, &wrong_key).expect("decryptor creation failed");
+ let mut decryptor = Decryptor::new(&header, &wrong_key);
let result = decryptor.pull(&ciphertext);
assert!(
@@ -1263,59 +1054,12 @@ mod tests {
);
}
- #[test]
- fn test_stream_tag_enum() {
- // Test StreamTag conversions
- assert_eq!(StreamTag::Message.as_byte(), TAG_MESSAGE);
- assert_eq!(StreamTag::Push.as_byte(), TAG_PUSH);
- assert_eq!(StreamTag::Rekey.as_byte(), TAG_REKEY);
- assert_eq!(StreamTag::Final.as_byte(), TAG_FINAL);
-
- assert!(!StreamTag::Message.is_final());
- assert!(!StreamTag::Push.is_final());
- assert!(!StreamTag::Rekey.is_final());
- assert!(StreamTag::Final.is_final());
-
- // Test TryFrom<u8>
- assert_eq!(StreamTag::try_from(0x00).unwrap(), StreamTag::Message);
- assert_eq!(StreamTag::try_from(0x01).unwrap(), StreamTag::Push);
- assert_eq!(StreamTag::try_from(0x02).unwrap(), StreamTag::Rekey);
- assert_eq!(StreamTag::try_from(0x03).unwrap(), StreamTag::Final);
- assert!(StreamTag::try_from(0x04).is_err());
- }
-
- #[test]
- fn test_pull_typed() {
- // Test the typed pull methods
- let key = generate_test_key();
- let plaintext = b"Test message";
-
- let mut encryptor = StreamEncryptor::new(&key).expect("encryptor creation failed");
- let header = encryptor.header.clone();
- let ciphertext = encryptor.push(plaintext, true).expect("push failed");
-
- let mut decryptor = StreamDecryptor::new(&header, &key).expect("decryptor creation failed");
- let (decrypted, tag) = decryptor
- .pull_typed(&ciphertext)
- .expect("pull_typed failed");
-
- assert_eq!(decrypted, plaintext);
- assert_eq!(tag, StreamTag::Final);
- assert!(tag.is_final());
- }
-
#[test]
fn test_constants_match_upstream() {
// Verify our constants match the upstream crate
assert_eq!(HEADER_BYTES, 24);
assert_eq!(KEY_BYTES, 32);
assert_eq!(ABYTES, 17);
-
- // Verify tag values match libsodium spec
- assert_eq!(TAG_MESSAGE, 0x00);
- assert_eq!(TAG_PUSH, 0x01);
- assert_eq!(TAG_REKEY, 0x02);
- assert_eq!(TAG_FINAL, 0x03);
}
#[test]
@@ -1348,91 +1092,28 @@ mod tests {
}
#[test]
- fn test_in_place_encryption() {
- // Test the in-place encryption API
- let key = generate_test_key();
- let plaintext = b"Test in-place encryption";
-
- let mut encryptor = StreamEncryptor::new(&key).expect("encryptor creation failed");
- let header = encryptor.header.clone();
-
- let mut buffer = plaintext.to_vec();
- encryptor
- .push_in_place(&mut buffer, &[], true)
- .expect("push_in_place failed");
-
- assert_eq!(buffer.len(), plaintext.len() + ABYTES);
-
- // Decrypt in-place
- let mut decryptor = StreamDecryptor::new(&header, &key).expect("decryptor creation failed");
- let tag = decryptor
- .pull_in_place(&mut buffer, &[])
- .expect("pull_in_place failed");
-
- assert_eq!(tag, TAG_FINAL);
- assert_eq!(buffer, plaintext);
- }
+ fn test_ciphertext_too_short() {
+ let key = test_key();
+ let header = Header::from_bytes([0u8; Header::BYTES]);
- #[test]
- fn test_in_place_typed() {
- // Test the typed in-place decryption API
- let key = generate_test_key();
- let plaintext = b"Test typed in-place";
-
- let mut encryptor = StreamEncryptor::new(&key).expect("encryptor creation failed");
- let header = encryptor.header.clone();
-
- let mut buffer = plaintext.to_vec();
- encryptor
- .push_in_place(&mut buffer, &[], true)
- .expect("push_in_place failed");
-
- let mut decryptor = StreamDecryptor::new(&header, &key).expect("decryptor creation failed");
- let tag = decryptor
- .pull_in_place_typed(&mut buffer, &[])
- .expect("pull_in_place_typed failed");
-
- assert_eq!(tag, StreamTag::Final);
- assert!(tag.is_final());
- assert_eq!(buffer, plaintext);
- }
+ let mut decryptor = Decryptor::new(&header, &key);
+ let result = decryptor.pull(&[0u8; ABYTES - 1]);
- #[test]
- fn test_libsodium_interop_vector() {
- // Test vector derived from libsodium's crypto_secretstream_xchacha20poly1305
- // Key: 32 bytes of 0x00
- // Header: 24 bytes of 0x00 (for deterministic testing)
- // This tests that our implementation produces compatible output format
-
- // Since we use random headers, we test format compatibility by:
- // 1. Encrypting with a known key
- // 2. Verifying the output structure (header size, ciphertext overhead)
- let key = [0u8; KEY_BYTES];
- let plaintext = b"libsodium interop test";
-
- let encrypted = encrypt(plaintext, &key).expect("encrypt failed");
-
- // Verify structure
- assert_eq!(encrypted.decryption_header.len(), HEADER_BYTES);
- assert_eq!(encrypted.encrypted_data.len(), plaintext.len() + ABYTES);
-
- // Verify roundtrip
- let decrypted = decrypt_stream(&encrypted, &key).expect("decrypt failed");
- assert_eq!(decrypted, plaintext);
+ assert!(
+ matches!(result, Err(CryptoError::StreamPullFailed)),
+ "Expected StreamPullFailed for short ciphertext, got {:?}",
+ result
+ );
}
#[test]
fn test_file_encrypt_decrypt_roundtrip() {
- let key = generate_test_key();
+ let key = test_key();
let plaintext: Vec<u8> = (0..10000).map(|i| (i % 256) as u8).collect();
let mut encrypted = Vec::new();
let mut reader = Cursor::new(&plaintext);
- let (returned_key, header) =
- encrypt_file(&mut reader, &mut encrypted, Some(&key)).expect("encrypt_file failed");
-
- assert_eq!(returned_key, key);
- assert_eq!(header.len(), HEADER_BYTES);
+ let header = encrypt_file(&mut reader, &mut encrypted, &key).expect("encrypt_file failed");
let mut decrypted = Vec::new();
let mut enc_reader = Cursor::new(&encrypted);
@@ -1443,13 +1124,11 @@ mod tests {
#[test]
fn test_file_encrypt_decrypt_multi_chunk() {
- // Regression test: exercises multiple chunks to ensure the refactored
- // encrypt_file/decrypt_file functions with in-place APIs work correctly.
- // We use 2x ENCRYPTION_CHUNK_SIZE + extra bytes to test:
+ // Regression test: exercises multiple chunks
// - Multiple full chunks with MESSAGE tag
// - Final partial chunk with FINAL tag
// - Lookahead logic for determining is_final flag
- let key = generate_test_key();
+ let key = test_key();
// 2 full chunks + 1000 bytes (total: ~8MB + 1000)
let size = ENCRYPTION_CHUNK_SIZE * 2 + 1000;
@@ -1457,11 +1136,7 @@ mod tests {
let mut encrypted = Vec::new();
let mut reader = Cursor::new(&plaintext);
- let (returned_key, header) =
- encrypt_file(&mut reader, &mut encrypted, Some(&key)).expect("encrypt_file failed");
-
- assert_eq!(returned_key, key);
- assert_eq!(header.len(), HEADER_BYTES);
+ let header = encrypt_file(&mut reader, &mut encrypted, &key).expect("encrypt_file failed");
// Verify ciphertext size: 2 full chunks + 1 partial chunk
// Each chunk adds ABYTES overhead
@@ -1484,7 +1159,7 @@ mod tests {
fn test_file_encrypt_decrypt_exact_chunk_boundary() {
// Edge case: plaintext exactly at chunk boundary.
// The last full chunk must be tagged FINAL (no extra empty FINAL chunk).
- let key = generate_test_key();
+ let key = test_key();
let plaintext: Vec<u8> = (0..ENCRYPTION_CHUNK_SIZE)
.map(|i| (i % 256) as u8)
@@ -1492,8 +1167,7 @@ mod tests {
let mut encrypted = Vec::new();
let mut reader = Cursor::new(&plaintext);
- let (_, header) =
- encrypt_file(&mut reader, &mut encrypted, Some(&key)).expect("encrypt_file failed");
+ let header = encrypt_file(&mut reader, &mut encrypted, &key).expect("encrypt_file failed");
assert_eq!(encrypted.len(), DECRYPTION_CHUNK_SIZE);
// Should match estimate
@@ -1509,13 +1183,12 @@ mod tests {
#[test]
fn test_file_encrypt_decrypt_empty() {
// Edge case: empty file
- let key = generate_test_key();
+ let key = test_key();
let plaintext: Vec<u8> = Vec::new();
let mut encrypted = Vec::new();
let mut reader = Cursor::new(&plaintext);
- let (_, header) =
- encrypt_file(&mut reader, &mut encrypted, Some(&key)).expect("encrypt_file failed");
+ let header = encrypt_file(&mut reader, &mut encrypted, &key).expect("encrypt_file failed");
// Should be exactly one empty FINAL chunk
assert_eq!(encrypted.len(), ABYTES);
@@ -1529,120 +1202,25 @@ mod tests {
#[test]
fn test_decrypt_file_data() {
- let key = generate_test_key();
+ let key = test_key();
let plaintext = b"Test decrypt_file_data function";
let mut encrypted = Vec::new();
let mut reader = Cursor::new(plaintext.as_slice());
- let (_, header) =
- encrypt_file(&mut reader, &mut encrypted, Some(&key)).expect("encrypt_file failed");
+ let header = encrypt_file(&mut reader, &mut encrypted, &key).expect("encrypt_file failed");
let decrypted =
decrypt_file_data(&encrypted, &header, &key).expect("decrypt_file_data failed");
assert_eq!(decrypted, plaintext);
}
- #[test]
- fn test_additional_data() {
- // Test that additional authenticated data works correctly
- let key = generate_test_key();
- let plaintext = b"Message with AAD";
- let aad = b"additional authenticated data";
-
- let mut encryptor = StreamEncryptor::new(&key).expect("encryptor creation failed");
- let header = encryptor.header.clone();
- let ciphertext = encryptor
- .push_with_ad(plaintext, aad, true)
- .expect("push_with_ad failed");
-
- // Decrypt with correct AAD
- let mut decryptor = StreamDecryptor::new(&header, &key).expect("decryptor creation failed");
- let (decrypted, tag) = decryptor
- .pull_with_ad(&ciphertext, aad)
- .expect("pull_with_ad failed");
-
- assert_eq!(decrypted, plaintext);
- assert_eq!(tag, TAG_FINAL);
- }
-
- #[test]
- fn test_additional_data_mismatch() {
- // Test that mismatched AAD causes decryption failure
- let key = generate_test_key();
- let plaintext = b"Message with AAD";
- let aad = b"correct aad";
- let wrong_aad = b"wrong aad";
-
- let mut encryptor = StreamEncryptor::new(&key).expect("encryptor creation failed");
- let header = encryptor.header.clone();
- let ciphertext = encryptor
- .push_with_ad(plaintext, aad, true)
- .expect("push_with_ad failed");
-
- // Decrypt with wrong AAD should fail
- let mut decryptor = StreamDecryptor::new(&header, &key).expect("decryptor creation failed");
- let result = decryptor.pull_with_ad(&ciphertext, wrong_aad);
-
- assert!(
- matches!(result, Err(CryptoError::StreamPullFailed)),
- "Expected StreamPullFailed with wrong AAD, got {:?}",
- result
- );
- }
-
- #[test]
- fn test_ciphertext_too_short() {
- // Test that ciphertext shorter than ABYTES is rejected
- let key = generate_test_key();
- let header = [0u8; HEADER_BYTES];
- let short_ciphertext = [0u8; ABYTES - 1];
-
- let mut decryptor = StreamDecryptor::new(&header, &key).expect("decryptor creation failed");
- let result = decryptor.pull(&short_ciphertext);
-
- assert!(
- matches!(result, Err(CryptoError::StreamPullFailed)),
- "Expected StreamPullFailed for short ciphertext, got {:?}",
- result
- );
- }
-
- #[test]
- fn test_invalid_key_length() {
- let short_key = [0u8; KEY_BYTES - 1];
- let result = StreamEncryptor::new(&short_key);
-
- assert!(matches!(
- result,
- Err(CryptoError::InvalidKeyLength {
- expected: 32,
- actual: 31
- })
- ));
- }
-
- #[test]
- fn test_invalid_header_length() {
- let key = generate_test_key();
- let short_header = [0u8; HEADER_BYTES - 1];
- let result = StreamDecryptor::new(&short_header, &key);
-
- assert!(matches!(
- result,
- Err(CryptoError::InvalidHeaderLength {
- expected: 24,
- actual: 23
- })
- ));
- }
-
- // Truncation detection tests for decrypt_file / decrypt
+ // Truncation detection tests for decrypt_file
#[test]
fn test_decrypt_file_truncation_empty_ciphertext() {
// Test that decrypt_file detects truncation when there's no ciphertext at all
- let key = generate_test_key();
- let header = [0u8; HEADER_BYTES];
+ let key = test_key();
+ let header = Header::from_bytes([0u8; Header::BYTES]);
let empty_ciphertext: &[u8] = &[];
let mut reader = Cursor::new(empty_ciphertext);
@@ -1660,13 +1238,13 @@ mod tests {
fn test_decrypt_file_truncation_at_chunk_boundary() {
// SECURITY TEST: Verify decrypt_file detects truncation at chunk boundary
// This tests the case where we have a valid MESSAGE chunk but no FINAL chunk
- let key = generate_test_key();
+ let key = test_key();
let plaintext = b"Test message for truncation detection";
// Create a valid encrypted chunk with MESSAGE tag (not FINAL)
- let mut encryptor = StreamEncryptor::new(&key).expect("encryptor creation failed");
- let header = encryptor.header.clone();
- let encrypted_chunk = encryptor.push(plaintext, false).expect("push failed"); // is_final = false
+ let mut encryptor = Encryptor::new(&key);
+ let header = *encryptor.header();
+ let encrypted_chunk = encryptor.push(plaintext, false).expect("push failed");
// Decrypt should fail because there's no FINAL tag
let mut reader = Cursor::new(&encrypted_chunk);
@@ -1683,16 +1261,13 @@ mod tests {
#[test]
fn test_decrypt_file_truncation_via_encrypt_file() {
// Test truncation detection when truncating output from encrypt_file
- // encrypt_file uses lookahead to mark the last chunk as FINAL
- // So we simulate truncation by only keeping part of the ciphertext
- let key = generate_test_key();
+ let key = test_key();
let plaintext = b"Test data that will be truncated";
// Encrypt using encrypt_file to get proper format
let mut encrypted = Vec::new();
let mut reader = Cursor::new(plaintext.as_slice());
- let (_, header) =
- encrypt_file(&mut reader, &mut encrypted, Some(&key)).expect("encrypt_file failed");
+ let header = encrypt_file(&mut reader, &mut encrypted, &key).expect("encrypt_file failed");
// Truncate the ciphertext (remove the last few bytes which contain MAC/tag info)
let truncated_len = encrypted.len() - 5;
@@ -1714,11 +1289,11 @@ mod tests {
#[test]
fn test_decrypt_file_valid_single_chunk() {
// Verify that a valid single FINAL chunk works
- let key = generate_test_key();
+ let key = test_key();
let plaintext = b"Valid single chunk";
- let mut encryptor = StreamEncryptor::new(&key).expect("encryptor creation failed");
- let header = encryptor.header.clone();
+ let mut encryptor = Encryptor::new(&key);
+ let header = *encryptor.header();
let ciphertext = encryptor.push(plaintext, true).expect("push failed");
let mut reader = Cursor::new(&ciphertext);
@@ -1730,11 +1305,11 @@ mod tests {
#[test]
fn test_decrypt_file_rejects_trailing_data_after_exact_final_chunk() {
- let key = generate_test_key();
+ let key = test_key();
let plaintext = vec![0xA5; ENCRYPTION_CHUNK_SIZE];
- let mut encryptor = StreamEncryptor::new(&key).expect("encryptor creation failed");
- let header = encryptor.header.clone();
+ let mut encryptor = Encryptor::new(&key);
+ let header = *encryptor.header();
let mut ciphertext = encryptor.push(&plaintext, true).expect("push failed");
ciphertext.extend_from_slice(b"TRAILING");
@@ -1751,16 +1326,13 @@ mod tests {
#[test]
fn test_decrypt_file_via_encrypt_file_roundtrip() {
- // Verify that encrypt_file + decrypt_file work together properly
- // encrypt_file creates properly formatted chunks with FINAL tag
- let key = generate_test_key();
+ let key = test_key();
let plaintext: Vec<u8> = (0..5000).map(|i| (i % 256) as u8).collect();
// Encrypt using encrypt_file
let mut encrypted = Vec::new();
let mut reader = Cursor::new(&plaintext);
- let (_, header) =
- encrypt_file(&mut reader, &mut encrypted, Some(&key)).expect("encrypt_file failed");
+ let header = encrypt_file(&mut reader, &mut encrypted, &key).expect("encrypt_file failed");
// Decrypt using decrypt_file
let mut reader = Cursor::new(&encrypted);
@@ -1773,12 +1345,12 @@ mod tests {
#[test]
fn test_decrypt_file_data_truncation() {
// Test that decrypt_file_data also detects truncation (it calls decrypt_file)
- let key = generate_test_key();
+ let key = test_key();
let plaintext = b"Test decrypt_file_data truncation";
- let mut encryptor = StreamEncryptor::new(&key).expect("encryptor creation failed");
- let header = encryptor.header.clone();
- let encrypted_chunk = encryptor.push(plaintext, false).expect("push failed"); // is_final = false
+ let mut encryptor = Encryptor::new(&key);
+ let header = *encryptor.header();
+ let encrypted_chunk = encryptor.push(plaintext, false).expect("push failed");
let result = decrypt_file_data(&encrypted_chunk, &header, &key);
@@ -1791,11 +1363,11 @@ mod tests {
#[test]
fn test_decrypt_file_data_rejects_trailing_data_after_exact_final_chunk() {
- let key = generate_test_key();
+ let key = test_key();
let plaintext = vec![0x5A; ENCRYPTION_CHUNK_SIZE];
- let mut encryptor = StreamEncryptor::new(&key).expect("encryptor creation failed");
- let header = encryptor.header.clone();
+ let mut encryptor = Encryptor::new(&key);
+ let header = *encryptor.header();
let mut ciphertext = encryptor.push(&plaintext, true).expect("push failed");
ciphertext.extend_from_slice(b"TRAILING");
@@ -1808,48 +1380,13 @@ mod tests {
);
}
- #[test]
- fn test_decrypt_oneshot_requires_final_tag() {
- // Test that the one-shot decrypt() helper requires TAG_FINAL
- let key = generate_test_key();
- let plaintext = b"Test one-shot decrypt";
-
- let mut encryptor = StreamEncryptor::new(&key).expect("encryptor creation failed");
- let header = encryptor.header.clone();
-
- // Encrypt with MESSAGE tag (not FINAL)
- let ciphertext = encryptor.push(plaintext, false).expect("push failed");
-
- let result = decrypt(&ciphertext, &header, &key);
-
- assert!(
- matches!(result, Err(CryptoError::StreamTruncated)),
- "Expected StreamTruncated for non-FINAL tag in decrypt(), got {:?}",
- result
- );
- }
-
- #[test]
- fn test_decrypt_oneshot_valid_final_tag() {
- // Verify that decrypt() works with proper FINAL tag
- let key = generate_test_key();
- let plaintext = b"Test one-shot decrypt with FINAL";
-
- let mut encryptor = StreamEncryptor::new(&key).expect("encryptor creation failed");
- let header = encryptor.header.clone();
- let ciphertext = encryptor.push(plaintext, true).expect("push failed");
-
- let decrypted = decrypt(&ciphertext, &header, &key).expect("decrypt failed");
- assert_eq!(decrypted, plaintext);
- }
-
#[test]
fn test_streaming_decryptor_rejects_trailing_data_after_exact_final_chunk() {
- let key = generate_test_key();
+ let key = test_key();
let plaintext = vec![0x3C; ENCRYPTION_CHUNK_SIZE];
- let mut encryptor = StreamEncryptor::new(&key).expect("encryptor creation failed");
- let mut encrypted = encryptor.header.clone();
+ let mut encryptor = Encryptor::new(&key);
+ let mut encrypted = encryptor.header().as_bytes().to_vec();
let mut ciphertext = encryptor.push(&plaintext, true).expect("push failed");
ciphertext.extend_from_slice(b"TRAILING");
encrypted.extend_from_slice(&ciphertext);
@@ -1869,145 +1406,38 @@ mod tests {
// Size estimation consistency tests
#[test]
- fn test_encrypt_file_size_matches_estimate_empty() {
- // Empty file: encrypt_file output should match estimate_encrypted_size
- let key = generate_test_key();
- let plaintext: Vec<u8> = Vec::new();
-
- let mut encrypted = Vec::new();
- let mut reader = Cursor::new(&plaintext);
- encrypt_file(&mut reader, &mut encrypted, Some(&key)).expect("encrypt_file failed");
-
- let expected = estimate_encrypted_size(plaintext.len());
- assert_eq!(
- encrypted.len(),
- expected,
- "Empty file: encrypt_file output {} != estimate {}",
- encrypted.len(),
- expected
- );
- assert_eq!(encrypted.len(), ABYTES);
- }
-
- #[test]
- fn test_encrypt_file_size_matches_estimate_small() {
- // Small file (< chunk size): encrypt_file output should match estimate
- let key = generate_test_key();
- let plaintext: Vec<u8> = (0..1000).map(|i| (i % 256) as u8).collect();
-
- let mut encrypted = Vec::new();
- let mut reader = Cursor::new(&plaintext);
- encrypt_file(&mut reader, &mut encrypted, Some(&key)).expect("encrypt_file failed");
-
- let expected = estimate_encrypted_size(plaintext.len());
- assert_eq!(
- encrypted.len(),
- expected,
- "Small file: encrypt_file output {} != estimate {}",
- encrypted.len(),
- expected
- );
- assert_eq!(encrypted.len(), plaintext.len() + ABYTES);
- }
-
- #[test]
- fn test_encrypt_file_size_matches_estimate_exact_chunk() {
- // Exact chunk size: encrypt_file output should match estimate.
- // The last full chunk should be tagged FINAL.
- let key = generate_test_key();
- let plaintext: Vec<u8> = (0..ENCRYPTION_CHUNK_SIZE)
- .map(|i| (i % 256) as u8)
- .collect();
-
- let mut encrypted = Vec::new();
- let mut reader = Cursor::new(&plaintext);
- encrypt_file(&mut reader, &mut encrypted, Some(&key)).expect("encrypt_file failed");
-
- let expected = estimate_encrypted_size(plaintext.len());
- assert_eq!(
- encrypted.len(),
- expected,
- "Exact chunk: encrypt_file output {} != estimate {}",
- encrypted.len(),
- expected
- );
- assert_eq!(encrypted.len(), DECRYPTION_CHUNK_SIZE);
- }
-
- #[test]
- fn test_encrypt_file_size_matches_estimate_exact_two_chunks() {
- // Exact two chunks: encrypt_file output should match estimate
- let key = generate_test_key();
- let plaintext: Vec<u8> = (0..ENCRYPTION_CHUNK_SIZE * 2)
- .map(|i| (i % 256) as u8)
- .collect();
-
- let mut encrypted = Vec::new();
- let mut reader = Cursor::new(&plaintext);
- encrypt_file(&mut reader, &mut encrypted, Some(&key)).expect("encrypt_file failed");
-
- let expected = estimate_encrypted_size(plaintext.len());
- assert_eq!(
- encrypted.len(),
- expected,
- "Two chunks: encrypt_file output {} != estimate {}",
- encrypted.len(),
- expected
- );
- assert_eq!(encrypted.len(), 2 * DECRYPTION_CHUNK_SIZE);
- }
-
- #[test]
- fn test_encrypt_file_with_md5() {
- let key = generate_test_key();
- let plaintext = b"Encrypt with md5";
-
- let mut encrypted = Vec::new();
- let mut reader = Cursor::new(plaintext);
- let (returned_key, header, md5_bytes) =
- encrypt_file_with_md5(&mut reader, &mut encrypted, Some(&key))
- .expect("encrypt_file_with_md5 failed");
-
- assert_eq!(returned_key, key.to_vec());
- assert_eq!(header.len(), HEADER_BYTES);
-
- let mut hasher = Md5::new();
- hasher.update(&encrypted);
- let expected = hasher.finalize();
- assert_eq!(md5_bytes.as_slice(), expected.as_slice());
- }
+ fn test_encrypt_file_size_matches_estimate() {
+ let key = test_key();
+
+ for size in [
+ 0usize,
+ 1000,
+ ENCRYPTION_CHUNK_SIZE,
+ ENCRYPTION_CHUNK_SIZE * 2,
+ ] {
+ let plaintext: Vec<u8> = (0..size).map(|i| (i % 256) as u8).collect();
- #[test]
- fn test_streaming_encryptor_size_matches_estimate_exact_chunk() {
- // Verify StreamingEncryptor also matches estimate for exact chunk size
- let key = generate_test_key();
- let plaintext: Vec<u8> = (0..ENCRYPTION_CHUNK_SIZE)
- .map(|i| (i % 256) as u8)
- .collect();
+ let mut encrypted = Vec::new();
+ let mut reader = Cursor::new(&plaintext);
+ encrypt_file(&mut reader, &mut encrypted, &key).expect("encrypt_file failed");
- let mut encrypted = Vec::new();
- {
- let mut encryptor =
- StreamingEncryptor::new(&key, &mut encrypted).expect("encryptor creation failed");
- encryptor.write(&plaintext).expect("write failed");
- encryptor.finish().expect("finish failed");
+ let expected = estimate_encrypted_size(plaintext.len());
+ assert_eq!(
+ encrypted.len(),
+ expected,
+ "size={}: encrypt_file output {} != estimate {}",
+ size,
+ encrypted.len(),
+ expected
+ );
}
-
- // Remove header to compare ciphertext size
- let ciphertext_len = encrypted.len() - HEADER_BYTES;
- let expected = estimate_encrypted_size(plaintext.len());
- assert_eq!(
- ciphertext_len, expected,
- "StreamingEncryptor: ciphertext {} != estimate {}",
- ciphertext_len, expected
- );
}
#[test]
fn test_encrypt_file_and_streaming_encryptor_same_size() {
// Verify encrypt_file and StreamingEncryptor produce same ciphertext sizes
// for the edge case of exact chunk multiple
- let key = generate_test_key();
+ let key = test_key();
for multiplier in [0, 1, 2, 3] {
let extra = [0, 1, 100, ENCRYPTION_CHUNK_SIZE / 2];
@@ -2021,7 +1451,7 @@ mod tests {
// encrypt_file
let mut enc_file = Vec::new();
let mut reader = Cursor::new(&plaintext);
- encrypt_file(&mut reader, &mut enc_file, Some(&key)).expect("encrypt_file failed");
+ encrypt_file(&mut reader, &mut enc_file, &key).expect("encrypt_file failed");
// StreamingEncryptor
let mut enc_stream = Vec::new();
@@ -2056,14 +1486,14 @@ mod tests {
#[test]
fn test_validate_sizes_with_encrypt_file() {
// Verify validate_sizes works correctly with encrypt_file output
- let key = generate_test_key();
+ let key = test_key();
for size in [0, 100, ENCRYPTION_CHUNK_SIZE, ENCRYPTION_CHUNK_SIZE + 500] {
let plaintext: Vec<u8> = (0..size).map(|i| (i % 256) as u8).collect();
let mut encrypted = Vec::new();
let mut reader = Cursor::new(&plaintext);
- encrypt_file(&mut reader, &mut encrypted, Some(&key)).expect("encrypt_file failed");
+ encrypt_file(&mut reader, &mut encrypted, &key).expect("encrypt_file failed");
assert!(
validate_sizes(plaintext.len(), encrypted.len()),
diff --git a/rust/crates/core/src/io.rs b/rust/crates/core/src/io.rs
new file mode 100644
index 0000000000..4dddb14853
--- /dev/null
+++ b/rust/crates/core/src/io.rs
@@ -0,0 +1,70 @@
+//! I/O adapters used alongside the crypto routines.
+
+use std::io::{self, Write};
+
+use md5::{Digest, Md5};
+
+/// A write-through adapter that computes the MD5 digest of everything written.
+///
+/// Wrap the destination writer in this to obtain, in a single pass, the MD5 of
+/// a produced byte stream β€” e.g. the `Content-MD5` of encrypted file content
+/// required by object-store uploads:
+///
+/// ```rust
+/// use std::io::Cursor;
+/// use ente_core::crypto::{Key, stream};
+/// use ente_core::io::Md5Writer;
+///
+/// let key = Key::generate();
+/// let mut writer = Md5Writer::new(Vec::new());
+/// let header = stream::encrypt_file(&mut Cursor::new(b"data"), &mut writer, &key).unwrap();
+/// let (encrypted, md5) = writer.finalize();
+/// # let _ = (header, encrypted, md5);
+/// ```
+pub struct Md5Writer<W: Write> {
+ inner: W,
+ digest: Md5,
+}
+
+impl<W: Write> Md5Writer<W> {
+ /// Wrap a writer, computing the MD5 of all bytes written through it.
+ pub fn new(inner: W) -> Self {
+ Self {
+ inner,
+ digest: Md5::new(),
+ }
+ }
+
+ /// Unwrap the inner writer and return it along with the 16-byte digest.
+ pub fn finalize(self) -> (W, [u8; 16]) {
+ (self.inner, self.digest.finalize().into())
+ }
+}
+
+impl<W: Write> Write for Md5Writer<W> {
+ fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
+ let written = self.inner.write(buf)?;
+ self.digest.update(&buf[..written]);
+ Ok(written)
+ }
+
+ fn flush(&mut self) -> io::Result<()> {
+ self.inner.flush()
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn test_md5_writer_matches_direct_digest() {
+ let mut writer = Md5Writer::new(Vec::new());
+ writer.write_all(b"hello ").unwrap();
+ writer.write_all(b"world").unwrap();
+ let (written, md5) = writer.finalize();
+
+ assert_eq!(written, b"hello world");
+ assert_eq!(md5, <[u8; 16]>::from(Md5::digest(b"hello world")));
+ }
+}
diff --git a/rust/crates/core/src/lib.rs b/rust/crates/core/src/lib.rs
index f1ac7cac76..fd5e457c66 100644
--- a/rust/crates/core/src/lib.rs
+++ b/rust/crates/core/src/lib.rs
@@ -6,4 +6,5 @@
pub mod auth;
pub mod crypto;
pub mod http;
+pub mod io;
pub mod urls;