Skip to content
jshacks.dev
Security

Encrypt data with Web Crypto AES-GCM

Encrypt and decrypt a string with AES-GCM in the Web Crypto API, using a fresh random 12-byte IV for every message.

1 min read
Summarize in AI

AES-GCM both encrypts and authenticates, so tampered data fails to decrypt instead of coming back as garbage. The one rule you must follow is never to reuse an IV with the same key.

aes.jsJavaScript
const key = await crypto.subtle.generateKey({ name: 'AES-GCM', length: 256 }, true, ['encrypt', 'decrypt']);

async function encrypt(text) {
  const iv = crypto.getRandomValues(new Uint8Array(12));
  const data = new TextEncoder().encode(text);
  const cipher = await crypto.subtle.encrypt({ name: 'AES-GCM', iv }, key, data);
  return { iv, cipher };
}

async function decrypt({ iv, cipher }) {
  const plain = await crypto.subtle.decrypt({ name: 'AES-GCM', iv }, key, cipher);
  return new TextDecoder().decode(plain);
}

const sealed = await encrypt('card ending 4242');
console.log(sealed.cipher.byteLength);
console.log(await decrypt(sealed));
Text
32
card ending 4242

The ciphertext is 32 bytes: 16 for the text plus the 16-byte authentication tag that GCM appends. Store the IV beside the ciphertext, since it is not secret. Flip one byte of cipher and decrypt rejects with an OperationError. See SubtleCrypto.encrypt on MDN.

A random 96-bit IV is safe for roughly 2^32 messages per key; rotate keys before that. This is the same global crypto in Node.js 24 and in browsers.

Share

More snippets

Security

Report CSP violations to an endpoint

Receive Content Security Policy violation reports at an endpoint with the report-to and report-uri directives, and parse what the browser sends.

1 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.