devHọc Dev

Week 2 - Day 7: TLS/HTTPS and Encryption at Rest & in Transit

Week 2 – Day 7

This lesson combines 2 topics: TLS / HTTPS, Encryption at Rest & in Transit.

Learning Objectives

  • Understand why HTTPS is mandatory for every web app (eavesdropping, MITM, integrity)
  • Learn the TLS handshake and compare TLS 1.2 with TLS 1.3
  • Distinguish cipher suites, key exchange (ECDHE), and forward secrecy
  • Understand the certificate chain: root CA → intermediate → leaf, and how browsers verify it
  • Know Let's Encrypt and the ACME protocol, with auto-renew via certbot/Caddy
  • Understand HSTS preload and why HPKP was deprecated
  • Learn the basics of mTLS (mutual TLS) for service-to-service auth
  • Distinguish symmetric (AES-256-GCM) and asymmetric encryption (RSA, ECC), and when to use each
  • Understand the envelope encryption pattern: DEK + KEK, and how KMS works
  • Compare AWS KMS, GCP KMS, and Azure Key Vault, with IAM-controlled key access
  • Know database encryption at rest: TDE (Transparent Data Encryption) vs application-level
  • Understand E2EE (end-to-end encryption) at a basic level, with an intro to the Signal protocol
  • Avoid common mistakes: ECB mode, hardcoded keys, weak IVs, using RSA to encrypt large data

Part 1: TLS / HTTPS

1. Why HTTPS is mandatory

The three threats HTTPS defends against

Browser──►HTTPplaintext──►ServerAnyonesittingonthispathcan:├──1.Eavesdropping:readpasswords,cookies,content├──2.MITM(man-in-the-middle):impersonatetheserver,harvestsecrets└──3.Tampering:modifytheresponse(injectmalware,ads)

Each threat in detail

ThreatReal-world exampleHTTPS addresses it with
EavesdroppingPublic Wi-Fi sniffs HTTP traffic and steals the session cookieEncryption (symmetric cipher)
MITMISP/coffee shop sits in the middle and fakes server responsesServer authentication (certificate)
TamperingISP injects ads into HTML, malware into JSIntegrity (MAC/AEAD)

Bonus: User trust

  • Browsers show "Not Secure" on HTTP → users lose trust
  • Some browser APIs only work over HTTPS: Service Worker, WebRTC, Geolocation, Notifications, Web Crypto, HTTP/2, HTTP/3
  • SEO: Google ranks HTTPS sites higher

2. TLS handshake — TLS 1.2 vs TLS 1.3

TLS 1.2 (2008)

ClientServer│││────────────ClientHello────────────────────►││(supportedciphersuites,random,SNI)││││◄───────────ServerHello─────────────────────││Certificate││ServerKeyExchange││ServerHelloDone││││────ClientKeyExchange──────────────────────►││ChangeCipherSpec││Finished││││◄────ChangeCipherSpec───────────────────────││Finished││││════════ApplicationData(encrypted)═══════►││◄════════ApplicationData(encrypted)═══════│2round-trips(2RTT)beforedatacanbesent

TLS 1.3 (2018)

ClientServer│││────────────ClientHello────────────────────►││(cipher,random,SNI,key_share,ALPN)││││◄───────────ServerHello─────────────────────││{EncryptedExtensions}││{Certificate}││{CertificateVerify}││{Finished}││││────{Finished}─────────────────────────────►││────ApplicationData(encrypted)───────────►││◄────ApplicationData(encrypted)───────────│1round-trip(1RTT)—50%faster0-RTTonsessionresumption(earlydata,withreplayrisk)

Comparison table

PropertyTLS 1.2TLS 1.3
Release year20082018 (RFC 8446)
Handshake RTT2 RTT1 RTT (0-RTT on resume)
Cipher suites~37 suites, many legacy5 suites, AEAD only
Key exchangeRSA, DH, ECDHE(EC)DHE only — forward secrecy mandatory
Forward secrecyOptionalMandatory
Legacy cryptoAllows RC4, 3DES, MD5, SHA-1Removed entirely
Encrypted handshakeNo (Certificate sent in plaintext)Yes (from EncryptedExtensions onward)

3. Cipher suite

A cipher suite defines the algorithms used in a TLS connection.

TLS 1.2 cipher suite name

TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384│││││││││└──PRF/MAC:SHA384│││└──────────Encryption:AES-256-GCM(AEAD)││└──────────────(legacy,notusedforAEAD)│└──────────────────────Authentication:RSAsignature└────────────────────────────Keyexchange:ECDHE(forwardsecrecy)

TLS 1.3 cipher suites (much shorter)

TLS_AES_256_GCM_SHA384              ← bulk + HKDF
TLS_CHACHA20_POLY1305_SHA256        ← for ARM/mobile (no AES-NI)
TLS_AES_128_GCM_SHA256

In TLS 1.3, key exchange and signature are not part of the cipher suite; they are negotiated separately (signature algorithm extension).

Cipher recommendations (2024-2025)

GOOD (TLS 1.3):
  TLS_AES_256_GCM_SHA384
  TLS_AES_128_GCM_SHA256
  TLS_CHACHA20_POLY1305_SHA256

GOOD (TLS 1.2):
  ECDHE-ECDSA-AES256-GCM-SHA384
  ECDHE-RSA-AES256-GCM-SHA384
  ECDHE-ECDSA-CHACHA20-POLY1305

BAD — disable:
  - Anything with RC4, 3DES, DES, MD5, SHA-1, NULL
  - Static RSA key exchange (no forward secrecy)
  - TLS 1.0, TLS 1.1, SSL 3.0, SSL 2.0

4. Forward Secrecy

The idea

If the server private key is compromised in the future, previously recorded traffic cannot be decrypted.

Without forward secrecy (RSA key exchange):
   Client encrypts the session key with the server public key → sends it over the network
   Attacker records the traffic
   1 year later: the server private key leaks
   Attacker decrypts the old session keys → decrypts all old traffic

With forward secrecy (ECDHE):
   Client + Server derive the session key via ephemeral Diffie-Hellman
   Each session gets a new key pair, discarded after the handshake
   The server long-term key is only used to SIGN, not to encrypt the session key
   Server key leak → does NOT help decrypt old traffic

Simplified ECDHE flow

1. Server has a long-term key pair (RSA or ECDSA) for IDENTITY (sign)
2. On every handshake:
   - Server creates an ephemeral EC key pair (eS_priv, eS_pub)
   - Client creates an ephemeral EC key pair (eC_priv, eC_pub)
   - They exchange public keys
   - Both compute: shared_secret = ECDH(eS_priv, eC_pub) = ECDH(eC_priv, eS_pub)
   - Server SIGNS the ephemeral pub key with its long-term key (proves identity)
3. After the handshake: discard eS_priv, eC_priv → nobody can recreate shared_secret

TLS 1.3 mandates forward secrecy, which is why RSA key exchange was removed entirely.

5. Certificate chain

Trust structure

┌────────────────────────────────────────────────────┐│RootCA(self-signed,intheOS/browserstore)││e.g.ISRGRootX1,DigiCertGlobalRoot│└──────────────────────┬─────────────────────────────┘│sign▼┌────────────────────────────────────────────────────┐│IntermediateCA││e.g.Let'sEncryptR3,DigiCertTLSRSASHA256│└──────────────────────┬─────────────────────────────┘│sign▼┌────────────────────────────────────────────────────┐│Leafcertificate(servercertificate)││CN:example.comSAN:*.example.com,www.exam...│└────────────────────────────────────────────────────┘

How does the browser verify it?

1. Server sends: [leaf cert, intermediate cert] in ServerHello
2. Browser:
   a. Reads the leaf cert → checks whether the Subject Alt Name matches the hostname
   b. Checks the leaf cert is still valid (notBefore < now < notAfter)
   c. Verifies the intermediate's signature on the leaf
   d. Takes the intermediate cert → verifies the root's signature on the intermediate
   e. The root cert must be in the OS/browser trust store
   f. Checks revocation:
      - CRL (Certificate Revocation List) — list of revoked certs
      - OCSP (Online Certificate Status Protocol)
      - OCSP stapling — the server attaches the OCSP response
3. If every step passes → "Secure" lock icon

Checking the chain with openssl

# Get the certificate chain from the server
openssl s_client -connect example.com:443 -showcerts

# Verify chain
openssl s_client -connect example.com:443 -CApath /etc/ssl/certs

# Print leaf cert details
echo | openssl s_client -connect example.com:443 2>/dev/null | \
  openssl x509 -text -noout

# Check expiration
echo | openssl s_client -connect example.com:443 2>/dev/null | \
  openssl x509 -enddate -noout
# notAfter=Mar 15 23:59:59 2026 GMT

Common chain errors

ErrorSymptomCause
unable to get local issuer certificateBrowser/curl does not trust the certServer does not send the intermediate cert
NET::ERR_CERT_DATE_INVALIDCert expiredForgot to renew
NET::ERR_CERT_COMMON_NAME_INVALIDHostname mismatchCN/SAN does not include the domain being accessed
NET::ERR_CERT_AUTHORITY_INVALIDBrowser does not trust the rootSelf-signed cert or root not in the store

6. Let's Encrypt and the ACME protocol

What is Let's Encrypt

A free, automated CA backed by the Internet Security Research Group (ISRG). Certs are valid for 90 days, and renewing after 60 days is recommended.

ACME protocol (RFC 8555)

Client(certbot)ACMEserver(Let'sEncrypt)certbot──►1.Neworder:example.com──►ACMEcertbot◄──2.Challenge(HTTP-01orDNS-01)◄──ACME3.Clientanswersthechallenge:HTTP-01:serveafileathttp://example.com/.well-known/acme-challenge/TOKENDNS-01:addaTXTrecordtoDNScertbot──►4.Notifyready──►ACMEcertbot◄──5.Verifychallenge(fetchURL/DNS)◄──ACMEcertbot──►6.CSR(certificatesigningreq)──►ACMEcertbot◄──7.Cert+chain◄──ACME

certbot — the most common approach

# Install certbot
sudo apt install certbot python3-certbot-nginx

# Standalone (cert + nginx config auto)
sudo certbot --nginx -d example.com -d www.example.com

# DNS-01 (for wildcard certs)
sudo certbot certonly --manual --preferred-challenges dns -d "*.example.com"

# Auto-renew (cron is set up automatically)
sudo certbot renew --dry-run

Default cron job:

0 */12 * * * root certbot renew --quiet

Caddy — the simplest

# Caddyfile
example.com {
    reverse_proxy localhost:3000
}

That's it. Caddy obtains the Let's Encrypt cert, renews it, redirects HTTP→HTTPS, and configures HTTPS correctly on its own. No nginx + certbot dance needed.

nginx + certbot snippet

server {
    listen 443 ssl http2;
    server_name example.com;

    ssl_certificate     /etc/letsencrypt/live/example.com/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;

    ssl_protocols TLSv1.2 TLSv1.3;
    ssl_prefer_server_ciphers off;
    ssl_session_cache shared:SSL:10m;
    ssl_session_timeout 1d;

    # HSTS
    add_header Strict-Transport-Security "max-age=31536000; includeSubDomains; preload" always;

    location / {
        proxy_pass http://localhost:3000;
    }
}

# Redirect HTTP → HTTPS
server {
    listen 80;
    server_name example.com;
    return 301 https://$host$request_uri;
}

7. HSTS and HPKP

HSTS (HTTP Strict Transport Security)

Response header:
Strict-Transport-Security: max-age=31536000; includeSubDomains; preload

Meaning: "Browser, for the next year, only connect to me over HTTPS — even if the user types http://".

HSTS preload list

The first-visit problem: on the very first visit, the browser has not seen the HSTS header yet → it can be MITM'd over HTTP. The fix: the preload list.

1. The site registers at https://hstspreload.org
2. Chrome, Firefox, Safari ship the HSTS preload list built into the browser
3. Even on the first visit, the browser auto-upgrades HTTP→HTTPS

Preload requirements:

  • Valid cert
  • HTTPS works across the whole domain and all subdomains
  • max-age >= 31536000 (1 year)
  • includeSubDomains; preload directive

Warning: preload is hard to undo. If a few months later you want to turn off HTTPS on some subdomain, you have to wait months for it to be removed from the list.

HPKP (HTTP Public Key Pinning) — deprecated

The idea: the server sends a header pinning a public key. The browser remembers the pin and rejects any cert that does not match.

Public-Key-Pins: pin-sha256="base64=="; max-age=2592000;

Why was it deprecated (2017)?

  1. Big foot-gun: pin the wrong key → the site becomes inaccessible to users who visited before, even after the cert is reissued. Some sites locked themselves out for months.
  2. Ransomware vector: an attacker temporarily compromises the server → pins a fake key → the server cannot recover.
  3. Certificate Transparency (CT) arrived and solved most of the "rogue CA" problem HPKP targeted.

Chrome dropped HPKP support in 2018. Replacements: the Expect-CT header (now also deprecated) and the CAA DNS record.

CAA record — today's line of defense

example.com.    IN  CAA  0 issue "letsencrypt.org"
example.com.    IN  CAA  0 issuewild ";"
example.com.    IN  CAA  0 iodef "mailto:security@example.com"

Meaning: only Let's Encrypt may issue certs for example.com. Every CA that follows the CA/Browser Forum baseline must check CAA before issuing.

8. mTLS (mutual TLS)

Regular TLS vs mTLS

Regular TLS:
   Client verifies Server identity (via cert)
   Server does not verify Client identity
   → App-level auth (cookie, JWT, OAuth) to know who the client is

mTLS:
   Client verifies Server identity
   Server also verifies Client identity (via client cert)
   → Auth right at the transport layer, no app-level token needed

When to use mTLS

  • Service-to-service in microservices (e.g. service mesh — Istio, Linkerd)
  • B2B APIs between companies (certs instead of a shared secret)
  • IoT — devices with individual certs, where username/password does not fit
  • Zero Trust networks — every connection must authenticate, including internal ones

Simple mTLS setup with nginx

server {
    listen 443 ssl;
    server_name api.example.com;

    ssl_certificate     /etc/ssl/server.crt;
    ssl_certificate_key /etc/ssl/server.key;

    # Require a client cert
    ssl_client_certificate /etc/ssl/ca.crt;   # CA trusted for client certs
    ssl_verify_client on;                      # client cert is mandatory

    location / {
        # Forward client cert info to the upstream
        proxy_set_header X-Client-CN $ssl_client_s_dn_cn;
        proxy_set_header X-Client-Cert $ssl_client_escaped_cert;
        proxy_pass http://backend;
    }
}

Service mesh: auto mTLS

In Kubernetes with Istio/Linkerd:

apiVersion: security.istio.io/v1beta1
kind: PeerAuthentication
metadata:
  name: default
spec:
  mtls:
    mode: STRICT

Istio injects a sidecar (Envoy) into each pod. The sidecar handles the TLS handshake with a cert issued by the Istio CA. App code does not need to know about TLS — Envoy takes care of everything.

Client cert authentication pattern in code (Node.js)

import https from "node:https";

const options = {
  hostname: "api.partner.com",
  port: 443,
  path: "/data",
  method: "GET",
  cert: fs.readFileSync("./client-cert.pem"),
  key:  fs.readFileSync("./client-key.pem"),
  ca:   fs.readFileSync("./partner-ca.pem"),  // verify server
};

const req = https.request(options, (res) => {
  console.log(`Status: ${res.statusCode}`);
});
req.end();

Part 2: Encryption at Rest & in Transit

1. Symmetric vs Asymmetric

SYMMETRIC─────────AsinglekeyforbothencryptionanddecryptionA──[key]──►B(samekeytoencryptanddecrypt)Fast(GB/s),hardtosharethekeysafelyoverthenetworkAlgorithm:AES,ChaCha20ASYMMETRIC──────────A(public_key,private_key)pairA──[pub_keyencrypt]──►B──[priv_keydecrypt]──►plaintext(orsignwithpriv_key,verifywithpub_key)Slow(KB/s—100-1000xslower),public_keycanbesharedopenlyAlgorithm:RSA,ECC(Curve25519,P-256)

Trade-offs and use cases

CriterionSymmetric (AES)Asymmetric (RSA/ECC)
SpeedVery fastSlow
Key size128/256 bit2048-4096 bit (RSA), 256 bit (ECC)
Encrypting large dataYesNO — only short keys
Key distributionHard (needs a secure channel)Easy (public key shared openly)
Main use caseBulk encryption (files, network)Key exchange, digital signature

Why do real systems use both (hybrid)?

TLS is the example:

  • ECDHE (asymmetric, slow) only negotiates the session key
  • AES-256-GCM (symmetric, fast) encrypts the actual data

Asymmetric solves "how do we share a key safely", symmetric does the heavy lifting.

2. AES-GCM — the modern standard AEAD

Block cipher mode

ECB(ElectronicCodeBook)—NEVERUSEblock_1──encrypt──►ciphertext_1block_2──encrypt──►ciphertext_2(sameasblock_1→identicalciphertext)block_3──encrypt──►ciphertext_3CBC(CipherBlockChaining)—legacy,haspaddingoracleissuesIVXORblock_1──encrypt──►c_1c_1XORblock_2──encrypt──►c_2...GCM(Galois/CounterMode)—RECOMMENDEDcounter_0──encrypt──►XORblock_1=c_1counter_1──encrypt──►XORblock_2=c_2...+GMACtag(authentication)

Why ECB is the classic disaster

Original image (Tux):         After AES-ECB encryption:
████████████████              █▒█▓█▒▓█▒█▓█▒
█        ████                 ▒▓▒    ▓███
█        ████                 ▒▓▒    ▓███
█        ████                 ▒▓▒    ▓███
████████████████              █▒█▓█▒▓█▒█▓█▒

→ The pattern is clearly visible! Same plaintext block → same ciphertext block.

ECB is the most basic mistake in cryptography. Every modern mode (CBC, GCM, XTS) uses a random IV (Initialization Vector) so the same plaintext produces different ciphertext.

AES-GCM in Node.js

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

function encrypt(plaintext, key) {
  // KEY: 32 bytes (256 bit), secret
  // IV: 12 random bytes (96 bit), must NOT be reused with the same key
  const iv = randomBytes(12);
  const cipher = createCipheriv("aes-256-gcm", key, iv);

  const encrypted = Buffer.concat([cipher.update(plaintext, "utf8"), cipher.final()]);
  const authTag = cipher.getAuthTag();  // 16 bytes

  // Store: iv + authTag + ciphertext (iv and tag do NOT need to be secret)
  return Buffer.concat([iv, authTag, encrypted]);
}

function decrypt(data, key) {
  const iv = data.subarray(0, 12);
  const authTag = data.subarray(12, 28);
  const ciphertext = data.subarray(28);

  const decipher = createDecipheriv("aes-256-gcm", key, iv);
  decipher.setAuthTag(authTag);

  return Buffer.concat([decipher.update(ciphertext), decipher.final()]).toString("utf8");
  // If authTag mismatches → throws → you know the data was tampered with
}

IV/Nonce rules

RULE: With the same key, an IV/nonce must NOT be reused.
      Reusing an IV in GCM = catastrophic, the attacker can recover the key stream.

Correct ways to generate an IV:
1. Random 96-bit (for GCM) — enough entropy if < 2^32 messages with the same key
2. Counter (incremented per message) — needs synchronization

WRONG ways to generate an IV:
- Hardcoded "000000000000"
- Derived from a low-resolution timestamp
- Reusing an old IV

3. Asymmetric: RSA and ECC

RSA

Key generation:
  - Pick 2 large primes p, q
  - n = p * q  (modulus)
  - pick e (public exponent, usually = 65537)
  - compute d (private exponent)
  - public_key = (n, e), private_key = (n, d)

Encrypt: c = m^e mod n
Decrypt: m = c^d mod n
  • Recommended key size: 3072 bit (~128-bit security). RSA-2048 is still acceptable but will be phased out.
  • Padding: you MUST use OAEP (Optimal Asymmetric Encryption Padding). PKCS#1 v1.5 padding is vulnerable (Bleichenbacher attack).
  • Limit: RSA-3072 can only encrypt a block ≤ 384 bytes (the modulus size) — with OAEP-SHA256, at most ~318 bytes of plaintext after padding. Never use RSA to encrypt real data; only use it to encrypt a symmetric key.

ECC (Elliptic Curve Cryptography)

Common curves:
  - secp256r1 / P-256 / NIST P-256 (TLS, web standard)
  - secp384r1 / P-384
  - Curve25519 (Signal, modern, safer than NIST curves)
  - Curve448 (high security)
  • ECC-256 ≈ RSA-3072 in security level
  • Much smaller keys → good for mobile/IoT
  • Faster operations than RSA
  • Ed25519 for signatures, X25519 for key exchange — the new standard

Comparison

RSA-3072ECDSA P-256Ed25519
Public key size384 bytes64 bytes32 bytes
Sign speedSlowMediumVery fast
Verify speedFastMediumVery fast
Security level~128-bit~128-bit~128-bit
RecommendedOKOKBest (for new projects)

4. Envelope Encryption — how KMS works

The problem with using KMS directly

If every byte of data calls KMS encrypt:
- KMS has a rate limit (~10,000 req/s)
- High latency (10-50ms per call)
- High cost ($0.03/10,000 requests)
- KMS is not designed to encrypt large data (4 KB limit)

Envelope encryption pattern

Envelopeencryption│├──KEK(KeyEncryptionKey)—NEVERleavesKMS│└──livesinaHardwareSecurityModule(HSM)│├──DEK(DataEncryptionKey)—AES-256,ephemeral│├──ciphertext_DEK=encrypt(KEK,DEK)→storedwiththedata│└──plaintextDEKexistsonlyinappmemory│└──Actualdata(canbeGBs)└──ciphertext=AES-256-GCM(plaintext_DEK,data)

Encrypt flow

1. App calls KMS GenerateDataKey(KeyId="my-kek", KeySpec=AES_256)
2. KMS returns:
   - plaintext_DEK   (32 bytes — exists only in app memory)
   - ciphertext_DEK  (the DEK encrypted with the KEK inside KMS)
3. App encrypts the data:
   encrypted_data = AES-256-GCM(plaintext_DEK, data)
4. App writes to storage:
   { ciphertext_DEK, iv, authTag, encrypted_data }
5. App WIPES plaintext_DEK from memory (zeroize)

Decrypt flow

1. App reads { ciphertext_DEK, iv, authTag, encrypted_data } from storage
2. App calls KMS Decrypt(CiphertextBlob=ciphertext_DEK)
   → KMS checks IAM, decrypts with the KEK, returns plaintext_DEK
3. App decrypts the data:
   data = AES-256-GCM-decrypt(plaintext_DEK, iv, authTag, encrypted_data)
4. App WIPES plaintext_DEK from memory

Benefits

  • Performance: KMS is called only once per object (encrypting a key, 4 KB limit), not for every byte
  • Caching: you can cache the DEK in memory for multiple objects within a session
  • Key rotation: rotating the KEK in KMS does not require re-encrypting data — only the DEK needs re-encrypting (fast)
  • Audit: KMS logs every Decrypt call → you know who accessed the data and when

Code example (AWS KMS + Node.js)

import { KMSClient, GenerateDataKeyCommand, DecryptCommand } from "@aws-sdk/client-kms";
import { createCipheriv, createDecipheriv, randomBytes } from "node:crypto";

const kms = new KMSClient({ region: "ap-southeast-1" });
const KEY_ID = "alias/my-app-kek";

async function encryptObject(plaintext) {
  // Step 1: Generate DEK
  const { Plaintext: dek, CiphertextBlob: encryptedDek } = await kms.send(
    new GenerateDataKeyCommand({ KeyId: KEY_ID, KeySpec: "AES_256" })
  );

  // Step 2: Encrypt data with the DEK
  const iv = randomBytes(12);
  const cipher = createCipheriv("aes-256-gcm", dek, iv);
  const ciphertext = Buffer.concat([cipher.update(plaintext, "utf8"), cipher.final()]);
  const authTag = cipher.getAuthTag();

  // Step 3: Return the envelope (encrypted DEK + ciphertext)
  return {
    encryptedDek: Buffer.from(encryptedDek).toString("base64"),
    iv: iv.toString("base64"),
    authTag: authTag.toString("base64"),
    ciphertext: ciphertext.toString("base64"),
  };
}

async function decryptObject(envelope) {
  // Step 1: Decrypt the DEK with KMS
  const { Plaintext: dek } = await kms.send(
    new DecryptCommand({
      CiphertextBlob: Buffer.from(envelope.encryptedDek, "base64"),
    })
  );

  // Step 2: Decrypt data with the DEK
  const decipher = createDecipheriv("aes-256-gcm", dek, Buffer.from(envelope.iv, "base64"));
  decipher.setAuthTag(Buffer.from(envelope.authTag, "base64"));
  return Buffer.concat([
    decipher.update(Buffer.from(envelope.ciphertext, "base64")),
    decipher.final(),
  ]).toString("utf8");
}

5. KMS comparison: AWS, GCP, Azure

PropertyAWS KMSGCP Cloud KMSAzure Key Vault
AuthIAMGCP IAMAzure AD / Managed Identity
HSMFIPS 140-3 Level 3 (before 2023: 140-2 Level 2)FIPS 140-2 Level 3 (HSM keys)FIPS 140-2 Level 2 (Level 3 with Managed HSM)
BYOK (Bring Your Own Key)Yes (import)YesYes
Hold Your Own Key (HYOK)XKS (External Key Store)EKM (External Key Manager)Managed HSM + customer key
Key rotationAuto (1 year) for symmetricAuto (configurable)Auto (configurable)
Cross-regionMulti-region keysMulti-region keyringGeo-replicated vault
Pricing$1/key/month + API calls$0.06/key version/month + API calls$0.03/10K transactions, premium tier has HSM

IAM-controlled key access

// AWS KMS key policy — who is allowed to use this key
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Sid": "AllowAppRoleToUseKey",
      "Effect": "Allow",
      "Principal": { "AWS": "arn:aws:iam::123456789012:role/app-role" },
      "Action": [
        "kms:Encrypt",
        "kms:Decrypt",
        "kms:GenerateDataKey",
        "kms:DescribeKey"
      ],
      "Resource": "*"
    },
    {
      "Sid": "DenyAuditorFromDecrypt",
      "Effect": "Deny",
      "Principal": { "AWS": "arn:aws:iam::123456789012:role/auditor" },
      "Action": "kms:Decrypt",
      "Resource": "*"
    }
  ]
}

The key policy and IAM policy are evaluated together. By default a KMS key only grants permission to the root account → you must grant access explicitly.

6. Database encryption at rest

Three layers of encryption

Application-levelencryption←youencryptintheappbeforesaving│▼┌──────────────────────────────────┐│Database││┌────────────────────────────┐│││TDE—TransparentData││←theDBencryptsitself,theappisunaware││Encryption│││└────────────────────────────┘│└────────────┬─────────────────────┘▼┌──────────────────────────────────┐│Disk/EBSvolume│←Filesystem-level/diskencryption│(full-diskencryption)│└──────────────────────────────────┘

Comparison table

LayerThreat protectedThreat NOT protected
Full-disk (EBS encryption, LUKS)Stolen diskDB connection compromise, SQL injection, admins viewing data
TDE (DB-level)Stolen backup, stolen diskAnything with app access → reads plaintext as usual
Application-levelAll threats above + DBA viewingApplication bugs that leak

TDE — Transparent Data Encryption

PostgreSQL: pgcrypto extension (column-level), or use RDS encryption (full DB)
MySQL: native TDE since 5.7+
SQL Server: TDE built-in (Enterprise edition)
Oracle: TDE built-in (Advanced Security option)

AWS RDS: tick "Enable encryption" when creating the DB → all storage, snapshots, replicas are encrypted
         Uses an AWS KMS key (default or your own CMK)

TDE protection model:

Disk steal scenario:
   Attacker steals the raw disk → reads the EBS snapshot → encrypted nonsense ✓ Safe

App compromise scenario:
   Attacker SQL injection → SELECT * FROM users → DB decrypt on the fly → plaintext ✗ Not safe

Application-level encryption (column-level)

-- Store the encrypted blob directly in the column
CREATE TABLE users (
  id UUID PRIMARY KEY,
  email TEXT NOT NULL,
  ssn_encrypted BYTEA,           -- AES-256-GCM ciphertext
  ssn_encrypted_dek BYTEA        -- DEK encrypted by KMS
);
// The app encrypts before INSERT
const { encryptedDek, iv, authTag, ciphertext } = await encryptObject(user.ssn);
await db.query(
  "INSERT INTO users (id, email, ssn_encrypted, ssn_encrypted_dek) VALUES ($1, $2, $3, $4)",
  [user.id, user.email, Buffer.concat([iv, authTag, ciphertext]), encryptedDek]
);

// Decrypt only when needed — a DBA querying the DB directly sees only ciphertext

Trade-off:

  • Pros: DBA access and backup compromise do not expose the data
  • Cons: querying/indexing encrypted fields is very hard, latency is higher, complexity grows

Special case: searchable encryption / deterministic encryption

If you need WHERE email = ? on an encrypted column, you can use deterministic encryption (same plaintext → same ciphertext). But deterministic mode leaks patterns (like ECB at the row level) — use it only for lookups, not for the main sensitive data.

7. End-to-End Encryption (E2EE)

Concept

Server-sideencryption(Gmail,Dropbox):Client→TLS→Server(decrypt)→re-encryptatrest→Storage↑TheservercanreadtheplaintextatanytimeE2EE(Signal,WhatsApp,iMessage):ClientAencrypts──────────────────────────►ClientBdecryptsTheserveronlyrelaysciphertext,itcannotdecrypt

Signal Protocol — the de facto standard

Concepts:
- Double Ratchet: every message uses a different key, keys are forward-secret
- X3DH (Extended Triple Diffie-Hellman): async key agreement
- Pre-keys: allow initiating a session while the recipient is offline

Properties achieved:
- Forward secrecy: leaking the current key does not decrypt old messages
- Future secrecy (post-compromise security): a temporarily leaked key → self-heals after a few turns
- Deniability: you cannot prove who sent a specific message
AppE2EE defaultGroup chatBackup E2EE
SignalYesYesYes (PIN-encrypted)
WhatsAppYesYesYes (optional, since 2021)
iMessageYesYesYes (Advanced Data Protection, opt-in)
TelegramNO (Secret Chat only)NONO
SlackNO--
ZoomYes (opt-in since 2020)Limited-

When do developers need to know E2EE?

  • Building sensitive messaging / collaboration apps
  • Building storage apps for users (Standard Notes, Bitwarden, ProtonMail)
  • Healthcare, legal — compliance requires that the provider cannot read the content

Libraries: libsignal, Matrix/Olm, Tink.

8. Common crypto mistakes

1. Using ECB mode

# ❌ DANGEROUS
from Crypto.Cipher import AES
cipher = AES.new(key, AES.MODE_ECB)
ciphertext = cipher.encrypt(pad(plaintext, 16))

# ✅ CORRECT
from Crypto.Cipher import AES
from Crypto.Random import get_random_bytes
nonce = get_random_bytes(12)
cipher = AES.new(key, AES.MODE_GCM, nonce=nonce)
ciphertext, tag = cipher.encrypt_and_digest(plaintext)

2. Hardcoding the key in source

// ❌ DANGEROUS
const KEY = Buffer.from("0123456789abcdef0123456789abcdef", "hex");

// ✅ CORRECT — load from KMS/secret manager
const key = await loadKeyFromKMS();

3. IV/Nonce reuse

// ❌ DANGEROUS — same IV for every message
const IV = Buffer.alloc(12, 0);
const cipher = createCipheriv("aes-256-gcm", key, IV);

// ✅ CORRECT
const iv = randomBytes(12);  // random every time

4. Using RSA to encrypt real data

# ❌ DANGEROUS (can only encrypt a few hundred bytes)
from cryptography.hazmat.primitives.asymmetric import padding
ciphertext = public_key.encrypt(huge_data, padding.OAEP(...))

# ✅ CORRECT — hybrid encryption
# 1. Generate random AES key
# 2. Encrypt data with AES-GCM
# 3. Encrypt the AES key with RSA-OAEP

5. Roll your own crypto

Rule: DO NOT WRITE your own crypto primitives.
Use audited libraries: libsodium, Tink, OpenSSL, BoringSSL, ring (Rust).

6. MD5/SHA-1 for password hashing

// ❌ DANGEROUS — MD5/SHA-1 are broken, not slow, not salted
const hash = createHash("md5").update(password).digest("hex");

// ✅ CORRECT — a dedicated password hash
import { hash, verify } from "@node-rs/argon2";
const hashed = await hash(password);          // argon2id, automatic salt
const ok = await verify(hashed, password);
// Or bcrypt, scrypt, PBKDF2

7. Weak randomness (Math.random, time)

// ❌ DANGEROUS — Math.random is predictable
const token = Math.random().toString(36);

// ✅ CORRECT
import { randomBytes } from "node:crypto";
const token = randomBytes(32).toString("hex");

8. Comparing hashes/MACs with ==

// ❌ DANGEROUS — timing attack
if (computedHmac === providedHmac) { ... }

// ✅ CORRECT — constant-time compare
import { timingSafeEqual } from "node:crypto";
if (timingSafeEqual(Buffer.from(computedHmac), Buffer.from(providedHmac))) { ... }

Review Questions

  1. Why is the TLS 1.3 handshake faster than TLS 1.2?

    Show answer

    TLS 1.3 cuts the handshake from 2 RTT to 1 RTT before the client can send application data, and supports 0-RTT on session resumption. The reason: TLS 1.3 removes the complex two-way negotiation — the client sends key_share right in the ClientHello (guessing the cipher), so the server has enough information to compute the key and return the certificate + Finished together with the ServerHello. TLS 1.3 also encrypts most of the handshake (from EncryptedExtensions onward), improving privacy.

  2. What does forward secrecy mean, and why does TLS 1.3 make it mandatory?

    Show answer

    Forward secrecy: if the server long-term private key is compromised in the future, previously recorded traffic still cannot be decrypted. It is achieved with ephemeral Diffie-Hellman (ECDHE) — each session creates a temporary key pair and discards it after the handshake; the long-term key is used only for signing, not for encrypting the session key.

    TLS 1.3 removes static RSA key exchange (which has no forward secrecy) and allows only (EC)DHE — so forward secrecy is on by default for every connection.

  3. When the browser receives a leaf certificate, how does it verify it to decide it is "trusted"?

    Show answer

    (1) The hostname being accessed must match the cert's Subject Alt Name (SAN). (2) The current time falls between notBefore and notAfter. (3) The intermediate CA's signature on the leaf cert is valid. (4) Walking up the chain: the root CA's signature on the intermediate is valid. (5) The root CA must be in the OS/browser trust store. (6) Revocation is checked via CRL, OCSP, or OCSP stapling.

    If any step fails → the browser shows a "Not Secure" warning.

  4. Why was HPKP deprecated, and what replaced it?

    Show answer

    HPKP let a server pin a public key in the browser — the browser remembers the pin and rejects any cert that does not match. Problems: (1) pinning the wrong key = locking the site away from every user who has visited, with no way to revert during max-age. (2) An attacker who temporarily takes over the server can pin a fake key → ransomware. (3) The benefit was weak compared to the operational risk.

    Replacements: Certificate Transparency (CT logs — every public cert must be logged, making rogue CAs easy to detect) and the CAA DNS record (specifies which CAs may issue certs for a domain). Both are operationally safer than HPKP.

  5. How does mTLS differ from regular TLS, and when should you use it?

    Show answer

    Regular TLS only verifies the identity of the server (via cert). mTLS also verifies the client (the client has a cert too, and the server checks its chain).

    Use mTLS when: (1) service-to-service in microservices/service mesh — auth at the transport layer instead of sharing tokens, (2) B2B APIs between organizations — a cert issued per partner, (3) IoT — devices with individual certs instead of username/password, (4) Zero Trust — every internal connection must still authenticate.

    Trade-off: more complex (cert lifecycle, distribution), not suitable for public-facing user apps (users do not have client certs).

  6. Why do real systems use hybrid encryption (asymmetric + symmetric) rather than just one type?

    Show answer

    Symmetric (AES) is fast and can encrypt large data (GB/s), but has a key distribution problem — how do you share a secret key over an insecure channel? Asymmetric (RSA, ECC) solves key distribution (the public key can be public), but is very slow and can only encrypt small data (a few hundred bytes).

    Hybrid pattern: use asymmetric only to exchange/encrypt a short symmetric key, then use that symmetric key to encrypt the large data. TLS, PGP, S/MIME, and the age tool all use this pattern. Envelope encryption (KMS) is also a variant: the KEK in the HSM is "asymmetric-like" while the DEK is symmetric.

  7. In envelope encryption with AWS KMS, why is this design more efficient than calling kms:Encrypt directly on the data?

    Show answer

    (1) Performance: KMS has a 4 KB/request limit and a rate limit of ~10K req/s. Encrypting a 100 MB object directly is not feasible. With envelope encryption, KMS is called only once to encrypt/decrypt the DEK (32 bytes), and bulk encryption is done locally with AES.

    (2) Cost: KMS requests cost money ($0.03/10K), and envelope encryption significantly reduces the number of KMS requests.

    (3) Key rotation: rotating the KEK in KMS only requires re-encrypting the DEKs (fast), without touching the data. Rotating directly = reading, decrypting, and re-encrypting every byte of data.

    (4) Audit: KMS logs every Decrypt → you can trace who accessed the data and when.

  8. What is the difference between TDE and application-level encryption — and which threats does each protect against or not?

    Show answer

    TDE (Transparent Data Encryption): the DB encrypts when writing to disk and decrypts when reading — the app is unaware. Protects against: stolen disks/snapshots/backups. Does NOT protect: an app/DBA querying the DB directly sees plaintext (the DB decrypts on the fly).

    Application-level: the app encrypts data before INSERT and decrypts after SELECT. Protects: both DBAs and compromised backups see only ciphertext. Trade-off: querying/indexing encrypted fields is very hard, latency is higher.

    Common rule: TDE for every DB (default), plus application-level on top for ultra-sensitive columns (SSN, credit card, health record).

  9. Why is using AES-ECB a basic mistake, and which mode should you use?

    Show answer

    ECB encrypts each block independently, so the same plaintext block → the same ciphertext block. As a result, patterns in the plaintext (e.g. areas of identical pixel color in an image, repeated headers) show through in the ciphertext. The "ECB-encrypted Tux" image is the classic illustration — you can still recognize the penguin after "encryption".

    Use instead: AES-GCM (AEAD — authenticated encryption with associated data) or ChaCha20-Poly1305 for mobile. Both use a random IV/nonce (same plaintext → different ciphertext) and have a MAC tag against tampering. Avoid CBC mode (legacy, prone to padding oracle attacks if implemented incorrectly).

  10. Why is E2EE different from the "encryption at rest + TLS in transit" that SaaS vendors usually advertise as "encrypted"?

Show answer

With encryption at rest + TLS:

  • TLS protects data in transit between client and server
  • At-rest encryption protects data on the server's disk
  • But: the server still decrypts the data in memory to process it → the server can read the plaintext at any time. Service provider employees, a government subpoena, or an attacker who takes over the server can all read it.

E2EE: data is encrypted on the client (e.g. the Signal app on phone A) and only decrypted on the receiving client (phone B). The server only relays ciphertext and is unable to decrypt it — not even Signal/WhatsApp staff can read it.

E2EE trade-off: server-side search/preview/spam filtering becomes much harder, and password recovery usually requires the old device (because the server does not have the key).

Hands-on Exercises

Part 1: TLS / HTTPS

# 1. Inspect a site's cert
openssl s_client -connect github.com:443 -servername github.com < /dev/null 2>/dev/null | \
  openssl x509 -text -noout | head -30

# 2. See which cipher suite is used
openssl s_client -connect github.com:443 < /dev/null 2>&1 | grep -E "Protocol|Cipher"

# 3. Test with TLS 1.3 only
openssl s_client -connect github.com:443 -tls1_3 < /dev/null

# 4. Generate a self-signed cert for local dev
openssl req -x509 -newkey rsa:2048 -keyout key.pem -out cert.pem \
  -sha256 -days 365 -nodes \
  -subj "/CN=localhost" \
  -addext "subjectAltName=DNS:localhost,DNS:127.0.0.1"

# 5. Generate a CA + client cert for an mTLS demo
# Create the CA
openssl genrsa -out ca.key 4096
openssl req -x509 -new -nodes -key ca.key -days 365 -out ca.crt -subj "/CN=My CA"

# Create the client key + CSR
openssl genrsa -out client.key 2048
openssl req -new -key client.key -out client.csr -subj "/CN=client-1"

# CA signs the client CSR
openssl x509 -req -in client.csr -CA ca.crt -CAkey ca.key -CAcreateserial \
  -out client.crt -days 365

# 6. Set up Caddy with auto-HTTPS (needs a real domain + public IP)
cat > Caddyfile <<EOF
example.com {
    reverse_proxy localhost:3000
}
EOF
caddy run

# 7. SSL Labs test (online, comprehensive)
# Open: https://www.ssllabs.com/ssltest/analyze.html?d=your-site.com
# Goal: A+ rating

Part 2: Encryption at Rest & in Transit

# 1. AES-GCM encrypt/decrypt with openssl
echo "Hello secret" | openssl enc -aes-256-gcm -e \
  -K $(openssl rand -hex 32) \
  -iv $(openssl rand -hex 12) \
  -base64

# 2. Generate RSA and ECDSA key pairs
openssl genrsa -out rsa-private.pem 3072
openssl rsa -in rsa-private.pem -pubout -out rsa-public.pem

openssl ecparam -name secp256r1 -genkey -noout -out ec-private.pem
openssl ec -in ec-private.pem -pubout -out ec-public.pem

# 3. Encrypt a file with hybrid encryption (RSA + AES)
openssl rand -out aes.key 32
openssl rand -out aes.iv 16

# Encrypt data
openssl enc -aes-256-cbc -in document.txt -out document.enc \
  -K $(xxd -p aes.key | tr -d '\n') \
  -iv $(xxd -p aes.iv | tr -d '\n')

# Encrypt the AES key with RSA
openssl pkeyutl -encrypt -inkey rsa-public.pem -pubin \
  -in aes.key -out aes.key.enc

# 4. Demo AWS KMS envelope encryption with the CLI
aws kms create-key --description "demo-kek"
KEY_ID=<from output>

# Generate DEK
aws kms generate-data-key --key-id $KEY_ID --key-spec AES_256
# → Plaintext (base64 32 bytes), CiphertextBlob (encrypted DEK)

# 5. Demo password hashing done right
npm install argon2
node -e "
const argon2 = require('argon2');
(async () => {
  const hash = await argon2.hash('mypassword', { type: argon2.argon2id });
  console.log('Hash:', hash);
  console.log('Verify:', await argon2.verify(hash, 'mypassword'));
})();
"

# 6. Check RDS encryption status
aws rds describe-db-instances --query \
  'DBInstances[*].[DBInstanceIdentifier,StorageEncrypted,KmsKeyId]'

References


Next lesson →