AES Encryption in JavaScript
Implement AES-256-GCM encryption in the browser using the Web Crypto API — with code examples.
Published:
Tags: AES encryption JavaScript, Web Crypto API AES, browser AES encrypt
AES Encryption in JavaScript The Web Crypto API provides AES-256-GCM encryption natively in all modern browsers and Node.js 15+ — no external libraries needed. This guide covers the full encrypt/decrypt cycle, key export/import, password-based encryption with PBKDF2, and common pitfalls. --- What is Web Crypto API Basics? is available in: All modern browsers (Chrome 37+, Firefox 34+, Safari 11+, Edge 12+) Node.js 15+ () Web Workers and Service Workers All operations are asynchronous and return Promises. How do I create a complete encrypt/decrypt example? How do I encode data for storage or transmission? The function returns a . For storage in JSON, databases, or URLs, convert to Base64: What is Key Export and Import? Important: Exported key material must be stored securely (encrypted at…
Frequently Asked Questions
How do I use AES in JavaScript?
Use the Web Crypto API built into all modern browsers and Node.js 15+. Generate a key with `crypto.subtle.generateKey`, encrypt with `crypto.subtle.encrypt({ name: 'AES-GCM', iv })`, and decrypt with `crypto.subtle.decrypt`. No external libraries required.
What is the Web Crypto API?
The Web Crypto API (defined in the W3C Web Cryptography API spec) provides cryptographic operations in JavaScript: key generation, import/export, encryption, decryption, signing, and verification. It is available as `window.crypto.subtle` in browsers and `crypto.subtle` in Node.js 15+. Operations are async and return Promises.
How do I encrypt with AES-GCM in the browser?
Generate a key with `crypto.subtle.generateKey({ name: 'AES-GCM', length: 256 }, true, ['encrypt', 'decrypt'])`. Generate an IV with `crypto.getRandomValues(new Uint8Array(12))`. Encrypt with `crypto.subtle.encrypt({ name: 'AES-GCM', iv }, key, data)`. Prepend the IV to the ciphertext for storage.
How do I generate a cryptographic key in JavaScript?
For AES-GCM: `const key = await crypto.subtle.generateKey({ name: 'AES-GCM', length: 256 }, true, ['encrypt', 'decrypt'])`. The second argument (true) makes the key extractable — set to false if you never need to export it. For HMAC: use `{ name: 'HMAC', hash: 'SHA-256', length: 256 }` with `['sign', 'verify']`.
What is SubtleCrypto?
SubtleCrypto is the cryptographic interface exposed as `crypto.subtle`. It is named 'subtle' to signal that correct usage requires understanding cryptographic concepts. It provides generateKey, importKey, exportKey, encrypt, decrypt, sign, verify, digest, deriveKey, and deriveBits operations.
All articles · theproductguy.in