Skip to content

armgit / ente

Public Imported from GitHub
0

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

Improve crypto module documentation

Manav Rathi24c80b985e6e
diff --git a/rust/crates/core/src/crypto/argon.rs b/rust/crates/core/src/crypto/argon.rs
index f8f1b2bc60..ebede29033 100644
--- a/rust/crates/core/src/crypto/argon.rs
+++ b/rust/crates/core/src/crypto/argon.rs
@@ -1,6 +1,13 @@
-//! Argon2id password hashing and key derivation.
+//! Deriving keys from passwords with Argon2id.
//!
-//! This module provides password-based key derivation using Argon2id.
+//! Argon2id stretches a low-entropy, human-chosen password into a key, spending
+//! tunable memory and time to make brute-force guessing expensive. Use it to
+//! turn a passphrase into a key; to derive subkeys from a key that is already
+//! high-entropy, use [`kdf`](super::kdf) instead.
+//!
+//! The same password, salt, and [`Params`] always produce the same key, so the
+//! salt and parameters must be stored alongside the data for other clients to
+//! reproduce it (see [`DerivedKey`]).
use std::fmt;
@@ -8,11 +15,12 @@ use argon2::{Algorithm, Argon2, Params as Argon2Params, Version};
use crate::crypto::{CryptoError, Key, Result, Salt};
-/// Argon2id cost parameters.
+/// Argon2id cost parameters: how much memory to use and how many passes to make.
///
-/// Memory is in bytes (must be a multiple of 1024); ops is the iteration
-/// count. Use the presets unless re-deriving with parameters previously
-/// stored alongside the data (e.g. the server's key attributes).
+/// Higher values cost an attacker more but also slow legitimate derivation. Use
+/// the presets ([`INTERACTIVE`](Self::INTERACTIVE), [`MODERATE`](Self::MODERATE),
+/// [`SENSITIVE`](Self::SENSITIVE)) unless re-deriving a key with parameters that
+/// were stored alongside it, such as the server's key attributes.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Params {
/// Memory limit in bytes.
@@ -22,7 +30,7 @@ pub struct Params {
}
impl Params {
- /// Parameters for interactive use (64 MiB, 2 ops) β€” fast, for UI
+ /// Parameters for interactive use (64 MiB, 2 ops): fast, for UI
/// responsiveness.
pub const INTERACTIVE: Self = Self {
mem_limit: 67_108_864,
@@ -47,9 +55,9 @@ impl Params {
/// The cheapest parameters Argon2 accepts (8 KiB, 1 op).
///
- /// These provide essentially no brute-force protection. ONLY for inputs
- /// that are already high-entropy keys β€” where the KDF is a formality β€”
- /// never for human-chosen passwords.
+ /// These provide essentially no brute-force protection, and are only for
+ /// inputs that are already high-entropy keys (where the KDF is a
+ /// formality), never for human-chosen passwords.
pub const MIN: Self = Self {
mem_limit: 8_192,
ops_limit: 1,
@@ -84,15 +92,21 @@ impl fmt::Debug for DerivedKey {
}
}
-/// Derive a key from a password using Argon2id.
+/// Derive a key from `password` and `salt` with the given Argon2id `params`.
+///
+/// Deterministic: the same inputs always yield the same key, which is how other
+/// clients reproduce it. The result is a [`Key`], zeroized on drop. To make a
+/// new key, the `derive_*_key` helpers choose parameters and a salt for you.
+///
+/// # Errors
///
-/// # Arguments
-/// * `password` - Password string (UTF-8).
-/// * `salt` - Salt to use for derivation.
-/// * `params` - Argon2 cost parameters.
+/// Returns
+/// [`InvalidKeyDerivationParams`](CryptoError::InvalidKeyDerivationParams) if
+/// `params` fall below the accepted minimum or memory is not a multiple of 1024
+/// bytes.
///
-/// # Returns
-/// 32-byte derived key, zeroized on drop.
+/// Wire-compatible with libsodium's `crypto_pwhash` using
+/// `crypto_pwhash_ALG_ARGON2ID13`.
pub fn derive_key(password: &str, salt: &Salt, params: Params) -> Result<Key> {
derive_key_impl(password.as_bytes(), salt, params)
}
@@ -139,7 +153,11 @@ fn derive_key_impl(password: &[u8], salt: &Salt, params: Params) -> Result<Key>
Ok(Key::from_bytes(key))
}
-/// Derive a key with interactive parameters and a newly generated salt.
+/// Derive a key from `password` with [`Params::INTERACTIVE`] and a freshly
+/// generated salt.
+///
+/// Returns the key together with the salt and parameters used, which must be
+/// stored to reproduce it.
pub fn derive_interactive_key(password: &str) -> Result<DerivedKey> {
let salt = Salt::generate();
let key = derive_key(password, &salt, Params::INTERACTIVE)?;
@@ -150,7 +168,11 @@ pub fn derive_interactive_key(password: &str) -> Result<DerivedKey> {
})
}
-/// Derive a key with moderate parameters and a newly generated salt.
+/// Derive a key from `password` with [`Params::MODERATE`] and a freshly
+/// generated salt.
+///
+/// Returns the key together with the salt and parameters used, which must be
+/// stored to reproduce it.
pub fn derive_moderate_key(password: &str) -> Result<DerivedKey> {
let salt = Salt::generate();
let key = derive_key(password, &salt, Params::MODERATE)?;
@@ -161,15 +183,18 @@ pub fn derive_moderate_key(password: &str) -> Result<DerivedKey> {
})
}
-/// Derive a key with the adaptive sensitive client policy and a newly
-/// generated salt.
+/// Derive a high-security key from `password`, adapting the cost to the device.
+///
+/// Aims for [`Params::SENSITIVE`] strength but starts at moderate memory
+/// (256 MiB) with the ops limit scaled up to compensate, then halves memory and
+/// doubles ops whenever allocation fails, down to a 128 MiB floor (the
+/// server-side minimum for accepted account key attributes). Holding the
+/// product of memory and ops constant preserves the work factor while fitting
+/// low-memory devices, and matches the policy used by the web and Flutter
+/// clients so the same account derives consistently everywhere.
///
-/// Starts at moderate memory (256 MiB) with the ops limit scaled up to
-/// preserve [`Params::SENSITIVE`] strength (mem Γ— ops), then halves memory and
-/// doubles ops on allocation failure, down to a 128 MiB floor (the server-side
-/// minimum for accepted account key attributes). This mirrors the established
-/// adaptive policy used by the existing web and Flutter clients so that newly
-/// generated key attributes remain consistent across platforms.
+/// Returns the key together with the salt and parameters actually used, which
+/// must be stored to reproduce it.
pub fn derive_sensitive_key(password: &str) -> Result<DerivedKey> {
let salt = Salt::generate();
derive_sensitive_adaptive(password.as_bytes(), &salt)
diff --git a/rust/crates/core/src/crypto/blob.rs b/rust/crates/core/src/crypto/blob.rs
index dda26270e2..220485b9b2 100644
--- a/rust/crates/core/src/crypto/blob.rs
+++ b/rust/crates/core/src/crypto/blob.rs
@@ -1,16 +1,26 @@
-//! Blob encryption (XChaCha20-Poly1305 SecretStream without chunking).
+//! Authenticated encryption of a single value with XChaCha20-Poly1305.
//!
-//! This module provides encryption using SecretStream for small-ish data
-//! that doesn't need to be chunked. Use this for encrypting metadata
-//! associated with Ente objects.
+//! A blob is one secretstream message: the data is encrypted and authenticated
+//! in a single shot, without the chunking that [`stream`](super::stream) applies
+//! to large file contents. Use it for the small, bounded values attached to an
+//! Ente object, such as file or collection metadata.
+//! ([`secretbox`](super::secretbox) fills the same single-value role for data
+//! not tied to an object.)
//!
-//! Two payload shapes are supported, mirroring [`super::secretbox`]:
+//! The construction is libsodium's secretstream
+//! (`crypto_secretstream_xchacha20poly1305`), driven here for a single message
+//! tagged final; the implementation is pure Rust but wire-compatible (recorded
+//! per function below). Unlike a secretbox nonce, the per-message randomness
+//! lives in a `header` that secretstream generates during encryption.
+//!
+//! Two payload shapes are offered, differing only in how the header travels:
//!
//! - Split ([`encrypt`] / [`decrypt`]): the ciphertext and the decryption
-//! header travel separately, matching the server's wire format.
+//! header are returned separately.
//!
-//! - Combined ([`encrypt_combined`] / [`decrypt_combined`]): a single
-//! self-contained `header β€– ciphertext` buffer.
+//! - Combined ([`encrypt_combined`] / [`decrypt_combined`]): the header is
+//! prepended to the ciphertext to form one self-contained buffer
+//! (`header β€– ciphertext`).
use super::stream::{Decryptor, Encryptor};
use crate::crypto::{CryptoError, Header, Key, Result};
@@ -24,27 +34,40 @@ pub const HEADER_BYTES: usize = Header::BYTES;
/// Overhead (tag + MAC) added to the plaintext by encryption.
pub use super::stream::ABYTES;
-/// The result of blob encryption: ciphertext and decryption header, separate.
+/// A blob ciphertext together with the header needed to open it, as returned by
+/// [`encrypt`].
+///
+/// This is the split shape, with the header held separately from the
+/// ciphertext; see the module docs for the combined alternative.
#[derive(Debug, Clone)]
pub struct EncryptedBlob {
- /// The encrypted data: a single secretstream message (plaintext length +
- /// [`ABYTES`] bytes).
+ /// The encrypted data: one secretstream message, [`ABYTES`] bytes longer
+ /// than the plaintext.
pub encrypted_data: Vec<u8>,
- /// The decryption header. Required for decryption; not secret.
+ /// The header that secretstream produced while encrypting. Needed to
+ /// decrypt, and not secret.
pub decryption_header: Header,
}
impl EncryptedBlob {
- /// Decrypt this blob.
+ /// Decrypt this blob with `key`, returning the plaintext.
+ ///
+ /// A convenience wrapper over [`decrypt`] using the stored ciphertext and
+ /// header; see it for the error cases.
pub fn decrypt(&self, key: &Key) -> Result<Vec<u8>> {
decrypt(&self.encrypted_data, &self.decryption_header, key)
}
}
-/// Encrypt the given data as a single secretstream message.
+/// Encrypt `data` under `key` as a single secretstream message.
///
-/// This is suitable for encrypting metadata and small files. Use [`decrypt`]
-/// or [`EncryptedBlob::decrypt`] to decrypt the result.
+/// A fresh header is generated for every call. The message is tagged final, so
+/// [`decrypt`] can later confirm the ciphertext is complete. Returns the
+/// ciphertext and that header; decrypt with [`decrypt`] or
+/// [`EncryptedBlob::decrypt`].
+///
+/// Wire-compatible with libsodium's secretstream, as one message tagged
+/// `TAG_FINAL` (`crypto_secretstream_xchacha20poly1305`).
pub fn encrypt(data: &[u8], key: &Key) -> Result<EncryptedBlob> {
let mut encryptor = Encryptor::new(key);
let decryption_header = *encryptor.header();
@@ -56,11 +79,23 @@ pub fn encrypt(data: &[u8], key: &Key) -> Result<EncryptedBlob> {
})
}
-/// Decrypt data encrypted with [`encrypt`].
+/// Decrypt a blob produced by [`encrypt`], using its `header` and `key`.
+///
+/// The message must carry the secretstream final tag, which proves it was not
+/// truncated; its Poly1305 MAC proves it was not otherwise altered. Data
+/// written by older clients without the final tag is rejected here; use
+/// [`decrypt_legacy`] for it.
///
-/// The data must carry the secretstream final tag; truncated or non-final
-/// payloads are rejected with `CryptoError::StreamTruncated`. For older data
-/// written without the final tag, use [`decrypt_legacy`].
+/// # Errors
+///
+/// Returns [`CiphertextTooShort`](CryptoError::CiphertextTooShort) if `data` is
+/// smaller than the per-message overhead,
+/// [`StreamTruncated`](CryptoError::StreamTruncated) if the final tag is absent,
+/// or [`StreamPullFailed`](CryptoError::StreamPullFailed) if the MAC does not
+/// verify, which happens when the key or header is wrong or the data was
+/// tampered with.
+///
+/// Wire-compatible with libsodium's `crypto_secretstream_xchacha20poly1305`.
pub fn decrypt(data: &[u8], header: &Header, key: &Key) -> Result<Vec<u8>> {
let (plaintext, is_final) = decrypt_impl(data, header, key)?;
if !is_final {
@@ -89,7 +124,15 @@ fn decrypt_impl(data: &[u8], header: &Header, key: &Key) -> Result<(Vec<u8>, boo
decryptor.pull(data)
}
-/// Encrypt data and return a single combined `header β€– ciphertext` payload.
+/// Encrypt `data` under `key` into one self-contained buffer.
+///
+/// Like [`encrypt`], but prepends the decryption header to the ciphertext,
+/// returning `header β€– ciphertext`: everything needed to decrypt except the
+/// key. Prefer this when a single opaque blob is easier to store or pass around
+/// than a separate ciphertext and header. Decrypt with [`decrypt_combined`].
+///
+/// Wire-compatible with libsodium's secretstream, storing the header ahead of
+/// the single message.
pub fn encrypt_combined(data: &[u8], key: &Key) -> Result<Vec<u8>> {
let encrypted = encrypt(data, key)?;
let mut combined = Vec::with_capacity(Header::BYTES + encrypted.encrypted_data.len());
@@ -98,7 +141,16 @@ pub fn encrypt_combined(data: &[u8], key: &Key) -> Result<Vec<u8>> {
Ok(combined)
}
-/// Decrypt a combined `header β€– ciphertext` payload.
+/// Decrypt a combined buffer produced by [`encrypt_combined`].
+///
+/// Splits the leading header from the ciphertext, then decrypts as [`decrypt`]
+/// does.
+///
+/// # Errors
+///
+/// Returns [`CiphertextTooShort`](CryptoError::CiphertextTooShort) if `data` is
+/// too short to hold a header and one message, otherwise the same errors as
+/// [`decrypt`].
pub fn decrypt_combined(data: &[u8], key: &Key) -> Result<Vec<u8>> {
if data.len() < Header::BYTES + ABYTES {
return Err(CryptoError::CiphertextTooShort {
@@ -111,28 +163,37 @@ pub fn decrypt_combined(data: &[u8], key: &Key) -> Result<Vec<u8>> {
decrypt(ciphertext, &Header::try_from_slice(header)?, key)
}
-/// Encrypt a JSON value.
+/// Serialize `value` to JSON and encrypt it as a blob.
+///
+/// The inverse is [`decrypt_json`].
pub fn encrypt_json<T: serde::Serialize>(value: &T, key: &Key) -> Result<EncryptedBlob> {
let json = serde_json::to_vec(value)
.map_err(|e| CryptoError::Json(format!("JSON serialization failed: {}", e)))?;
encrypt(&json, key)
}
-/// Encrypt a JSON value and return a combined `header β€– ciphertext` payload.
+/// Serialize `value` to JSON and encrypt it into one combined buffer.
+///
+/// Like [`encrypt_json`] but using [`encrypt_combined`]; the inverse is
+/// [`decrypt_json_combined`].
pub fn encrypt_json_combined<T: serde::Serialize>(value: &T, key: &Key) -> Result<Vec<u8>> {
let json = serde_json::to_vec(value)
.map_err(|e| CryptoError::Json(format!("JSON serialization failed: {}", e)))?;
encrypt_combined(&json, key)
}
-/// Decrypt an [`EncryptedBlob`] into a JSON value.
+/// Decrypt a blob and deserialize its plaintext from JSON into `T`.
+///
+/// The inverse of [`encrypt_json`].
pub fn decrypt_json<T: serde::de::DeserializeOwned>(blob: &EncryptedBlob, key: &Key) -> Result<T> {
let plaintext = blob.decrypt(key)?;
serde_json::from_slice(&plaintext)
.map_err(|e| CryptoError::Json(format!("JSON deserialization failed: {}", e)))
}
-/// Decrypt a combined `header β€– ciphertext` payload into a JSON value.
+/// Decrypt a combined buffer and deserialize its plaintext from JSON into `T`.
+///
+/// The inverse of [`encrypt_json_combined`].
pub fn decrypt_json_combined<T: serde::de::DeserializeOwned>(
combined: &[u8],
key: &Key,
@@ -277,7 +338,7 @@ mod tests {
)
.unwrap();
- // Decrypt into a mismatched type β€” should be CryptoError::Json
+ // Decrypt into a mismatched type; should be CryptoError::Json
let result: std::result::Result<Different, _> = decrypt_json(&encrypted, &key);
assert!(
matches!(result, Err(CryptoError::Json(_))),
diff --git a/rust/crates/core/src/crypto/encoding.rs b/rust/crates/core/src/crypto/encoding.rs
index 1e5e159dba..274f499c0e 100644
--- a/rust/crates/core/src/crypto/encoding.rs
+++ b/rust/crates/core/src/crypto/encoding.rs
@@ -1,4 +1,9 @@
-//! Base64 and hex encoding helpers.
+//! Base64 and hex encoding and decoding.
+//!
+//! Conversions between bytes and their textual forms: standard and URL-safe
+//! base64, hexadecimal, and base64 to hex. These move key material and
+//! ciphertext across text boundaries such as JSON and URLs; they are plumbing,
+//! not themselves cryptographic.
use base64::{
Engine,
@@ -9,27 +14,20 @@ use base64::{
use crate::crypto::Result;
-/// Decode a base64 string to bytes.
+/// Decode a standard base64 string to bytes, the inverse of [`encode_b64`].
///
-/// # Arguments
-/// * `input` - Base64 encoded string.
+/// # Errors
///
-/// # Returns
-/// The decoded bytes.
+/// Returns [`Base64Decode`](crate::crypto::CryptoError::Base64Decode) if
+/// `input` is not valid standard base64.
pub fn decode_b64(input: &str) -> Result<Vec<u8>> {
Ok(BASE64.decode(input)?)
}
-/// Encode bytes to a base64 string.
+/// Encode bytes to a standard base64 string, the inverse of [`decode_b64`].
///
-/// This is standard base64 (RFC 4648 Β§4), matching libsodium's
+/// Standard base64 (RFC 4648 Β§4), matching libsodium's
/// `sodium_base64_VARIANT_ORIGINAL`.
-///
-/// # Arguments
-/// * `input` - Bytes to encode.
-///
-/// # Returns
-/// Base64 encoded string.
pub fn encode_b64(input: &[u8]) -> String {
BASE64.encode(input)
}
@@ -57,63 +55,55 @@ pub fn encode_b64_url_safe_no_padding(input: &[u8]) -> String {
BASE64_URL_SAFE_NO_PAD.encode(input)
}
-/// Decode an unpadded URL-safe base64 string to bytes.
+/// Decode an unpadded URL-safe base64 string to bytes, the inverse of
+/// [`encode_b64_url_safe_no_padding`].
+///
+/// # Errors
+///
+/// Returns [`Base64Decode`](crate::crypto::CryptoError::Base64Decode) if
+/// `input` is not valid unpadded URL-safe base64.
pub fn decode_b64_url_safe_no_padding(input: &str) -> Result<Vec<u8>> {
Ok(BASE64_URL_SAFE_NO_PAD.decode(input)?)
}
-/// Convert a UTF-8 string to bytes.
-///
-/// # Arguments
-/// * `input` - UTF-8 string.
-///
-/// # Returns
-/// UTF-8 bytes.
+/// Return the UTF-8 bytes of `input`.
pub fn str_to_bin(input: &str) -> Vec<u8> {
input.as_bytes().to_vec()
}
-/// Decode a hex string to bytes.
+/// Decode a hex string to bytes, the inverse of [`encode_hex`].
///
-/// # Arguments
-/// * `input` - Hex encoded string.
+/// # Errors
///
-/// # Returns
-/// The decoded bytes.
+/// Returns [`HexDecode`](crate::crypto::CryptoError::HexDecode) if `input` is
+/// not valid hexadecimal.
pub fn decode_hex(input: &str) -> Result<Vec<u8>> {
Ok(hex::decode(input)?)
}
-/// Encode bytes to a hex string.
-///
-/// # Arguments
-/// * `input` - Bytes to encode.
-///
-/// # Returns
-/// Hex encoded string (lowercase).
+/// Encode bytes to a lowercase hex string, the inverse of [`decode_hex`].
pub fn encode_hex(input: &[u8]) -> String {
hex::encode(input)
}
-/// Convert a base64 string to hex.
+/// Re-encode a standard base64 string as lowercase hex, the inverse of
+/// [`hex_to_b64`].
///
-/// # Arguments
-/// * `b64` - Base64 encoded string.
+/// # Errors
///
-/// # Returns
-/// Hex encoded string.
+/// Returns [`Base64Decode`](crate::crypto::CryptoError::Base64Decode) if `b64`
+/// is not valid standard base64.
pub fn b64_to_hex(b64: &str) -> Result<String> {
let bytes = decode_b64(b64)?;
Ok(encode_hex(&bytes))
}
-/// Convert a hex string to base64.
+/// Re-encode a hex string as standard base64, the inverse of [`b64_to_hex`].
///
-/// # Arguments
-/// * `hex_str` - Hex encoded string.
+/// # Errors
///
-/// # Returns
-/// Base64 encoded string.
+/// Returns [`HexDecode`](crate::crypto::CryptoError::HexDecode) if `hex_str` is
+/// not valid hexadecimal.
pub fn hex_to_b64(hex_str: &str) -> Result<String> {
let bytes = decode_hex(hex_str)?;
Ok(encode_b64(&bytes))
diff --git a/rust/crates/core/src/crypto/error.rs b/rust/crates/core/src/crypto/error.rs
index 939ea356ee..af66782644 100644
--- a/rust/crates/core/src/crypto/error.rs
+++ b/rust/crates/core/src/crypto/error.rs
@@ -1,8 +1,12 @@
-//! Crypto error types.
+//! The error type shared by the crypto module.
use thiserror::Error;
-/// Errors that can occur during cryptographic operations.
+/// An error from a cryptographic operation.
+///
+/// Each variant is returned by the operations documented to produce it.
+/// [`code`](Self::code) maps a variant to a stable string identifier that
+/// bindings forward to non-Rust callers.
#[derive(Error, Debug)]
pub enum CryptoError {
/// Base64 decoding failed.
diff --git a/rust/crates/core/src/crypto/hash.rs b/rust/crates/core/src/crypto/hash.rs
index 260dd9f4ae..187e7faaec 100644
--- a/rust/crates/core/src/crypto/hash.rs
+++ b/rust/crates/core/src/crypto/hash.rs
@@ -1,6 +1,12 @@
-//! BLAKE2b hashing functions.
+//! Cryptographic hashing with BLAKE2b.
//!
-//! This module provides BLAKE2b hashing with support for keyed hashing.
+//! BLAKE2b maps data of any length to a fixed-size digest (16 to 64 bytes, 32
+//! by default). Supplying a key turns it into a MAC. Hashing is available
+//! one-shot ([`hash`]), incrementally for data that arrives in pieces
+//! ([`HashState`]), or straight from a reader ([`hash_reader`]).
+//!
+//! The construction is libsodium's `crypto_generichash`; the implementation
+//! here wraps the pure-Rust `blake2b_simd` crate and is wire-compatible.
use blake2b_simd::{Params as Blake2bParams, State as Blake2bState};
use std::io::Read;
@@ -25,15 +31,18 @@ pub const KEY_BYTES_MIN: usize = 16;
/// Maximum key length in bytes for keyed hashing.
pub const KEY_BYTES_MAX: usize = 64;
-/// Compute BLAKE2b hash of data.
+/// Hash `data` with BLAKE2b.
+///
+/// `out_len` chooses the digest length (16 to 64 bytes), defaulting to 32.
+/// Passing a `key` of 16 to 64 bytes computes a keyed hash, that is a MAC;
+/// `None` or an empty key hashes without one.
///
-/// # Arguments
-/// * `data` - Data to hash.
-/// * `out_len` - Optional output length (16-64 bytes). Defaults to 32.
-/// * `key` - Optional key for keyed hashing (0 or 16-64 bytes).
+/// # Errors
///
-/// # Returns
-/// Hash output of the specified length.
+/// Returns [`InvalidKeyLength`](CryptoError::InvalidKeyLength) if `out_len` is
+/// outside 16 to 64 bytes, or if a non-empty `key` is outside that range.
+///
+/// Wire-compatible with libsodium's `crypto_generichash`.
pub fn hash(data: &[u8], out_len: Option<usize>, key: Option<&[u8]>) -> Result<Vec<u8>> {
let out_len = out_len.unwrap_or(HASH_BYTES);
@@ -64,35 +73,33 @@ pub fn hash(data: &[u8], out_len: Option<usize>, key: Option<&[u8]>) -> Result<V
Ok(hash.as_bytes()[..out_len].to_vec())
}
-/// Compute BLAKE2b hash with default parameters (32-byte output, no key).
-///
-/// # Arguments
-/// * `data` - Data to hash.
+/// Hash `data` with BLAKE2b using the defaults: a 32-byte digest and no key.
///
-/// # Returns
-/// 32-byte hash output.
+/// Shorthand for [`hash`] with `out_len` 32 and no key.
pub fn hash_default(data: &[u8]) -> Result<Vec<u8>> {
hash(data, Some(HASH_BYTES), None)
}
-/// Streaming hash state for incremental hashing.
+/// Incremental BLAKE2b hasher, for data that arrives in pieces.
///
-/// This allows hashing large files or data streams without loading
-/// everything into memory.
+/// Build it with [`new`](Self::new), feed chunks with [`update`](Self::update),
+/// and produce the digest with [`finalize`](Self::finalize). The result is
+/// identical to passing the concatenation of the chunks to [`hash`], so a large
+/// input can be hashed without holding it all in memory.
pub struct HashState {
state: Blake2bState,
out_len: usize,
}
impl HashState {
- /// Create a new hash state.
+ /// Create a hasher with the given digest length and optional key.
///
- /// # Arguments
- /// * `out_len` - Optional output length (16-64 bytes). Defaults to 32.
- /// * `key` - Optional key for keyed hashing (0 or 16-64 bytes).
+ /// `out_len` and `key` follow the same rules and defaults as [`hash`].
///
- /// # Returns
- /// A new hash state ready for incremental updates.
+ /// # Errors
+ ///
+ /// Returns [`InvalidKeyLength`](CryptoError::InvalidKeyLength) if `out_len`
+ /// or a non-empty `key` is outside 16 to 64 bytes.
pub fn new(out_len: Option<usize>, key: Option<&[u8]>) -> Result<Self> {
let out_len = out_len.unwrap_or(HASH_BYTES);
@@ -124,40 +131,34 @@ impl HashState {
Ok(HashState { state, out_len })
}
- /// Update the hash state with more data.
- ///
- /// # Arguments
- /// * `data` - Data to add to the hash.
+ /// Feed more data into the hash.
pub fn update(&mut self, data: &[u8]) -> Result<()> {
self.state.update(data);
Ok(())
}
- /// Finalize the hash and return the result.
- ///
- /// # Returns
- /// Hash output of the configured length.
+ /// Consume the hasher and return the digest, of the configured length.
pub fn finalize(self) -> Result<Vec<u8>> {
let hash = self.state.finalize();
Ok(hash.as_bytes()[..self.out_len].to_vec())
}
}
-/// Create a new hash state with default parameters (32-byte output, no key).
+/// Create an incremental [`HashState`] with the defaults: a 32-byte digest and
+/// no key.
pub fn hash_state_new() -> Result<HashState> {
HashState::new(Some(HASH_BYTES), None)
}
-/// Hash data from a reader.
+/// Hash everything from `reader` with BLAKE2b.
///
-/// This allows hashing streams without loading everything into memory.
+/// Reads to EOF, hashing as it goes, so the source is never fully held in
+/// memory. `out_len` is the digest length (16 to 64 bytes, default 32).
///
-/// # Arguments
-/// * `reader` - Source to read data from.
-/// * `out_len` - Optional output length (16-64 bytes). Defaults to 32.
+/// # Errors
///
-/// # Returns
-/// Hash output of the specified length.
+/// Returns [`InvalidKeyLength`](CryptoError::InvalidKeyLength) if `out_len` is
+/// out of range, or an [`Io`](CryptoError::Io) error if the reader fails.
pub fn hash_reader<R: Read>(reader: &mut R, out_len: Option<usize>) -> Result<Vec<u8>> {
let mut state = HashState::new(out_len, None)?;
let mut buffer = vec![0u8; 4096];
diff --git a/rust/crates/core/src/crypto/kdf.rs b/rust/crates/core/src/crypto/kdf.rs
index bc30ab7808..d24427d9a7 100644
--- a/rust/crates/core/src/crypto/kdf.rs
+++ b/rust/crates/core/src/crypto/kdf.rs
@@ -1,7 +1,15 @@
-//! Key derivation functions using BLAKE2b.
+//! Deriving independent subkeys from a high-entropy key, with BLAKE2b.
//!
-//! This module provides key derivation using BLAKE2b with salt and personalization.
-//! Maintains compatibility with libsodium's crypto_kdf_derive_from_key.
+//! Given one high-entropy key, this produces subkeys such that knowing a
+//! derived subkey reveals nothing about the parent key or its sibling subkeys.
+//! Each subkey is selected by a numeric id and an 8-byte context, so a single
+//! parent key can safely key many separate purposes.
+//!
+//! Unlike [`argon`](super::argon), the input must already be high-entropy (a
+//! key, not a password): this is fast keyed hashing, not password stretching.
+//!
+//! The construction is libsodium's `crypto_kdf_derive_from_key`; the
+//! implementation here is pure Rust but wire-compatible.
use blake2b_simd::Params as Blake2bParams;
@@ -28,20 +36,27 @@ pub const LOGIN_SUBKEY_ID: u64 = 1;
/// Login subkey context (used by derive_login_key).
pub const LOGIN_SUBKEY_CONTEXT: &[u8; CONTEXT_BYTES] = b"loginctx";
-/// Derive a subkey from a master key.
+/// Derive a `subkey_len`-byte subkey of `key`, selected by `subkey_id` and
+/// `context`.
+///
+/// `subkey_id` and `context` together name the subkey: the same `key` yields
+/// independent subkeys for different ids or contexts, so `context` acts as a
+/// domain separator (conventionally a short, fixed application label).
+/// `subkey_len` must be between 16 and 64 bytes. The result is a [`SecretVec`],
+/// zeroized on drop.
+///
+/// # Wire format
///
-/// # Wire Format
-/// - salt = subkey_id (8 bytes LE) || zeros (8 bytes)
-/// - personal = context (up to 8 bytes, zero-padded) || zeros (8 bytes)
+/// BLAKE2b keyed with `key`, salt `subkey_id` (8 bytes little-endian followed
+/// by 8 zero bytes), personalization `context` (8 bytes followed by 8 zero
+/// bytes).
///
-/// # Arguments
-/// * `key` - Master key.
-/// * `subkey_len` - Length of the derived subkey (16-64 bytes).
-/// * `subkey_id` - Subkey identifier (used as salt).
-/// * `context` - Context for domain separation (exactly 8 bytes).
+/// # Errors
///
-/// # Returns
-/// Derived subkey of the specified length, zeroized on drop.
+/// Returns [`InvalidKeyLength`](crate::crypto::CryptoError::InvalidKeyLength) if
+/// `subkey_len` is outside 16 to 64 bytes.
+///
+/// Wire-compatible with libsodium's `crypto_kdf_derive_from_key`.
pub fn derive_subkey(
key: &Key,
subkey_len: usize,
@@ -74,16 +89,12 @@ pub fn derive_subkey(
Ok(SecretVec::new(hash.as_bytes()[..subkey_len].to_vec()))
}
-/// Derive a login key from a master key.
-///
-/// This is a specialized wrapper around `derive_subkey` used for SRP authentication.
-/// Returns the first 16 bytes of a 32-byte subkey derived with context "loginctx" and ID 1.
-///
-/// # Arguments
-/// * `master_key` - Master key to derive from (must be exactly 32 bytes).
+/// Derive the SRP login key from the user's master key.
///
-/// # Returns
-/// 16-byte login key, zeroized on drop.
+/// A fixed specialization of [`derive_subkey`]: the first 16 bytes of the
+/// 32-byte subkey with id 1 and context `loginctx`. The login key is what the
+/// client proves knowledge of during SRP authentication, which keeps the master
+/// key itself off the wire. The result is a [`SecretVec`], zeroized on drop.
pub fn derive_login_key(master_key: &Key) -> SecretVec {
let subkey = derive_subkey(
master_key,
diff --git a/rust/crates/core/src/crypto/mod.rs b/rust/crates/core/src/crypto/mod.rs
index 7e0b8ccb14..5190bdab52 100644
--- a/rust/crates/core/src/crypto/mod.rs
+++ b/rust/crates/core/src/crypto/mod.rs
@@ -4,9 +4,11 @@
//!
//! # Implementation
//!
-//! This crate uses **pure Rust** cryptographic implementations from the RustCrypto project.
-//! All implementations maintain byte-for-byte wire format compatibility with libsodium
-//! for interoperability with existing clients (mobile/web).
+//! Every primitive is implemented in pure Rust, with no libsodium or other C
+//! dependency, drawing on established crates such as those from the RustCrypto
+//! project, `blake2b_simd`, and `crypto_secretstream`. All of them keep
+//! byte-for-byte wire compatibility with libsodium, so keys and ciphertext
+//! interoperate with the existing mobile and web clients.
//!
//! # Overview
//!
diff --git a/rust/crates/core/src/crypto/sealed.rs b/rust/crates/core/src/crypto/sealed.rs
index 823b7c556e..973ed2aabc 100644
--- a/rust/crates/core/src/crypto/sealed.rs
+++ b/rust/crates/core/src/crypto/sealed.rs
@@ -1,18 +1,22 @@
-//! Sealed box (anonymous public-key encryption).
+//! Anonymous public-key encryption (sealed boxes).
//!
-//! Sealed boxes provide encryption to a recipient's public key without revealing
-//! the sender's identity. This is achieved using an ephemeral key pair.
+//! A sealed box lets anyone encrypt a message to a recipient's public key so
+//! that only the holder of the matching secret key can read it, while the
+//! recipient learns nothing about who sent it. Each message uses a fresh
+//! ephemeral key pair whose public half is included in the output; the
+//! ephemeral secret is discarded, so even the sender cannot decrypt afterwards.
//!
-//! # Wire Format (libsodium crypto_box_seal)
+//! The construction is libsodium's `crypto_box_seal`; the implementation here
+//! is pure Rust but wire-compatible (recorded per function below).
//!
-//! Output: ephemeral_pk (32 bytes) || MAC (16 bytes) || ciphertext
+//! # Wire format
//!
-//! - Nonce: BLAKE2b-24(ephemeral_pk || recipient_pk)
-//! - Shared secret: X25519(ephemeral_sk, recipient_pk)
-//! - Key: HSalsa20(shared_secret, zero_nonce)
-//! - Encryption: XSalsa20-Poly1305 (MAC || ciphertext format)
+//! `ephemeral_pk (32 bytes) β€– MAC (16 bytes) β€– ciphertext`, where:
//!
-//! Note: Format is verified against libsodium in the validation suite.
+//! - the nonce is `BLAKE2b-24(ephemeral_pk β€– recipient_pk)`,
+//! - the shared secret is `X25519(ephemeral_sk, recipient_pk)`,
+//! - the symmetric key is `HSalsa20(shared_secret, zero_nonce)`, and
+//! - the body is the `MAC β€– ciphertext` of XSalsa20-Poly1305.
use blake2b_simd::Params as Blake2bParams;
use rand_core::{OsRng, RngCore};
@@ -74,17 +78,21 @@ fn is_contributory(shared_secret: &[u8; 32]) -> bool {
shared_secret.ct_ne(&[0u8; 32]).into()
}
-/// Seal (encrypt) plaintext for a recipient's public key.
+/// Encrypt `plaintext` so that only the holder of `recipient_pk`'s secret key
+/// can read it.
///
-/// Creates an ephemeral key pair and encrypts the message such that only
-/// the recipient can decrypt it, without revealing the sender's identity.
+/// A fresh ephemeral key pair is generated per call and its secret discarded,
+/// so the output carries no sender identity and the sender cannot decrypt it
+/// afterwards. Open it with [`open`].
///
-/// # Arguments
-/// * `plaintext` - Data to encrypt.
-/// * `recipient_pk` - Recipient's 32-byte public key.
+/// # Errors
///
-/// # Returns
-/// ephemeral_pk || MAC || ciphertext (libsodium crypto_box_seal format)
+/// Returns [`InvalidPublicKey`](CryptoError::InvalidPublicKey) if `recipient_pk`
+/// is a low-order point, which would make the X25519 exchange yield an all-zero
+/// shared secret and provide no security.
+///
+/// Returns `ephemeral_pk β€– MAC β€– ciphertext`, wire-compatible with libsodium's
+/// `crypto_box_seal`.
pub fn seal(plaintext: &[u8], recipient_pk: &PublicKey) -> Result<Vec<u8>> {
let recipient_pk_arr: [u8; 32] = *recipient_pk.as_bytes();
let recipient_pk_point = x25519_dalek::PublicKey::from(recipient_pk_arr);
@@ -132,15 +140,21 @@ pub fn seal(plaintext: &[u8], recipient_pk: &PublicKey) -> Result<Vec<u8>> {
Ok(result)
}
-/// Open (decrypt) a sealed box.
+/// Decrypt a sealed box addressed to `recipient_pk` / `recipient_sk`.
+///
+/// `ciphertext` is the `ephemeral_pk β€– MAC β€– ciphertext` produced by [`seal`].
+/// Both halves of the recipient key pair are needed: the secret key performs
+/// the X25519 exchange, and the public key reconstructs the nonce.
+///
+/// # Errors
///
-/// # Arguments
-/// * `ciphertext` - Sealed data (ephemeral_pk || MAC || ciphertext).
-/// * `recipient_pk` - Recipient's 32-byte public key.
-/// * `recipient_sk` - Recipient's 32-byte secret key.
+/// Returns [`CiphertextTooShort`](CryptoError::CiphertextTooShort) if
+/// `ciphertext` is smaller than [`SEAL_OVERHEAD`],
+/// [`InvalidPublicKey`](CryptoError::InvalidPublicKey) if the embedded ephemeral
+/// key is low-order, or [`DecryptionFailed`](CryptoError::DecryptionFailed) if
+/// the MAC does not verify, which happens with the wrong key pair or tampering.
///
-/// # Returns
-/// Decrypted plaintext.
+/// Wire-compatible with libsodium's `crypto_box_seal_open`.
pub fn open(
ciphertext: &[u8],
recipient_pk: &PublicKey,
diff --git a/rust/crates/core/src/crypto/secret.rs b/rust/crates/core/src/crypto/secret.rs
index a9289fb9d3..3b9aec4115 100644
--- a/rust/crates/core/src/crypto/secret.rs
+++ b/rust/crates/core/src/crypto/secret.rs
@@ -153,7 +153,7 @@ mod tests {
#[test]
fn test_secret_vec_zeroize_clears_buffer() {
// Verify that calling zeroize() (which Drop invokes) zeroes the
- // buffer while we still own the memory β€” no UB from reading freed
+ // buffer while we still own the memory; no UB from reading freed
// allocations.
let mut secret = SecretVec::new(vec![0xABu8; 64]);
assert!(secret.iter().any(|&b| b != 0), "precondition: non-zero");
@@ -175,7 +175,7 @@ mod tests {
#[test]
fn test_secret_vec_into_vec_leaves_empty_inner() {
// After into_vec(), the SecretVec's inner buffer is empty, so
- // Drop won't zeroize the extracted data β€” that's the caller's
+ // Drop won't zeroize the extracted data; that's the caller's
// responsibility now.
let secret = SecretVec::new(vec![0xEFu8; 16]);
let vec = secret.into_vec();
diff --git a/rust/crates/core/src/crypto/stream.rs b/rust/crates/core/src/crypto/stream.rs
index df9890cfda..e4d6c910d8 100644
--- a/rust/crates/core/src/crypto/stream.rs
+++ b/rust/crates/core/src/crypto/stream.rs
@@ -1,14 +1,26 @@
-//! XChaCha20-Poly1305 secretstream implementation.
+//! Chunked authenticated encryption with XChaCha20-Poly1305.
//!
-//! 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`].
+//! This is the encryption used for file contents: the plaintext is split into
+//! fixed-size chunks ([`ENCRYPTION_CHUNK_SIZE`]) and each chunk is encrypted as
+//! one secretstream message, so an arbitrarily large file can be processed
+//! without holding it all in memory. For a single bounded value that fits in
+//! memory, use [`blob`](super::blob) instead.
//!
-//! # Wire Format
-//! - Header: 24 bytes
-//! - Each message: plaintext length + [`ABYTES`] bytes (an encrypted tag
-//! byte, the ciphertext, and a trailing 16-byte MAC)
+//! The chunks are chained, so a decryptor detects any truncation, reordering,
+//! or modification. The last chunk is tagged final, and reaching that tag is
+//! what proves the stream is complete rather than cut short (see
+//! [`Decryptor::finish`]).
+//!
+//! The construction is libsodium's secretstream
+//! (`crypto_secretstream_xchacha20poly1305`); the implementation here wraps the
+//! pure-Rust `crypto_secretstream` crate and is wire-compatible.
+//!
+//! # Wire format
+//!
+//! A 24-byte header (produced when encryption starts, stored or sent
+//! separately), followed by one secretstream message per chunk. Each message is
+//! [`ABYTES`] bytes longer than its plaintext: a one-byte encrypted tag, the
+//! ciphertext, and a 16-byte Poly1305 MAC.
use crypto_secretstream::{
Header as UpstreamHeader, Key as UpstreamKey, PullStream, PushStream, Stream, Tag,
@@ -29,8 +41,8 @@ pub const HEADER_BYTES: usize = Header::BYTES;
/// Size of the encryption key in bytes.
pub const KEY_BYTES: usize = Key::BYTES;
-/// Overhead (MAC + tag) added to each message (from upstream
-/// crypto_secretstream).
+/// Per-message overhead secretstream adds to the plaintext: a one-byte
+/// encrypted tag and a 16-byte Poly1305 MAC.
pub const ABYTES: usize = Stream::ABYTES;
/// Plaintext chunk size for streaming file encryption (4 MB).
@@ -43,17 +55,19 @@ fn upstream_key(key: &Key) -> UpstreamKey {
UpstreamKey::from(*key.as_bytes())
}
-/// Stateful chunk-by-chunk encryptor.
+/// Stateful chunk-by-chunk stream encryptor.
///
-/// Encrypt each chunk with [`push`](Self::push), marking the last one with
-/// `is_final`. The [`header`](Self::header) must be preserved for decryption.
+/// Feed the plaintext one chunk at a time to [`push`](Self::push), marking the
+/// last chunk with `is_final`. The [`header`](Self::header) must be kept and
+/// handed to the [`Decryptor`]. This is the low-level building block; for
+/// reader/writer plumbing see [`encrypt_file`] and [`StreamingEncryptor`].
pub struct Encryptor {
stream: PushStream,
header: Header,
}
impl Encryptor {
- /// Create a new encryptor with a random header.
+ /// Create an encryptor under `key`, generating a fresh random header.
pub fn new(key: &Key) -> Self {
let (header, stream) = PushStream::init(OsRng, &upstream_key(key));
Self {
@@ -85,19 +99,21 @@ impl Encryptor {
}
}
-/// Stateful chunk-by-chunk decryptor.
+/// Stateful chunk-by-chunk stream 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.
+/// Decrypt each chunk with [`pull`](Self::pull), in the order they were
+/// produced. After the last chunk, call [`finish`](Self::finish): it fails if
+/// the final tag was never seen, which is how truncation at a chunk boundary is
+/// caught. This is the low-level building block; for reader/writer plumbing see
+/// [`decrypt_file`] and [`StreamingDecryptor`].
pub struct Decryptor {
stream: PullStream,
seen_final: bool,
}
impl Decryptor {
- /// Create a new decryptor from the header that was produced during
- /// encryption.
+ /// Create a decryptor from the `header` produced during encryption and the
+ /// same `key`.
pub fn new(header: &Header, key: &Key) -> Self {
let header = UpstreamHeader::from(*header.as_bytes());
let stream = PullStream::init(header, &upstream_key(key));
@@ -107,9 +123,16 @@ impl Decryptor {
}
}
- /// Decrypt a chunk.
+ /// Decrypt the next chunk, returning its plaintext and whether it was the
+ /// final chunk.
+ ///
+ /// Chunks must be pulled in the order they were pushed; a wrong key or
+ /// header, or out-of-order, modified, or reordered chunks, all fail the MAC.
+ ///
+ /// # Errors
///
- /// Returns the plaintext and whether this was the final chunk.
+ /// Returns [`StreamPullFailed`](CryptoError::StreamPullFailed) if the chunk
+ /// is shorter than the per-message overhead or its MAC does not verify.
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)?;
@@ -136,10 +159,16 @@ impl Decryptor {
Ok(is_final)
}
- /// Verify that the stream was complete.
+ /// Confirm the stream was complete, consuming the decryptor.
///
- /// Returns `CryptoError::StreamTruncated` if no final-tagged chunk was
- /// pulled, which means the ciphertext was truncated at a chunk boundary.
+ /// Call this after the last [`pull`](Self::pull). Without it, a stream cut
+ /// short exactly at a chunk boundary is indistinguishable from a complete
+ /// one, since each chunk on its own is valid.
+ ///
+ /// # Errors
+ ///
+ /// Returns [`StreamTruncated`](CryptoError::StreamTruncated) if no
+ /// final-tagged chunk was ever pulled.
pub fn finish(self) -> Result<()> {
if self.seen_final {
Ok(())
@@ -149,14 +178,12 @@ impl Decryptor {
}
}
-/// 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
-/// emitted.
+/// Predict the ciphertext size, excluding the header, for encrypting
+/// `plaintext_len` bytes.
///
-/// If the calculation overflows `usize`, this returns `usize::MAX`.
+/// The plaintext is split into [`ENCRYPTION_CHUNK_SIZE`] chunks, each gaining
+/// [`ABYTES`] of overhead; an empty plaintext still emits one empty final
+/// chunk. Saturates to `usize::MAX` rather than overflowing.
#[inline]
pub fn estimate_encrypted_size(plaintext_len: usize) -> usize {
if plaintext_len == 0 {
@@ -185,13 +212,12 @@ pub fn estimate_encrypted_size(plaintext_len: usize) -> usize {
}
}
-/// Validate that plaintext and ciphertext sizes match chunked secretstream
-/// encryption.
+/// Check that `ciphertext_len` is what encrypting `plaintext_len` bytes would
+/// produce.
///
-/// 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.
+/// Returns `true` when `ciphertext_len` equals [`estimate_encrypted_size`] for
+/// the given plaintext. This compares sizes only and excludes the header; it is
+/// a cheap sanity check, not an integrity check (decryption provides that).
#[inline]
pub fn validate_sizes(plaintext_len: usize, ciphertext_len: usize) -> bool {
let estimated = estimate_encrypted_size(plaintext_len);
@@ -201,10 +227,16 @@ pub fn validate_sizes(plaintext_len: usize, ciphertext_len: usize) -> bool {
estimated == ciphertext_len
}
-/// Streaming file encryptor that writes encrypted chunks to a writer.
+/// Encrypt a stream of writes to an underlying writer, chunk by chunk.
+///
+/// Feed plaintext with [`write`](Self::write) and end with
+/// [`finish`](Self::finish); the header is written to the writer up front. Use
+/// this when plaintext arrives incrementally. When you already have a reader,
+/// [`encrypt_file`] is simpler.
///
-/// 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.
+/// It holds back the last full chunk so that chunk can be tagged final, which
+/// avoids emitting an extra empty final chunk when the plaintext is an exact
+/// multiple of [`ENCRYPTION_CHUNK_SIZE`].
pub struct StreamingEncryptor<W: Write> {
encryptor: Encryptor,
writer: W,
@@ -216,9 +248,8 @@ pub struct StreamingEncryptor<W: Write> {
}
impl<W: Write> StreamingEncryptor<W> {
- /// Create a new streaming encryptor.
- ///
- /// The decryption header is written to the writer before any ciphertext.
+ /// Create a streaming encryptor under `key`, writing the decryption header
+ /// to `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())?;
@@ -251,7 +282,10 @@ impl<W: Write> StreamingEncryptor<W> {
Ok(())
}
- /// Write plaintext data to the stream.
+ /// Buffer and encrypt plaintext, writing completed chunks to the writer.
+ ///
+ /// Bytes accumulate until a full chunk is available; call
+ /// [`finish`](Self::finish) to flush the remainder as the final chunk.
pub fn write(&mut self, data: &[u8]) -> Result<()> {
let mut input_pos = 0;
@@ -283,7 +317,7 @@ impl<W: Write> StreamingEncryptor<W> {
Ok(())
}
- /// Finish encryption, writing the final chunk.
+ /// Flush the buffered remainder as the final chunk and return the writer.
pub fn finish(mut self) -> Result<W> {
if !self.pending.is_empty() {
if !self.buffer.is_empty() {
@@ -300,15 +334,16 @@ impl<W: Write> StreamingEncryptor<W> {
}
}
-/// Streaming file decryptor that reads encrypted chunks from a reader.
+/// Decrypt a stream from an underlying reader, chunk by chunk.
///
-/// Uses a single-buffer strategy to minimize memory copies:
-/// - Ciphertext is read directly into the buffer
-/// - Decryption happens in-place (buffer shrinks by ABYTES)
-/// - Plaintext is served via indices into the same buffer
+/// Read plaintext with [`read`](Self::read) or
+/// [`read_to_end`](Self::read_to_end); the header is read from the reader
+/// first. Like [`decrypt_file`] it detects truncation: reaching EOF without the
+/// final tag is an error, as is trailing data after it. Use this when you want
+/// to consume plaintext incrementally.
///
-/// This eliminates the extra copies that would occur with separate
-/// read/decrypt/output buffers.
+/// Decryption happens in place in a single reused buffer, avoiding the copies
+/// that separate read, decrypt, and output buffers would incur.
pub struct StreamingDecryptor<R: Read> {
decryptor: Decryptor,
reader: R,
@@ -336,9 +371,8 @@ fn ensure_reader_exhausted<R: Read>(reader: &mut R) -> Result<()> {
}
impl<R: Read> StreamingDecryptor<R> {
- /// Create a new streaming decryptor.
- ///
- /// The decryption header is read from the reader before any ciphertext.
+ /// Create a streaming decryptor under `key`, reading the decryption header
+ /// from `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)?;
@@ -353,8 +387,16 @@ impl<R: Read> StreamingDecryptor<R> {
})
}
- /// Read and decrypt data into the provided buffer.
- /// Returns the number of bytes read, or 0 if EOF.
+ /// Decrypt into `buf`, returning the number of bytes written, or 0 at the
+ /// end of the stream.
+ ///
+ /// # Errors
+ ///
+ /// Returns [`StreamTruncated`](CryptoError::StreamTruncated) if the stream
+ /// ends before the final tag,
+ /// [`StreamTrailingData`](CryptoError::StreamTrailingData) if bytes follow
+ /// the final chunk, or [`StreamPullFailed`](CryptoError::StreamPullFailed)
+ /// if a chunk fails to decrypt.
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
@@ -434,7 +476,9 @@ impl<R: Read> StreamingDecryptor<R> {
Ok(to_copy)
}
- /// Read all remaining data into a Vec.
+ /// Decrypt the entire remaining stream into a new `Vec`.
+ ///
+ /// Convenience over repeated [`read`](Self::read); the same errors apply.
pub fn read_to_end(&mut self) -> Result<Vec<u8>> {
let mut result = Vec::new();
let mut buf = [0u8; 8192];
@@ -450,24 +494,17 @@ impl<R: Read> StreamingDecryptor<R> {
}
}
-/// Encrypt a file from a reader to a writer.
+/// Encrypt everything from `reader` to `writer`, returning the decryption
+/// header.
///
-/// 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).
+/// The header is not written to the writer; it travels separately (for
+/// instance, in the file's server-side metadata). The ciphertext is the chunk
+/// stream described at the module level, byte-for-byte the same as a
+/// [`StreamingEncryptor`] produces; predict its size with
+/// [`estimate_encrypted_size`].
///
-/// # 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.
+/// Reuses buffers and encrypts in place, so memory stays bounded to about twice
+/// the chunk size regardless of file size.
pub fn encrypt_file<R: Read, W: Write>(
reader: &mut R,
writer: &mut W,
@@ -535,20 +572,19 @@ pub fn encrypt_file<R: Read, W: Write>(
Ok(header)
}
-/// Decrypt a file from a reader to a writer.
+/// Decrypt the chunk stream in `reader` to `writer`, using `header` and `key`.
///
-/// 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.
+/// `reader` holds the ciphertext only; the header travels separately. Like
+/// [`encrypt_file`] it reuses buffers and decrypts in place, so memory stays
+/// bounded to about twice the chunk size.
///
/// # Errors
-/// 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.
+///
+/// Returns [`StreamTruncated`](CryptoError::StreamTruncated) if EOF is reached
+/// without the final tag (the truncation check), or
+/// [`StreamTrailingData`](CryptoError::StreamTrailingData) if bytes remain after
+/// the final chunk. A chunk that fails to decrypt yields
+/// [`StreamPullFailed`](CryptoError::StreamPullFailed).
pub fn decrypt_file<R: Read, W: Write>(
reader: &mut R,
writer: &mut W,
@@ -592,10 +628,10 @@ pub fn decrypt_file<R: Read, W: Write>(
}
}
-/// Decrypt file data that's already in memory.
+/// Decrypt an in-memory chunk stream, using `header` and `key`.
///
-/// This is a convenience function for when you have the entire encrypted file
-/// in a buffer. The header and key must be provided separately.
+/// Convenience over [`decrypt_file`] for when the whole ciphertext is already
+/// in a buffer; the same truncation and trailing-data checks apply.
pub fn decrypt_file_data(encrypted_data: &[u8], header: &Header, key: &Key) -> Result<Vec<u8>> {
use std::io::Cursor;
diff --git a/rust/crates/core/src/crypto/types.rs b/rust/crates/core/src/crypto/types.rs
index a5cbe86424..ec10724459 100644
--- a/rust/crates/core/src/crypto/types.rs
+++ b/rust/crates/core/src/crypto/types.rs
@@ -1,8 +1,8 @@
//! Typed key material and related fixed-size values.
//!
//! These newtypes carry their size in the type, so length validation happens
-//! once β€” at the boundary where raw bytes enter ([`Key::try_from_slice`] and
-//! friends) β€” instead of inside every operation. Secret types zeroize on drop
+//! once, at the boundary where raw bytes enter ([`Key::try_from_slice`] and
+//! friends), rather than inside every operation. Secret types zeroize on drop
//! and redact their `Debug` output; non-secret types (`Nonce`, `Salt`,
//! [`Header`]) are plain `Copy` values.