WebCrypto AES-GCM Encrypts And Decrypts

Encrypt and decrypt with WebCrypto AES-GCM, seeing the 16-byte authentication tag and verifying that tampered ciphertext is rejected.

JavascriptSecurity Boundaries

Code

javascriptsnippet
22 lines
// AES-GCM: authenticated encryption through WebCrypto
const keyBytes = new Uint8Array(32).fill(9);
const key = await crypto.subtle.importKey('raw', keyBytes, 'AES-GCM', false, ['encrypt', 'decrypt']);

const iv = crypto.getRandomValues(new Uint8Array(12));
const plaintext = new TextEncoder().encode('transfer 42 coins to alice');

const ciphertext = await crypto.subtle.encrypt({ name: 'AES-GCM', iv }, key, plaintext);
console.log('ciphertext bytes:', ciphertext.byteLength); // includes the 16-byte auth tag

const decrypted = await crypto.subtle.decrypt({ name: 'AES-GCM', iv }, key, ciphertext);
console.log('round trip:', new TextDecoder().decode(decrypted) === 'transfer 42 coins to alice');

// tampering with authenticated ciphertext fails instead of returning garbage
const tampered = new Uint8Array(ciphertext);
tampered[0] ^= 1;
try {
  await crypto.subtle.decrypt({ name: 'AES-GCM', iv }, key, tampered);
  console.log('tampered accepted');
} catch {
  console.log('tampered rejected');
}

Output

Captured from a sandboxed run of this snippet in the build pipeline.

ciphertext bytes: 42
round trip: true
tampered rejected

How it works

The async parts await their results, which keeps ordering predictable.

The demo data lives in module-level bindings: keyBytes, key, iv, plaintext.

Caveats

  • The whole dependency story is the language version itself.
  • This is browser-side code — crypto will not resolve in Node.

Applying it

The run emits 3 labeled sections — ciphertext bytes:, round trip:, tampered rejected; tampered accepted is the branch that never prints, because tampered ciphertext always fails authenticated decryption.

Statements that matter

const key = await crypto.subtle.importKey('raw', keyBytes, 'AES-GCM', false, ['encrypt', 'decrypt']);
const ciphertext = await crypto.subtle.encrypt({ name: 'AES-GCM', iv }, key, plaintext);
const decrypted = await crypto.subtle.decrypt({ name: 'AES-GCM', iv }, key, ciphertext);

Interactive Tools for This Topic

FAQ

Do I need to install anything before running this?
No — every API used here ships with the language runtime, so there is nothing to install. Its state lives in module-level bindings: `keyBytes`, `key`, `iv`.