diff --git a/web/packages/base/crypto/ente.ts b/web/packages/base/crypto/ente.ts index dce6dc1050..11f1c41878 100644 --- a/web/packages/base/crypto/ente.ts +++ b/web/packages/base/crypto/ente.ts @@ -142,7 +142,7 @@ export const encryptMetadataJSON = async (r: EncryptJSON) => /** * Decrypt arbitrary data, provided as a base64 string, using the given key and - * the provided nonce. + * the provided nonce, and return the base64 * * This is the sibling of {@link encryptBoxB64}. * diff --git a/web/packages/base/crypto/libsodium.ts b/web/packages/base/crypto/libsodium.ts index 5f57c459b8..a21359b181 100644 --- a/web/packages/base/crypto/libsodium.ts +++ b/web/packages/base/crypto/libsodium.ts @@ -12,10 +12,12 @@ import { mergeUint8Arrays } from "@/utils/array"; import { CustomError } from "@ente/shared/error"; import sodium, { type StateAddress } from "libsodium-wrappers"; import type { + BytesOrB64, DecryptBlobBytes, DecryptBoxBytes, EncryptBytes, EncryptedBlobBytes, + EncryptedBox2, EncryptedBoxBytes, } from "./types"; @@ -342,6 +344,29 @@ export const decryptBox = async ({ ); }; +/** + * If the provided {@link bob} ("Bytes or B64 string") is already a + * {@link Uint8Array}, return it unchanged, otherwise convert the base64 string + * into bytes and return those. + */ +const bytes = async (bob: BytesOrB64) => + typeof bob == "string" ? fromB64(bob) : bob; + +/** + * Decrypt the result of {@link encryptBox}. + */ +export const decryptBox2 = async ( + { encryptedData, nonce }: EncryptedBox2, + key: BytesOrB64, +): Promise => { + await sodium.ready; + return sodium.crypto_secretbox_open_easy( + await bytes(encryptedData), + await bytes(nonce), + await bytes(key), + ); +}; + /** * Decrypt the result of {@link encryptBlob}. */ diff --git a/web/packages/base/crypto/types.ts b/web/packages/base/crypto/types.ts index 1166c00bc3..1e6144d059 100644 --- a/web/packages/base/crypto/types.ts +++ b/web/packages/base/crypto/types.ts @@ -149,6 +149,34 @@ export interface DecryptBoxBytes { keyB64: string; } +/** + * Data provided either as bytes ({@link Uint8Array}) or their base64 string representation. + */ +export type BytesOrB64 = Uint8Array | string; + +/** + * A decryption request to decrypt data encrypted using the secretbox APIs. + * + * See: [Note: 3 forms of encryption (Box | Blob | Stream)]. + */ +export interface EncryptedBox2 { + /** + * The data to decrypt. + */ + encryptedData: BytesOrB64; + /** + * The nonce that was used during encryption. + * + * The nonce is required to decrypt the data, but it does not need to be + * kept secret. + */ + nonce: BytesOrB64; + /** + * The encryption key. + */ + key: BytesOrB64; +} + /** * A variant of {@link DecryptBoxBytes} with the encrypted Blob's data as a * base64 encoded string.