v149 · JavaScript
WebCrypto Round-Trip
Encrypt a message with AES-GCM, then use Uint8Array.prototype.toBase64() to encode the ciphertext and IV for safe transport. Paste the base64 back in and use Uint8Array.fromBase64() to reconstruct the bytes before decrypting. The full encrypt → encode → decode → decrypt cycle in one page.
Generating AES-256-GCM key…
Encrypt
Plaintext message
1 IV (base64, 12 bytes)
—
2 Ciphertext (base64)
—
Decrypt
IV (base64) — auto-filled after encrypt
Ciphertext (base64) — auto-filled after encrypt
3 Decrypted plaintext
—
// 1. Encrypt and encode with toBase64()
const key = await crypto.subtle.generateKey(
{ name: 'AES-GCM', length: 256 },
false, // non-exportable
['encrypt', 'decrypt']
);
const iv = crypto.getRandomValues(new Uint8Array(12));
const cipherBuf = await crypto.subtle.encrypt(
{ name: 'AES-GCM', iv },
key,
new TextEncoder().encode(plaintext)
);
const ivB64 = iv.toBase64(); // ← new API
const cipherB64 = new Uint8Array(cipherBuf).toBase64(); // ← new API
// 2. Decode and decrypt with fromBase64()
const ivBytes = Uint8Array.fromBase64(ivB64); // ← new API
const cipherBytes = Uint8Array.fromBase64(cipherB64); // ← new API
const decryptedBuf = await crypto.subtle.decrypt(
{ name: 'AES-GCM', iv: ivBytes },
key,
cipherBytes
);
const result = new TextDecoder().decode(decryptedBuf);
see also
- Encode & Decode — basic round-trip
- URL-Safe Base64 —
alphabet: "base64url"option - Streaming Chunks —
setFromBase64()with chunk tracking
implementation reference
Need the exact API surface, compatibility boundaries, errors, lifecycle, and source links? Read the matching gendn reference ↗