Full answer
Symmetric encryption uses one secret key for both encrypting and decrypting. GCM mode is an authenticated mode: besides hiding the content, it produces an authentication tag that proves nothing was altered. Older modes such as CBC without a MAC allow silent tampering.
Ingredients:
- Key: 32 random bytes for AES-256. Get it from a secret manager, or derive it from a password with scrypt and a salt. Do not use a plain password as a key.
- IV (nonce): 12 random bytes, new for every message. With GCM, reusing an IV under the same key breaks the security badly. Store the IV with the ciphertext (it is not secret).
- Auth tag: 16 bytes, from cipher.getAuthTag() after final(). Store it too, and give it back with decipher.setAuthTag() before final().
- Additional authenticated data (AAD): optional plain data (a record id, a version) that is not encrypted but is covered by the tag. It binds the ciphertext to its context.
Process:
- cipher = crypto.createCipheriv('aes-256-gcm', key, iv); optionally cipher.setAAD(aad).
- ciphertext = Buffer.concat([cipher.update(plaintext), cipher.final()]).
- tag = cipher.getAuthTag(). Save iv, ciphertext and tag together (for example iv | tag | ciphertext).
- To decrypt, create a decipher with the same key and iv, call setAuthTag(tag), then update and final. If anything was altered, final() throws an error and you must not use the output.
Notes: never log keys or plaintext, plan key rotation (store a key id with the data), and remember that encryption does not hide the data size. For passwords use hashing, not encryption.
const crypto = require('node:crypto');
function encrypt(plaintext, key, aad) {
const iv = crypto.randomBytes(12); // new for every message
const cipher = crypto.createCipheriv('aes-256-gcm', key, iv);
if (aad) cipher.setAAD(Buffer.from(aad));
const ciphertext = Buffer.concat([cipher.update(plaintext, 'utf8'), cipher.final()]);
const tag = cipher.getAuthTag(); // 16 bytes
return Buffer.concat([iv, tag, ciphertext]); // layout: iv | tag | ciphertext
}
function decrypt(packed, key, aad) {
const iv = packed.subarray(0, 12);
const tag = packed.subarray(12, 28);
const ciphertext = packed.subarray(28);
const decipher = crypto.createDecipheriv('aes-256-gcm', key, iv);
if (aad) decipher.setAAD(Buffer.from(aad));
decipher.setAuthTag(tag);
return Buffer.concat([decipher.update(ciphertext), decipher.final()]).toString('utf8'); // final() throws on tampering
}
const key = crypto.randomBytes(32);
const message = 'Asha scored 78 in Maths';
const packed = encrypt(message, key, 'student:42');
console.log('packed length = 12 (iv) + 16 (tag) + message bytes:', packed.length === 12 + 16 + Buffer.byteLength(message));
console.log('round trip works:', decrypt(packed, key, 'student:42') === message);
const second = encrypt(message, key, 'student:42');
console.log('same message, different output (random IV):', !packed.equals(second));
function tryDecrypt(label, data, k, aad) {
try {
decrypt(data, k, aad);
console.log(label, '-> accepted');
} catch (err) {
console.log(label, '-> rejected:', err.message);
}
}
const tampered = Buffer.from(packed);
tampered[tampered.length - 1] ^= 1; // flip one bit of the ciphertext
tryDecrypt('tampered ciphertext', tampered, key, 'student:42');
tryDecrypt('wrong context (aad)', packed, key, 'student:43');
tryDecrypt('wrong key', packed, crypto.randomBytes(32), 'student:42');Three decryption attempts fail on purpose (error on purpose): a changed bit, the wrong context and the wrong key. All three throw the same authentication error. Save it as app.js and run it with node app.js. Output (Node.js v24.22.1, same on two runs): packed length = 12 (iv) + 16 (tag) + message bytes: true round trip works: true same message, different output (random IV): true tampered ciphertext -> rejected: Unsupported state or unable to authenticate data wrong context (aad) -> rejected: Unsupported state or unable to authenticate data wrong key -> rejected: Unsupported state or unable to authenticate data
Key points
- Key: 32 random bytes. IV: 12 bytes, unique per message.
- Store IV and auth tag with the ciphertext.
- final() throws when data or tag was tampered with.
- AAD binds the ciphertext to its context.
- Never reuse an IV with the same key.
Common mistakes
- Reusing an IV or using a counter that restarts after a crash.
- Forgetting to store the auth tag.
- Using the decrypted output before final() has succeeded.
- Using a human password directly as the key.
Follow-ups
- Why is GCM better than CBC for most uses?
- How would you rotate encryption keys for stored data?
- What is envelope encryption?
Tips
- Name the three stored items: IV, tag, ciphertext.
- Say 'authenticated encryption' and explain tampering.
- State the IV rule firmly.