Skip to content

armgit / ente

Public Imported from GitHub
0

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

Improve secretbox crypto documentation

Manav Rathi3a02db633ad4
diff --git a/rust/crates/core/src/crypto/secretbox.rs b/rust/crates/core/src/crypto/secretbox.rs
index e5ffc26c52..6f9213a65d 100644
--- a/rust/crates/core/src/crypto/secretbox.rs
+++ b/rust/crates/core/src/crypto/secretbox.rs
@@ -1,16 +1,28 @@
-//! SecretBox (XSalsa20-Poly1305) authenticated encryption.
+//! Authenticated encryption with XSalsa20-Poly1305.
//!
-//! This module provides authenticated encryption using XSalsa20-Poly1305,
-//! byte-for-byte compatible with libsodium's `crypto_secretbox_easy`.
+//! SecretBox encrypts and authenticates a single, self-contained value under a
+//! 256-bit key. It suits small, independent pieces of data such as a wrapped
+//! key or a short field. For data attached to an Ente object (file or
+//! collection metadata and the like) prefer [`blob`](super::blob), and for file
+//! contents, which are encrypted in chunks, use [`stream`](super::stream).
//!
-//! Two payload shapes are supported:
+//! The name comes from libsodium, which exposes this same construction as
+//! `crypto_secretbox`; the implementation here is pure Rust but wire-compatible
+//! (recorded per function below).
+//!
+//! Every message takes a 192-bit nonce. The nonce is not secret, but it must
+//! never be reused with the same key (see [`encrypt_with_nonce`]). The
+//! [`encrypt`] and [`encrypt_combined`] functions generate a fresh random nonce
+//! for you, which is the safe default.
+//!
+//! Two payload shapes are offered, differing only in how the nonce travels:
//!
//! - Split ([`encrypt`] / [`decrypt`]): the ciphertext (`MAC β€– ct`) and the
-//! nonce travel separately. This matches the server's wire format, where
-//! encrypted fields are stored alongside their nonces.
+//! nonce are returned separately.
//!
-//! - Combined ([`encrypt_combined`] / [`decrypt_combined`]): a single
-//! self-contained buffer (`nonce β€– MAC β€– ct`).
+//! - Combined ([`encrypt_combined`] / [`decrypt_combined`]): the nonce is
+//! prepended to the ciphertext to form one self-contained buffer
+//! (`nonce β€– MAC β€– ct`).
use xsalsa20poly1305::XSalsa20Poly1305;
use xsalsa20poly1305::aead::generic_array::GenericArray;
@@ -18,28 +30,47 @@ use xsalsa20poly1305::aead::{Aead, KeyInit};
use crate::crypto::{CryptoError, Key, Nonce, Result};
-/// Size of the authentication tag in bytes.
+/// Size in bytes of the Poly1305 authentication tag that prefixes every
+/// ciphertext.
+///
+/// Same as libsodium's `crypto_secretbox_MACBYTES`.
pub const MAC_BYTES: usize = 16;
-/// The result of SecretBox encryption: ciphertext and nonce, separate.
+/// A secretbox ciphertext together with the nonce needed to open it, as
+/// returned by [`encrypt`].
+///
+/// This is the split shape, with the nonce held separately from the ciphertext;
+/// see the module docs for the combined alternative.
#[derive(Debug, Clone, PartialEq)]
pub struct EncryptedBox {
- /// The encrypted data: `MAC (16 bytes) β€– ciphertext`.
+ /// The Poly1305 tag followed by the ciphertext: `MAC (16 bytes) β€– ciphertext`.
pub encrypted_data: Vec<u8>,
- /// The nonce used during encryption. Required for decryption; not secret.
+ /// The nonce that encrypted [`encrypted_data`](Self::encrypted_data). Needed
+ /// to decrypt, and not secret, but never reused with the same key.
pub nonce: Nonce,
}
impl EncryptedBox {
- /// Decrypt this box.
+ /// Decrypt this box with `key`, returning the plaintext.
+ ///
+ /// A convenience wrapper over [`decrypt`] using the stored ciphertext and
+ /// nonce; see it for the error cases.
pub fn decrypt(&self, key: &Key) -> Result<Vec<u8>> {
decrypt(&self.encrypted_data, &self.nonce, key)
}
}
-/// Encrypt the given data with a randomly generated nonce.
+/// Encrypt `data` under `key`, generating a fresh random nonce.
+///
+/// This is the default choice for secretbox encryption: a new nonce is
+/// generated on every call, so a (key, nonce) pair cannot be reused by mistake.
+/// The plaintext is not padded, so the ciphertext length reveals the exact
+/// plaintext length.
///
-/// Use [`decrypt`] or [`EncryptedBox::decrypt`] to decrypt the result.
+/// Returns the ciphertext and the generated nonce; decrypt with [`decrypt`] or
+/// [`EncryptedBox::decrypt`].
+///
+/// Wire-compatible with libsodium's `crypto_secretbox_easy`.
pub fn encrypt(data: &[u8], key: &Key) -> EncryptedBox {
let nonce = Nonce::generate();
let encrypted_data = encrypt_with_nonce(data, &nonce, key);
@@ -49,10 +80,21 @@ pub fn encrypt(data: &[u8], key: &Key) -> EncryptedBox {
}
}
-/// Encrypt the given data with the provided nonce.
+/// Encrypt `data` under `key` with a caller-supplied `nonce`.
+///
+/// Prefer [`encrypt`], which generates the nonce for you. Reach for this only
+/// when the nonce is fixed by something else, for example re-creating a
+/// ciphertext that must match bytes produced earlier.
+///
+/// # Security
+///
+/// The nonce must be unique for every message encrypted under a given key.
+/// Reusing a (key, nonce) pair is catastrophic: it reveals the XOR of the two
+/// plaintexts and makes the Poly1305 tag forgeable, breaking both
+/// confidentiality and authenticity. The nonce itself need not be secret.
///
-/// Returns `MAC (16 bytes) β€– ciphertext` (libsodium `crypto_secretbox_easy`
-/// format).
+/// Returns `MAC (16 bytes) β€– ciphertext`, wire-compatible with libsodium's
+/// `crypto_secretbox_easy`.
pub fn encrypt_with_nonce(data: &[u8], nonce: &Nonce, key: &Key) -> Vec<u8> {
let cipher = XSalsa20Poly1305::new(GenericArray::from_slice(key.as_bytes()));
let nonce_ga = GenericArray::from_slice(nonce.as_bytes());
@@ -64,9 +106,21 @@ pub fn encrypt_with_nonce(data: &[u8], nonce: &Nonce, key: &Key) -> Vec<u8> {
.expect("XSalsa20-Poly1305 encryption cannot fail for in-memory plaintexts")
}
-/// Decrypt data encrypted with [`encrypt`] or [`encrypt_with_nonce`].
+/// Decrypt a ciphertext produced by [`encrypt`] or [`encrypt_with_nonce`].
///
-/// `data` is `MAC (16 bytes) β€– ciphertext`.
+/// Pass the same `nonce` and `key` that encrypted it. `data` is
+/// `MAC (16 bytes) β€– ciphertext`. The Poly1305 tag is verified before any
+/// plaintext is returned, so a successful result is also proof that the
+/// ciphertext was not altered.
+///
+/// # Errors
+///
+/// Returns [`CiphertextTooShort`](CryptoError::CiphertextTooShort) if `data` is
+/// smaller than the tag, or [`DecryptionFailed`](CryptoError::DecryptionFailed)
+/// if the tag does not verify, which is the case whenever the key, nonce, or
+/// ciphertext is wrong or the data was tampered with.
+///
+/// Wire-compatible with libsodium's `crypto_secretbox_open_easy`.
pub fn decrypt(data: &[u8], nonce: &Nonce, key: &Key) -> Result<Vec<u8>> {
if data.len() < MAC_BYTES {
return Err(CryptoError::CiphertextTooShort {
@@ -83,11 +137,17 @@ pub fn decrypt(data: &[u8], nonce: &Nonce, key: &Key) -> Result<Vec<u8>> {
.map_err(|_| CryptoError::DecryptionFailed)
}
-/// Encrypt the given data into a single self-contained buffer.
+/// Encrypt `data` under `key` into one self-contained buffer.
+///
+/// Like [`encrypt`], but prepends a fresh random nonce to the ciphertext,
+/// returning `nonce (24 bytes) β€– MAC (16 bytes) β€– 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 nonce. Decrypt
+/// with [`decrypt_combined`].
///
-/// Returns `nonce (24 bytes) β€– MAC (16 bytes) β€– ciphertext`. Everything needed
-/// for decryption except the key is in the returned buffer; use
-/// [`decrypt_combined`] to decrypt it.
+/// The `MAC β€– ciphertext` body is wire-compatible with libsodium's
+/// `crypto_secretbox_easy`; prepending the nonce is an Ente convention, not part
+/// of libsodium itself.
pub fn encrypt_combined(data: &[u8], key: &Key) -> Vec<u8> {
let nonce = Nonce::generate();
let encrypted = encrypt_with_nonce(data, &nonce, key);
@@ -98,8 +158,18 @@ pub fn encrypt_combined(data: &[u8], key: &Key) -> Vec<u8> {
combined
}
-/// Decrypt a combined `nonce β€– MAC β€– ciphertext` buffer produced by
-/// [`encrypt_combined`].
+/// Decrypt a combined buffer produced by [`encrypt_combined`].
+///
+/// Splits the leading nonce from the `MAC β€– ciphertext` body, then verifies the
+/// tag and decrypts as [`decrypt`] does.
+///
+/// # Errors
+///
+/// Returns [`CiphertextTooShort`](CryptoError::CiphertextTooShort) if `data` is
+/// too short to hold a nonce and tag, otherwise the same errors as [`decrypt`].
+///
+/// The body is wire-compatible with libsodium's `crypto_secretbox_open_easy`;
+/// the leading nonce is an Ente convention.
pub fn decrypt_combined(data: &[u8], key: &Key) -> Result<Vec<u8>> {
if data.len() < Nonce::BYTES + MAC_BYTES {
return Err(CryptoError::CiphertextTooShort {