ShieldX Toolly
Open a tool Donate
Home Home
Blog Blog
FAQ FAQ
Open a tool Donate
Back to cheatsheets
Cryptography

AES-GCM Encryption / Decryption

AES-GCM 256-bit encryption and decryption with passphrase-derived keys using the Web Crypto API.

2 snippets Intermediate aes-encrypt-decrypt
AES-GCMencryptionPBKDF2Web Crypto API

What you'll learn

  • Encrypt with passphrase
  • Decrypt with passphrase

How to use these snippets

  1. Click the Copy button next to any snippet to copy it to your clipboard.
  2. Paste the code into your project, IDE, or terminal.
  3. Replace placeholder values (like example.com or your-secret) with your actual data.
  4. Review the code comments for important security notes and caveats.
  5. 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);
}
              
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.

Open the toolkit

Part of the Toolly ecosystem · secure.toolly.site