π End-to-end encrypted cloud for everything.
Dart 2faandroidauthye2eeencryptionend-to-end-encryptionfluttergolanggoogle-photosgoogle-photos-alternativeiosopensourcephotosprivacyprivacy-toolstypescriptzero-knowledge
Add typed key vocabulary and secretbox surface to wasm-core
Manav Rathid43dcd04cc5f
diff --git a/rust/bindings/wasm/core/src/crypto.rs b/rust/bindings/wasm/core/src/crypto.rsindex 2ea820bebf..66c738e995 100644--- a/rust/bindings/wasm/core/src/crypto.rs+++ b/rust/bindings/wasm/core/src/crypto.rs@@ -48,8 +48,8 @@ impl EncryptedBox {}}-#[wasm_bindgen(js_name = encryptBox)]-pub fn encrypt_box(data: &[u8], key: &[u8]) -> Result<EncryptedBox, CryptoError> {+#[wasm_bindgen(js_name = secretboxEncrypt)]+pub fn secretbox_encrypt(data: &[u8], key: &[u8]) -> Result<EncryptedBox, CryptoError> {let out = core_crypto::secretbox::encrypt(data, &core_crypto::Key::try_from_slice(key)?);Ok(EncryptedBox {encrypted_data: out.encrypted_data,@@ -57,11 +57,40 @@ pub fn encrypt_box(data: &[u8], key: &[u8]) -> Result<EncryptedBox, CryptoError>})}-#[wasm_bindgen(js_name = decryptBox)]-pub fn decrypt_box(data: &[u8], nonce: &[u8], key: &[u8]) -> Result<Vec<u8>, CryptoError> {+#[wasm_bindgen(js_name = secretboxEncryptWithNonce)]+pub fn secretbox_encrypt_with_nonce(+ data: &[u8],+ nonce: &[u8],+ key: &[u8],+) -> Result<Vec<u8>, CryptoError> {+ Ok(core_crypto::secretbox::encrypt_with_nonce(+ data,+ &core_crypto::Nonce::try_from_slice(nonce)?,+ &core_crypto::Key::try_from_slice(key)?,+ ))+}++#[wasm_bindgen(js_name = secretboxDecrypt)]+pub fn secretbox_decrypt(data: &[u8], nonce: &[u8], key: &[u8]) -> Result<Vec<u8>, CryptoError> {Ok(core_crypto::secretbox::decrypt(data,&core_crypto::Nonce::try_from_slice(nonce)?,&core_crypto::Key::try_from_slice(key)?,)?)}++#[wasm_bindgen(js_name = secretboxEncryptCombined)]+pub fn secretbox_encrypt_combined(data: &[u8], key: &[u8]) -> Result<Vec<u8>, CryptoError> {+ Ok(core_crypto::secretbox::encrypt_combined(+ data,+ &core_crypto::Key::try_from_slice(key)?,+ ))+}++#[wasm_bindgen(js_name = secretboxDecryptCombined)]+pub fn secretbox_decrypt_combined(data: &[u8], key: &[u8]) -> Result<Vec<u8>, CryptoError> {+ Ok(core_crypto::secretbox::decrypt_combined(+ data,+ &core_crypto::Key::try_from_slice(key)?,+ )?)+}diff --git a/web/packages/wasm-core/index.ts b/web/packages/wasm-core/index.tsindex 0cdd0d3412..1d784d052d 100644--- a/web/packages/wasm-core/index.ts+++ b/web/packages/wasm-core/index.ts@@ -1,62 +1,9 @@/**- * @file Cryptographic operations for Ente web apps.+ * @file Cryptographic primitives for Ente.** Each function loads the WebAssembly backend on first use (so all are async)* and runs on the calling thread; run heavy operations from a Web Worker to* keep the UI responsive.*/-import { loadWasmCore } from "./load";--/**- * The result of {@link encryptBox}: the secretbox ciphertext and the randomly- * generated nonce needed to decrypt it.- */-export interface EncryptedBox {- /** The encrypted data, a libsodium secretbox (`MAC β ciphertext`). */- encryptedData: Uint8Array;- /**- * The nonce generated during encryption. Required for decryption; not- * secret.- */- nonce: Uint8Array;-}--/**- * Encrypt `data` with `key` using XSalsa20-Poly1305 authenticated encryption- * (libsodium's secretbox), generating a random nonce.- *- * Use {@link decryptBox} to decrypt the result.- *- * @param data The bytes to encrypt.- * @param key A 32-byte secretbox key.- * @returns The ciphertext and the generated nonce.- */-export const encryptBox = async (- data: Uint8Array,- key: Uint8Array,-): Promise<EncryptedBox> => {- const wasm = await loadWasmCore();- const box = wasm.encryptBox(data, key);- try {- return { encryptedData: box.encryptedData, nonce: box.nonce };- } finally {- box.free();- }-};--/**- * Decrypt data encrypted with {@link encryptBox}.- *- * @param data The secretbox ciphertext (`MAC β ciphertext`).- * @param nonce The nonce produced during encryption.- * @param key The 32-byte secretbox key used to encrypt.- * @returns The decrypted bytes.- */-export const decryptBox = async (- data: Uint8Array,- nonce: Uint8Array,- key: Uint8Array,-): Promise<Uint8Array> => {- const wasm = await loadWasmCore();- return wasm.decryptBox(data, nonce, key);-};+export * from "./secretbox";+export * from "./types";diff --git a/web/packages/wasm-core/secretbox.ts b/web/packages/wasm-core/secretbox.tsnew file mode 100644index 0000000000..0caa0b6ab5--- /dev/null+++ b/web/packages/wasm-core/secretbox.ts@@ -0,0 +1,166 @@+/**+ * @file Authenticated encryption with XSalsa20-Poly1305.+ *+ * 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. Ente uses blob for data attached to an object (file or+ * collection metadata and the like), and stream for file contents, which are+ * encrypted in chunks.+ *+ * 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 {@link secretboxEncryptWithNonce}). The+ * {@link secretboxEncrypt} and {@link secretboxEncryptCombined} 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 ({@link secretboxEncrypt} / {@link secretboxDecrypt}): the ciphertext+ * (`MAC β ct`) and the nonce are returned separately.+ *+ * - Combined ({@link secretboxEncryptCombined} / {@link+ * secretboxDecryptCombined}): the nonce is prepended to the ciphertext to form+ * one self-contained buffer (`nonce β MAC β ct`).+ */+import { loadWasmCore } from "./load";+import { Key, Nonce } from "./types";++/**+ * A secretbox ciphertext together with the nonce needed to open it, as returned+ * by {@link secretboxEncrypt}.+ *+ * This is the split shape, with the nonce held separately from the ciphertext;+ * {@link secretboxEncryptCombined} produces the combined alternative.+ */+export interface EncryptedBox {+ /**+ * The Poly1305 tag followed by the ciphertext:+ * `MAC (16 bytes) β ciphertext`.+ */+ encryptedData: Uint8Array;+ /**+ * The nonce that encrypted {@link encryptedData}. Needed to decrypt, and not+ * secret, but never reused with the same key.+ */+ nonce: 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.+ *+ * Returns the ciphertext and the generated nonce; decrypt with+ * {@link secretboxDecrypt}.+ *+ * Wire-compatible with libsodium's `crypto_secretbox_easy`.+ */+export const secretboxEncrypt = async (+ data: Uint8Array,+ key: Key,+): Promise<EncryptedBox> => {+ const wasm = await loadWasmCore();+ const box = wasm.secretboxEncrypt(data, key.bytes);+ try {+ return {+ encryptedData: box.encryptedData,+ nonce: Nonce.fromBytes(box.nonce),+ };+ } finally {+ box.free();+ }+};++/**+ * Encrypt `data` under `key` with a caller-supplied `nonce`.+ *+ * Prefer {@link secretboxEncrypt}, 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.+ *+ * 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`, wire-compatible with libsodium's+ * `crypto_secretbox_easy`.+ */+export const secretboxEncryptWithNonce = async (+ data: Uint8Array,+ nonce: Nonce,+ key: Key,+): Promise<Uint8Array> => {+ const wasm = await loadWasmCore();+ return wasm.secretboxEncryptWithNonce(data, nonce.bytes, key.bytes);+};++/**+ * Decrypt a ciphertext produced by {@link secretboxEncrypt}.+ *+ * 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.+ *+ * Throws if `data` is smaller than the tag, or 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`.+ */+export const secretboxDecrypt = async (+ data: Uint8Array,+ nonce: Nonce,+ key: Key,+): Promise<Uint8Array> => {+ const wasm = await loadWasmCore();+ return wasm.secretboxDecrypt(data, nonce.bytes, key.bytes);+};++/**+ * Encrypt `data` under `key` into one self-contained buffer.+ *+ * Like {@link secretboxEncrypt}, 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 {@link secretboxDecryptCombined}.+ *+ * 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.+ */+export const secretboxEncryptCombined = async (+ data: Uint8Array,+ key: Key,+): Promise<Uint8Array> => {+ const wasm = await loadWasmCore();+ return wasm.secretboxEncryptCombined(data, key.bytes);+};++/**+ * Decrypt a combined buffer produced by {@link secretboxEncryptCombined}.+ *+ * Splits the leading nonce from the `MAC β ciphertext` body, then verifies the+ * tag and decrypts as {@link secretboxDecrypt} does.+ *+ * Throws if `data` is too short to hold a nonce and tag, otherwise the same as+ * {@link secretboxDecrypt}.+ *+ * The body is wire-compatible with libsodium's `crypto_secretbox_open_easy`;+ * the leading nonce is an Ente convention.+ */+export const secretboxDecryptCombined = async (+ data: Uint8Array,+ key: Key,+): Promise<Uint8Array> => {+ const wasm = await loadWasmCore();+ return wasm.secretboxDecryptCombined(data, key.bytes);+};diff --git a/web/packages/wasm-core/types.ts b/web/packages/wasm-core/types.tsnew file mode 100644index 0000000000..d2a505e002--- /dev/null+++ b/web/packages/wasm-core/types.ts@@ -0,0 +1,143 @@+/**+ * @file Typed key material and related fixed-size values.+ *+ * These types carry their size in the type, so length validation happens once,+ * at the boundary where raw bytes enter ({@link Key.fromBytes} and friends),+ * rather than inside every operation.+ */++const sized = (bytes: Uint8Array, length: number, name: string): Uint8Array => {+ if (bytes.length !== length) {+ throw new Error(+ `${name} must be ${length} bytes, but got ${bytes.length}`,+ );+ }+ return bytes;+};++/**+ * A 256-bit symmetric encryption key.+ *+ * One key type serves the secretbox, blob and stream operations: both algorithm+ * families take 256-bit keys, and Ente's data model shares key material across+ * them (e.g. a collection key wraps file keys via secretbox and encrypts+ * collection metadata via blob).+ */+export class Key {+ private constructor(private readonly _bytes: Uint8Array) {}++ /**+ * Construct a key from `bytes`, validating the length.+ *+ * Throws unless `bytes` is exactly 32 bytes long.+ */+ static fromBytes(bytes: Uint8Array): Key {+ return new Key(sized(bytes, 32, "Key"));+ }++ /** The raw key bytes. */+ get bytes(): Uint8Array {+ return this._bytes;+ }+}++/** A 192-bit SecretBox nonce. Not secret. */+export class Nonce {+ private constructor(private readonly _bytes: Uint8Array) {}++ /**+ * Construct a nonce from `bytes`, validating the length.+ *+ * Throws unless `bytes` is exactly 24 bytes long.+ */+ static fromBytes(bytes: Uint8Array): Nonce {+ return new Nonce(sized(bytes, 24, "Nonce"));+ }++ /** The raw nonce bytes. */+ get bytes(): Uint8Array {+ return this._bytes;+ }+}++/** A 128-bit key derivation salt. Not secret. */+export class Salt {+ private constructor(private readonly _bytes: Uint8Array) {}++ /**+ * Construct a salt from `bytes`, validating the length.+ *+ * Throws unless `bytes` is exactly 16 bytes long.+ */+ static fromBytes(bytes: Uint8Array): Salt {+ return new Salt(sized(bytes, 16, "Salt"));+ }++ /** The raw salt bytes. */+ get bytes(): Uint8Array {+ return this._bytes;+ }+}++/**+ * A 192-bit SecretStream decryption header. Not secret.+ *+ * While the exact contents are an implementation detail of the secretstream+ * construction, it effectively contains the random nonce generated during+ * encryption, and is required for decryption.+ */+export class Header {+ private constructor(private readonly _bytes: Uint8Array) {}++ /**+ * Construct a header from `bytes`, validating the length.+ *+ * Throws unless `bytes` is exactly 24 bytes long.+ */+ static fromBytes(bytes: Uint8Array): Header {+ return new Header(sized(bytes, 24, "Header"));+ }++ /** The raw header bytes. */+ get bytes(): Uint8Array {+ return this._bytes;+ }+}++/** An X25519 public key. Not secret. */+export class PublicKey {+ private constructor(private readonly _bytes: Uint8Array) {}++ /**+ * Construct a public key from `bytes`, validating the length.+ *+ * Throws unless `bytes` is exactly 32 bytes long.+ */+ static fromBytes(bytes: Uint8Array): PublicKey {+ return new PublicKey(sized(bytes, 32, "PublicKey"));+ }++ /** The raw public key bytes. */+ get bytes(): Uint8Array {+ return this._bytes;+ }+}++/** An X25519 secret key. */+export class SecretKey {+ private constructor(private readonly _bytes: Uint8Array) {}++ /**+ * Construct a secret key from `bytes`, validating the length.+ *+ * Throws unless `bytes` is exactly 32 bytes long.+ */+ static fromBytes(bytes: Uint8Array): SecretKey {+ return new SecretKey(sized(bytes, 32, "SecretKey"));+ }++ /** The raw secret key bytes. */+ get bytes(): Uint8Array {+ return this._bytes;+ }+}