Skip to the content

Lesson 265 of 296

Secrets, encryption and least privilege

What you will learn

  • What counts as a secret and where it must live
  • Encryption in transit and at rest
  • Symmetric and asymmetric encryption, hashing and signing: which is which
  • Encrypting data in the application with AES-GCM
  • Key management and envelope encryption
  • Least privilege everywhere
On this page

Secrets

Secrets are values that grant access: database passwords, API keys (Stripe, OpenAI), JWT signing keys, OAuth client secrets, encryption keys, private certificates, webhook secrets.

NeverInstead
Commit them to Git (even private repositories).env locally (git-ignored), with a .env.example of placeholders
Put them in front-end code or NEXT_PUBLIC_ variablesKeep them on the server
Bake them into Docker imagesInject at runtime (Lesson 249)
Paste them in chat, tickets or logsShare through a password manager or secrets manager
Share one key across all environmentsSeparate secrets per environment

In production use a secrets manager: AWS Secrets Manager (supports automatic rotation for RDS), SSM Parameter Store, HashiCorp Vault, Doppler, 1Password. The app reads secrets at start-up through its IAM role (Lesson 252).

If a secret leaks: rotate it immediately (create a new one, deploy, revoke the old), then investigate usage. Removing it from Git history is not enough. Enable secret scanning to catch leaks before they are pushed.

Encryption in transit and at rest

In transitAt rest
ProtectsData moving over networksStored data: disks, databases, backups, files
HowTLS everywhere: browser to server, server to database (sslmode=require or stricter), service to serviceDisk and database encryption (RDS, S3 and EBS encryption with KMS keys), encrypted backups
Protects againstEavesdropping, tampering on networksStolen disks or backups, some insider and cloud-level risks

At-rest encryption managed by the platform does not protect against an attacker who gets in through your application (SQL injection still reads decrypted data). For very sensitive fields (national insurance numbers, health data, bank details), add application-level encryption of those fields.

Which tool for which job

ToolReversible?KeysUse for
Hashing (SHA-256)NoNoneChecksums, file integrity, deduplication
Password hashing (Argon2id, scrypt, bcrypt)No, deliberately slowSalt per passwordPasswords (Lesson 201)
HMACNoShared secretProving a message came from someone with the secret: webhooks, signed URLs, cookies
Symmetric encryption (AES-256-GCM)YesOne shared keyEncrypting data you must read back
Asymmetric encryption (RSA, elliptic curves)YesPublic key encrypts, private key decryptsKey exchange, encrypting to someone without a shared secret
Digital signatures (Ed25519, ECDSA, RSA)Verify onlyPrivate key signs, public key verifiesJWTs (RS256/ES256), software releases, documents
Encoding (Base64, hex)Yes, no keyNoneRepresenting bytes as text. Not security

Common interview trap: "Base64 is encryption." It is not; anyone can decode it.

Encrypting fields with AES-GCM

AES-256-GCM is the standard modern symmetric choice: it provides confidentiality (nobody can read it) and integrity (any change is detected) at once ("authenticated encryption").

TypeScript
import { createCipheriv, createDecipheriv, randomBytes } from "node:crypto";

export function encryptField(plaintext: string, key: Buffer, associatedData = ""): string {
  if (key.length !== 32) throw new Error("Key must be 32 bytes for AES-256");
  const iv = randomBytes(12);
  const cipher = createCipheriv("aes-256-gcm", key, iv);
  cipher.setAAD(Buffer.from(associatedData, "utf8"));
  const ciphertext = Buffer.concat([cipher.update(plaintext, "utf8"), cipher.final()]);
  const tag = cipher.getAuthTag();
  return ["v1", iv.toString("base64"), tag.toString("base64"), ciphertext.toString("base64")].join(".");
}

export function decryptField(payload: string, key: Buffer, associatedData = ""): string {
  const [version, ivB64, tagB64, dataB64] = payload.split(".");
  if (version !== "v1" || !ivB64 || !tagB64 || dataB64 === undefined) throw new Error("Unsupported payload");
  const decipher = createDecipheriv("aes-256-gcm", key, Buffer.from(ivB64, "base64"));
  decipher.setAAD(Buffer.from(associatedData, "utf8"));
  decipher.setAuthTag(Buffer.from(tagB64, "base64"));
  return Buffer.concat([decipher.update(Buffer.from(dataB64, "base64")), decipher.final()]).toString("utf8");
}

Key points:

  • A new random IV (nonce) for every encryption. Reusing an IV with the same key in GCM is catastrophic: it can reveal data and allow forgeries.
  • The authentication tag is checked on decryption; if anyone changes one bit of the ciphertext, decryption throws instead of returning garbage.
  • Associated data (here, for example, the user ID) is not encrypted but is bound to the ciphertext: an attacker cannot copy user A's encrypted field into user B's row, because decryption with B's ID fails.
  • A version prefix (v1) allows changing algorithms or keys later.

Tested: encrypting the same text twice gave different outputs (random IVs); decryption returned the original; changing one character of the ciphertext, using the wrong key, or using a different associated data value made decryption throw.

Key management

The encryption is only as safe as the key:

  • Do not store the key next to the data (not in the same database, not in code).
  • Use a KMS (AWS KMS, Google Cloud KMS, Azure Key Vault): keys stay inside hardware security modules; your app asks KMS to encrypt or decrypt, with IAM controlling who may, and every use is logged in CloudTrail.
  • Envelope encryption: KMS generates a data key; you encrypt data locally with the data key and store the data key encrypted by the KMS key next to the data. To decrypt, ask KMS to decrypt the data key. Fast, and the master key never leaves KMS. S3 and RDS encryption work this way.
  • Rotate keys: new data uses the new key; old data can be re-encrypted over time (the version prefix helps).
  • Use proven libraries and algorithms. Never invent your own cryptography, and avoid outdated options (MD5 and SHA-1 for security, DES, ECB mode, RSA without proper padding).

Least privilege everywhere

Give every identity only the access it needs, for only as long as it needs it:

LayerPractice
CloudNarrow IAM roles per service (Lesson 252); no shared admin keys
DatabaseThe app user can read and write its tables but not create users or drop tables; migrations run with a separate, more powerful user; read-only users for reporting
Operating system and containersRun as non-root (Lessons 247 and 249); read-only filesystems where possible
NetworkOnly required ports open; databases in private subnets (Lesson 257)
ApplicationRole and permission checks (Lesson 203); scoped API keys with expiry
PeopleLeast privilege for staff, temporary elevated access for production, MFA, removal of access when people leave
CI/CDWorkflow permissions limited; OIDC roles scoped to repository and branch (Lesson 251)

Least privilege limits the blast radius: when one part is compromised (and eventually something will be), the attacker cannot reach everything.

How to say it in an interview

"Secrets never go in Git, front-end code or images; they live in a secrets manager and are read at runtime through the service's IAM role, separate per environment, and anything leaked is rotated immediately. I encrypt in transit with TLS everywhere including to the database, and at rest with KMS-backed storage encryption, adding application-level AES-256-GCM for very sensitive fields with a fresh random IV each time, associated data binding the ciphertext to its record, and keys managed in KMS with envelope encryption and rotation. I distinguish hashing, password hashing, HMAC, encryption, signatures and plain encoding. And I apply least privilege at every layer to limit the blast radius of any compromise."

Key words

WordMeaning
SecretA value that grants access
Secrets managerA secure store for secrets with access control and rotation
Encryption in transit / at restProtecting data moving / stored
AES-256-GCMAuthenticated symmetric encryption
IV / nonceA unique value per encryption
Authentication tagDetects any change to encrypted data
KMSA managed service that keeps and uses encryption keys
Envelope encryptionData encrypted with a data key, itself encrypted by a master key
Blast radiusHow much damage one compromise can do

Now prove it

This lesson is complete when you pass the quiz and all three practice levels.