AES-GCM is the gold standard for authenticated encryption. In this tutorial, you will derive a key from a passphrase using PBKDF2, encrypt with AES-GCM and a random IV, and decrypt with error handling — all client-side.
Key derivation with PBKDF2
Never use a passphrase directly as an encryption key. Instead, derive a key using PBKDF2 (Password-Based Key Derivation Function 2) with a high iteration count.
async function deriveKey(passphrase, salt, iterations = 100000) {
const encoder = new TextEncoder();
const keyMaterial = await crypto.subtle.importKey('raw', encoder.encode(passphrase), 'PBKDF2', false, ['deriveKey']);
return crypto.subtle.deriveKey(
{ name: 'PBKDF2', salt, iterations, hash: 'SHA-256' },
keyMaterial,
{ name: 'AES-GCM', length: 256 },
false,
['encrypt', 'decrypt']
);
}
Encrypting with AES-GCM
async function encrypt(text, key) {
const encoder = new TextEncoder();
const iv = crypto.getRandomValues(new Uint8Array(12)); // 96-bit IV for GCM
const ciphertext = await crypto.subtle.encrypt(
{ name: 'AES-GCM', iv },
key,
encoder.encode(text)
);
return { ciphertext: new Uint8Array(ciphertext), iv };
}
Decrypting with AES-GCM
async function decrypt(ciphertext, iv, key) {
const decoder = new TextDecoder();
const plaintext = await crypto.subtle.decrypt(
{ name: 'AES-GCM', iv },
key,
ciphertext
);
return decoder.decode(plaintext);
}
WarningAES-GCM is authenticated encryption — if the ciphertext or IV is tampered with, decrypt() will throw. Always handle this error to avoid processing corrupted data.
Try it yourself
Open the ShieldX AES Encrypt / Decrypt tool, enter a passphrase and some text, and encrypt. Then decrypt with the same passphrase. Try changing one byte of the ciphertext — decryption will fail.