API reference@evolu/commonCrypto › encryptWithXChaCha20Poly1305

function encryptWithXChaCha20Poly1305(
  deps: RandomBytesDep,
): (
  plaintext: Uint8Array,
  encryptionKey: Uint8Array<ArrayBufferLike> &
    Brand<"Entropy"> &
    Brand<"Length32"> &
    Brand<"EncryptionKey">,
) => [
  Uint8Array<ArrayBufferLike> & Brand<"XChaCha20Poly1305Ciphertext">,
  Uint8Array<ArrayBufferLike> & Brand<"Entropy"> & Brand<"Length24">,
];

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

Encrypts plaintext with XChaCha20-Poly1305.

Generates a random nonce internally and returns both the ciphertext and nonce. The nonce must be stored alongside the ciphertext for decryption.

Example

import {
  assertEqual,
  assertType,
  createRandomBytes,
  EncryptionKey,
  encryptWithXChaCha20Poly1305,
  type XChaCha20Poly1305Ciphertext,
  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);

assertType<XChaCha20Poly1305Ciphertext, typeof ciphertext>();
assertEqual(nonce.length, 24);

See

https://github.com/paulmillr/noble-ciphers