Authenticated encryption with ChaCha20-Poly1305 and AES-GCM
Encrypt with ChaCha20-Poly1305 and AES-GCM; a tampered message or a wrong key is rejected.
Apache-2.0Runs on this page
Package: @awacloud/fw
Encrypt and decrypt a message with both AEADs, with a fresh key and nonce from the secure random source; a tampered ciphertext, a wrong key or a wrong associated data is rejected, not decrypted.
Uses @awacloud/fw (Apache-2.0). This example's code is Apache-2.0.
When to use it
Anything encrypted at rest or in transit needs authentication too: an AEAD
gives both in one call. ChaCha20-Poly1305 is fast in pure JavaScript;
AES-GCM matches what servers and crypto.subtle speak. Never reuse a nonce
with the same key: the modules ship a nonceTracker for long-lived keys.
Copy-paste steps
npm install @awacloud/fw- Serve
node_modules/@awacloud/fw/src/at/vendor/fw/(node serve.jsfrom the examples root does this; any static server works). - Copy
index.htmlandmain.jsnext to each other and openindex.htmlthrough that server. The../../_style/examples.csslink is optional: copy that file along, or delete the link. - Keep the
chacha/aesGcmwrappers: they fix the byte layout (ciphertext || tag) and turn a failed tag intonull.
What it shows
chacha20poly1305.encrypt(key, nonce, plaintext, aad)→{ ct, tag }anddecrypt(...)→ bytes orfalse, allUint8Array.gcm.encrypt(prf, plaintext, iv, aad, 128)whereprfisaes.fn(key)and everything is a bit array;bitArrayconverts at the edges. For AES-GCM in an app, WebCrypto is usually simpler (fw/crypto-webcrypto).- Four plain functions,
seal*andopen*per algorithm:open*returnsnull, never garbage, for a tampered message, a wrong key or a wrong AAD. random.bytes(n)for keys and nonces,hex.fromBytesto show them.- Checked against the public known answers of RFC 8439 and NIST GCM, and against tampered inputs.
Code
main.js
// SPDX-License-Identifier: Apache-2.0
import fw from '@awacloud/fw';
import { chacha20poly1305 } from '@awacloud/fw/crypto/mode/chacha20poly1305.js';
import { gcm } from '@awacloud/fw/crypto/mode/gcm.js';
import { aes } from '@awacloud/fw/crypto/cipher/aes.js';
import { random } from '@awacloud/fw/crypto/utils/random.js';
import { hex } from '@awacloud/fw/io/codec/hex.js';
fw.runtime.registerAllDeep([chacha20poly1305, gcm, aes, random, hex]);
const CHACHA = fw.runtime.resolve('chacha20poly1305');
const GCM = fw.runtime.resolve('gcm');
const AES = fw.runtime.resolve('aes');
const RANDOM = fw.runtime.resolve('random');
const BA = fw.runtime.resolve('bitArray');
export const HEX = fw.runtime.resolve('hex');
const encoder = new TextEncoder();
const decoder = new TextDecoder();
/** Authenticated but not encrypted: a label both sides must agree on. */
export const AAD = encoder.encode('examples/crypto-aead v1');
// Each function: bytes in, `ciphertext || 16-byte tag` out; `open*` returns
// null (never garbage) when the tag does not verify.
/**
* ChaCha20-Poly1305 (RFC 8439).
* @param {Uint8Array} key @param {Uint8Array} nonce @param {Uint8Array} plain @param {Uint8Array} aad
*/
export function sealChaCha(key, nonce, plain, aad) {
const { ct, tag } = CHACHA.encrypt(key, nonce, plain, aad);
return new Uint8Array([...ct, ...tag]);
}
/** @param {Uint8Array} key @param {Uint8Array} nonce @param {Uint8Array} sealed @param {Uint8Array} aad */
export function openChaCha(key, nonce, sealed, aad) {
const plain = CHACHA.decrypt(key, nonce, sealed.subarray(0, -16), sealed.subarray(-16), aad);
return plain === false ? null : plain;
}
// AES-256-GCM in pure JavaScript works on bit arrays (`bitArray`): convert at
// the edges. Most apps take WebCrypto's AES-GCM instead (fw/crypto-webcrypto).
/** @param {Uint8Array} key @param {Uint8Array} nonce @param {Uint8Array} plain @param {Uint8Array} aad */
export function sealAesGcm(key, nonce, plain, aad) {
const cipher = AES.fn(BA.ui8_to_ba(key));
const { ct, tag } = GCM.encrypt(cipher, BA.ui8_to_ba(plain), BA.ui8_to_ba(nonce), BA.ui8_to_ba(aad), 128);
return BA.ba_to_ui8(BA.concat(ct, tag));
}
/** @param {Uint8Array} key @param {Uint8Array} nonce @param {Uint8Array} sealed @param {Uint8Array} aad */
export function openAesGcm(key, nonce, sealed, aad) {
const [ct, tag] = [sealed.subarray(0, -16), sealed.subarray(-16)].map((part) => BA.ui8_to_ba(part));
const plain = GCM.decrypt(AES.fn(BA.ui8_to_ba(key)), ct, BA.ui8_to_ba(nonce), BA.ui8_to_ba(aad), tag, 128);
return plain === false ? null : BA.ba_to_ui8(plain);
}
const rows = /** @type {HTMLElement} */ (document.getElementById('rows'));
const message = /** @type {HTMLTextAreaElement} */ (document.getElementById('message'));
const tamper = /** @type {HTMLInputElement} */ (document.getElementById('tamper'));
const ALGORITHMS = [['ChaCha20-Poly1305', sealChaCha, openChaCha], ['AES-256-GCM', sealAesGcm, openAesGcm]];
function update() {
const key = /** @type {Uint8Array} */ (RANDOM.bytes(32)); // one key; a fresh nonce per encryption
rows.replaceChildren(...ALGORITHMS.map(([name, seal, open]) => {
const nonce = /** @type {Uint8Array} */ (RANDOM.bytes(12));
const sealed = /** @type {Function} */ (seal)(key, nonce, encoder.encode(message.value), AAD);
if (tamper.checked) sealed[0] ^= 0x01;
const opened = /** @type {Function} */ (open)(key, nonce, sealed, AAD);
const tr = document.createElement('tr');
const verdict = opened ? decoder.decode(opened) : 'REJECTED (tag mismatch)';
for (const cell of [name, HEX.fromBytes(nonce), HEX.fromBytes(sealed), verdict]) {
tr.appendChild(document.createElement('td')).textContent = /** @type {string} */ (cell);
}
return tr;
}));
}
message.addEventListener('input', update);
tamper.addEventListener('change', update);
update();index.html
<!doctype html>
<!-- SPDX-License-Identifier: Apache-2.0 -->
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>fw · Authenticated encryption with ChaCha20-Poly1305 and AES-GCM</title>
<link rel="stylesheet" href="../../_style/examples.css">
<script type="importmap">
{ "imports": {
"@awacloud/fw": "/vendor/fw/main.js", "@awacloud/fw/": "/vendor/fw/" } }
</script>
<script type="module" src="./main.js"></script>
</head>
<body>
<main>
<h1>Authenticated encryption with ChaCha20-Poly1305 and AES-GCM</h1>
<label for="message">Message</label>
<textarea id="message" rows="2">Meet at the usual place at nine.</textarea>
<label><input id="tamper" type="checkbox"> Flip one ciphertext byte before decrypting</label>
<table>
<caption>One random 256-bit key and a fresh 96-bit nonce per encryption</caption>
<thead><tr><th scope="col">AEAD</th><th scope="col">Nonce</th><th scope="col">Ciphertext + tag (hex)</th>
<th scope="col">Decrypts to</th></tr></thead>
<tbody id="rows"></tbody>
</table>
</main>
</body>
</html>