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.
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.
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));32
card ending 4242The 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.