Files
skills/docs/security-stack/crypto/crypto-cipher/src/primitives/xchacha20-poly1305/xchacha20-poly1305.select/xchacha20-poly1305.select.md
2026-05-29 08:20:56 +01:00

2.6 KiB

xchacha20-poly1305.select

(no submodules)

Purpose

xchacha20-poly1305.select.ts is the build-time primitive selector for XChaCha20-Poly1305 in @suaveplan/crypto-cipher. Generated by bun scripts/gen-crypto-selects.ts, it re-exports one backend — xchacha20-poly1305.noble.ts or xchacha20-poly1305.native.ts — based on the xchacha20-poly1305 field in crypto.config.ts.

Callers import through the stable xchacha20-poly1305.ts entry point. This selector level means backend changes require only regenerating this file; all call sites above it remain unchanged. Currently the Noble backend is selected.

Features

  • Re-exports encrypt, decrypt, KEY_LENGTH, NONCE_LENGTH, TAG_LENGTH.
  • Generated — never hand-edited.
  • Controlled by crypto.config.ts: set xchacha20-poly1305 to 'noble' or 'native'.
  • Enables dead-code elimination of the inactive backend.

Usage: Basic Example

import { KEY_LENGTH, NONCE_LENGTH } from "@suaveplan/crypto-cipher/xchacha20-poly1305";

console.log(KEY_LENGTH);   // 32
console.log(NONCE_LENGTH); // 24 (XChaCha20's extended nonce)

Usage: Advanced Example

import { encrypt, decrypt, NONCE_LENGTH } from "@suaveplan/crypto-cipher/xchacha20-poly1305";

// Round-trip with random nonce.
function roundTrip(key: Uint8Array, msg: Uint8Array): Uint8Array {
    const nonce = crypto.getRandomValues(new Uint8Array(NONCE_LENGTH));
    return decrypt(key, nonce, encrypt(key, nonce, msg));
}

API Reference

Re-exports from the active implementation:

  • encrypt(key: Uint8Array, nonce: Uint8Array, plaintext: Uint8Array, aad?: Uint8Array): Uint8Array
  • decrypt(key: Uint8Array, nonce: Uint8Array, ciphertext: Uint8Array, aad?: Uint8Array): Uint8Array
  • KEY_LENGTH: 32
  • NONCE_LENGTH: 24
  • TAG_LENGTH: 16

Implementation Notes

This file is a generated one-liner marked /* GENERATED — DO NOT EDIT */. The NONCE_LENGTH of 24 is the defining characteristic of XChaCha20 relative to standard ChaCha20. The generator resolves the xchacha20-poly1305 backend from crypto.config.ts and emits the correct export * path. Regenerating is idempotent.

Selection Logic

At build time crypto.config.ts picks the Noble or native engine for XChaCha20-Poly1305 — the 24-byte-nonce variant suitable for random-nonce encryption of large numbers of messages under a single key. The selector routes every call to the chosen impl and throws PrimitiveNotImplemented when the selected engine has no native binding yet. Nonce is caller-supplied in every path.