API reference@evolu/commonCrypto › decryptWithXChaCha20Poly1305

function decryptWithXChaCha20Poly1305(
  ciphertext: Uint8Array<ArrayBufferLike> &
    Brand<"XChaCha20Poly1305Ciphertext">,
  nonce: Uint8Array<ArrayBufferLike> & Brand<"Entropy"> & Brand<"Length24">,
  encryptionKey: Uint8Array<ArrayBufferLike> &
    Brand<"Entropy"> &
    Brand<"Length32"> &
    Brand<"EncryptionKey">,
): Result<Uint8Array<ArrayBufferLike>, DecryptWithXChaCha20Poly1305Error>;

Defined in: packages/common/src/Crypto.ts:258

Decrypts ciphertext with XChaCha20-Poly1305.

Requires the same nonce that was used during encryption. Returns a Result that may contain a decryption error if the ciphertext was tampered with or the wrong key/nonce was used.

Example

import {
  assertOk,
  bytesToUtf8,
  createRandomBytes,
  decryptWithXChaCha20Poly1305,
  EncryptionKey,
  encryptWithXChaCha20Poly1305,
  ok,
  utf8ToBytes,
} from "@evolu/common";

const plaintext = utf8ToBytes("secret message");
const encryptionKey = EncryptionKey.orThrow(new Uint8Array(32).fill(7));
const [ciphertext, nonce] = encryptWithXChaCha20Poly1305({
  randomBytes: createRandomBytes(),
})(plaintext, encryptionKey);

const decryptMessage = () => {
  const result = decryptWithXChaCha20Poly1305(ciphertext, nonce, encryptionKey);
  if (!result.ok) return result;
  return ok(bytesToUtf8(result.value));
};

assertOk(decryptMessage(), "secret message");