We're sorry but this app doesn't work properly without JavaScript enabled. Please enable it to continue.

This lesson's interactive features are locked, please to keep using them

Encrypting Data at Rest

HTTPS protects data in transit. It does nothing once the data is stored.

If someone steals a database file, uploaded document, or backup, encryption at rest can prevent them from reading it without the key. If you're storing especially sensitive values in a database, like a user's API key or shipping details, consider field-level encryption.

Authenticated Encryption

AES-GCM is a type of authenticated, symmetric encryption. It provides:

  • Confidentiality: The plaintext becomes unreadable ciphertext.
  • Integrity: An authentication tag detects changes to the encrypted value.

Click to play video

The Encrypted Payload

When you encrypt a value with AES-GCM, it produces three pieces that need to stay together:

  • The ciphertext, which replaces the plaintext
  • A 12-byte nonce, also called an initialization vector (IV)
  • A 16-byte authentication tag, which detects tampering

The nonce and authentication tag aren't secrets, so you can just store them alongside the ciphertext. The 32-byte AES-256 key is the secret.

Every encryption that uses the same key needs a unique nonce. Reusing a GCM nonce can destroy both confidentiality and integrity, so generate a fresh one with randomBytes each time you encrypt:

const nonce = randomBytes(12);
const cipher = createCipheriv("aes-256-gcm", key, nonce, {
  authTagLength: 16,
});
const ciphertext = Buffer.concat([
  cipher.update("I like Nickelback"),
  cipher.final(),
]);
const authTag = cipher.getAuthTag();

Decryption reverses the operation, but only after supplying the stored authentication tag:

const decipher = createDecipheriv("aes-256-gcm", key, nonce, {
  authTagLength: 16,
});
decipher.setAuthTag(authTag);
const plaintext = Buffer.concat([
  decipher.update(ciphertext),
  decipher.final(),
]);
// plaintext.toString() === "I like Nickelback"

The helper should accept Buffer values instead of strings so it can later protect JSON, database fields, and binary files without changing cryptographic formats.

Assignment

Bearly Secure needs one safe encryption primitive for its sensitive stored data. Create a reusable AES-256-GCM helper.

Run and submit the CLI tests from the project root.