Files
suaveplan/packages/security-stack/crypto/crypto-cipher/src/primitives/chacha20-poly1305/chacha20-poly1305.select/chacha20-poly1305.select.md
2026-05-27 23:47:53 +01:00

2.7 KiB

chacha20-poly1305.select

(no submodules)

Purpose

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

Callers import through chacha20-poly1305.ts and never reference this file directly. The selector decouples the public API from the concrete implementation, enabling backend switches with no changes to caller code.

Features

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

Usage: Basic Example

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

const key = crypto.getRandomValues(new Uint8Array(KEY_LENGTH));
const nonce = crypto.getRandomValues(new Uint8Array(NONCE_LENGTH));
const ct = encrypt(key, nonce, new TextEncoder().encode("test"));
console.log(ct.length); // 4 + 16 = 20

Usage: Advanced Example

import { decrypt } from "@suaveplan/crypto-cipher/chacha20-poly1305";
import { CryptoCipherError } from "@suaveplan/crypto-cipher/errors";
import { CRYPTO_CIPHER_CODES } from "@suaveplan/crypto-cipher/errors";

function isDecryptError(err: unknown): err is CryptoCipherError {
    return err instanceof CryptoCipherError &&
        err.code === CRYPTO_CIPHER_CODES.DECRYPT_FAILED;
}

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: 12
  • TAG_LENGTH: 16

Implementation Notes

This generated file contains export * from "./impl/chacha20-poly1305.noble.js" and is marked /* GENERATED — DO NOT EDIT */. The generator is idempotent and safe to run at any time. Do not add logic here — it will be overwritten on the next generator run.

Selection Logic

At build time crypto.config.ts picks the Noble or native engine for the IETF ChaCha20-Poly1305 primitive; the selector routes every call to the chosen implementation. Authentication tag mismatch throws the shared CryptoCipherError with code CRYPTO.CIPHER.TAG_MISMATCH. Nonce is caller-supplied; the IETF 12-byte nonce variant is the one implemented here — the extended 24-byte XChaCha20 variant lives in xchacha20-poly1305.