Back to cheatsheets
Cryptography
AES-GCM Encryption / Decryption
AES-GCM 256-bit encryption and decryption with passphrase-derived keys using the Web Crypto API.
What you'll learn
- Encrypt with passphrase
- Decrypt with passphrase
How to use these snippets
- Click the Copy button next to any snippet to copy it to your clipboard.
- Paste the code into your project, IDE, or terminal.
- Replace placeholder values (like
example.comoryour-secret) with your actual data. - Review the code comments for important security notes and caveats.
- Try the interactive related tool to see the concept in action.
Code Snippets
Copy-paste code snippets
2 ready-to-use snippets for aes-gcm encryption / decryption. Click copy and paste into your project.
Encrypt with passphrase
async function encrypt(text, passphrase) {
const enc = new TextEncoder();
const salt = crypto.getRandomValues(new Uint8Array(16));
const iv = crypto.getRandomValues(new Uint8Array(12));
// Derive key from passphrase
const keyMaterial = await crypto.subtle.importKey(
'raw', enc.encode(passphrase), 'PBKDF2', false, ['deriveKey']
);
const key = await crypto.subtle.deriveKey(
{ name: 'PBKDF2', salt, iterations: 100000, hash: 'SHA-256' },
keyMaterial,
{ name: 'AES-GCM', length: 256 },
false, ['encrypt']
);
// Encrypt
const ciphertext = await crypto.subtle.encrypt(
{ name: 'AES-GCM', iv },
key, enc.encode(text)
);
// Return salt + iv + ciphertext
return { salt, iv, ciphertext };
}
Decrypt with passphrase
async function decrypt(encrypted, passphrase) {
const enc = new TextEncoder();
const { salt, iv, ciphertext } = encrypted;
// Derive same key
const keyMaterial = await crypto.subtle.importKey(
'raw', enc.encode(passphrase), 'PBKDF2', false, ['deriveKey']
);
const key = await crypto.subtle.deriveKey(
{ name: 'PBKDF2', salt, iterations: 100000, hash: 'SHA-256' },
keyMaterial,
{ name: 'AES-GCM', length: 256 },
false, ['decrypt']
);
// Decrypt
const plaintext = await crypto.subtle.decrypt(
{ name: 'AES-GCM', iv }, key, ciphertext
);
return new TextDecoder().decode(plaintext);
}
Tool
Related ShieldX tool
Try this concept hands-on with the interactive tool.
100% Free · No signup · No cost
Generate something unguessable right now
148 bits of entropy, a crack-time estimate you can trust, and a clipboard that clears itself after 30 seconds.
Part of the Toolly ecosystem · secure.toolly.site