Data Protection and Encryption

WhereHow
In transitTLS 1.2+ everywhere: client → LB → app → DB → other services
At restDisk/DB encryption (RDS, EBS, S3 SSE), plus field-level encryption for very sensitive fields
PasswordsHash, never encrypt (argon2/bcrypt, see 01)
Tokens to look up (API keys, reset tokens)Store a SHA-256 hash, compare hashes

Hashing = one way (passwords). Encryption = two way (data you need to read back).

Packages

PackageUse
crypto (built into Node)AES-256-GCM, random bytes, HMAC, timing-safe compare
@aws-sdk/client-kmsEnvelope encryption, key management
libsodium-wrappersEasy, hard-to-misuse crypto

Never write your own crypto algorithm. Use AES-GCM or libsodium.

✅ Field encryption with AES-256-GCM

const crypto = require('crypto');
const KEY = Buffer.from(process.env.DATA_KEY, 'hex'); // 32 bytes, from a secret manager / KMS

function encrypt(plain) {
  const iv = crypto.randomBytes(12);                       // new IV every time
  const c = crypto.createCipheriv('aes-256-gcm', KEY, iv);
  const enc = Buffer.concat([c.update(plain, 'utf8'), c.final()]);
  return Buffer.concat([iv, c.getAuthTag(), enc]).toString('base64');
}

function decrypt(b64) {
  const buf = Buffer.from(b64, 'base64');
  const d = crypto.createDecipheriv('aes-256-gcm', KEY, buf.subarray(0, 12));
  d.setAuthTag(buf.subarray(12, 28));                      // detects tampering
  return Buffer.concat([d.update(buf.subarray(28)), d.final()]).toString('utf8');
}

✅ Store tokens hashed + timing-safe compare

const token = crypto.randomBytes(32).toString('hex');               // send to the user
const tokenHash = crypto.createHash('sha256').update(token).digest('hex'); // store this

const a = Buffer.from(hashOfInput), b = Buffer.from(storedHash);
const ok = a.length === b.length && crypto.timingSafeEqual(a, b);   // not ===

Privacy (GDPR / India DPDP Act)

  • Data minimization: don't collect what you don't need
  • Masking: show XXXX-XXXX-1234, log a***@gmail.com
  • Retention: delete old data automatically
  • Right to delete / export: build these endpoints
  • Payments: never store card numbers; use Stripe/Razorpay tokens (PCI DSS)

Checklist

  • HTTPS everywhere, including internal traffic and DB connections (sslmode=require)
  • Encryption at rest enabled on DB, disks, backups and buckets
  • Field encryption for PII such as Aadhaar/PAN/SSN or health data
  • Keys in KMS / a secret manager, with a rotation plan
  • crypto.randomBytes for tokens, never Math.random()
  • Hash stored tokens and API keys