3 Hours
15. Encryption & Secure Data Storage
Encryption
Encryption protects sensitive data both at rest (in databases) and in transit. This module covers symmetric encryption (AES), key management, and best practices for storing sensitive data like PII and payment info.
Symmetric Encryption (AES-256-GCM)
AES-256-GCM is the recommended symmetric encryption algorithm. It provides both confidentiality and integrity.
JavaScript
const crypto = require('crypto'); function encrypt(text, secretKey) { const iv = crypto.randomBytes(16); // Initialization vector const cipher = crypto.createCipheriv('aes-256-gcm', secretKey, iv); let encrypted = cipher.update(text, 'utf8', 'hex'); encrypted += cipher.final('hex'); const authTag = cipher.getAuthTag(); return { iv: iv.toString('hex'), encryptedData: encrypted, authTag: authTag.toString('hex') }; } function decrypt(encryptedData, secretKey) { const decipher = crypto.createDecipheriv( 'aes-256-gcm', secretKey, Buffer.from(encryptedData.iv, 'hex') ); decipher.setAuthTag(Buffer.from(encryptedData.authTag, 'hex')); let decrypted = decipher.update(encryptedData.encryptedData, 'hex', 'utf8'); decrypted += decipher.final('utf8'); return decrypted; } // Example const userSSN = '123-45-6789'; const encryptionKey = crypto.randomBytes(32); const encrypted = encrypt(userSSN, encryptionKey); const decrypted = decrypt(encrypted, encryptionKey); console.log(decrypted); // '123-45-6789'
Key points: IV must be random for each encryption. Store IV and authTag with the encrypted data. Never reuse IVs!
Envelope Encryption (Key Management)
Never encrypt data directly with your master key. Use envelope encryption: master key encrypts data keys, data keys encrypt data.
JavaScript
class KeyManagementService { constructor(masterKey) { this.masterKey = masterKey; // Store securely (env variable, KMS) } generateDataKey() { return crypto.randomBytes(32); } encryptDataKey(dataKey) { const iv = crypto.randomBytes(12); const cipher = crypto.createCipheriv('aes-256-gcm', this.masterKey, iv); let encrypted = cipher.update(dataKey); encrypted = Buffer.concat([encrypted, cipher.final()]); return { encryptedKey: encrypted.toString('base64'), iv: iv.toString('base64'), tag: cipher.getAuthTag().toString('base64') }; } decryptDataKey(wrappedKey) { const decipher = crypto.createDecipheriv( 'aes-256-gcm', this.masterKey, Buffer.from(wrappedKey.iv, 'base64') ); decipher.setAuthTag(Buffer.from(wrappedKey.tag, 'base64')); let decrypted = decipher.update(Buffer.from(wrappedKey.encryptedKey, 'base64')); decrypted = Buffer.concat([decrypted, decipher.final()]); return decrypted; } } // Usage const kms = new KeyManagementService(masterKey); const dataKey = kms.generateDataKey(); const wrappedDataKey = kms.encryptDataKey(dataKey); // Store wrappedDataKey in database, not the raw dataKey // When you need to decrypt data, unwrap the dataKey first
Why envelope encryption? If the master key is compromised, you can rotate it without re-encrypting all data (just re-wrap data keys).
What Data Should Be Encrypted?
Text
MUST encrypt: - Passwords (using bcrypt, not encryption) - Social Security Numbers - Credit card numbers - Medical records - API keys and secrets - Authentication tokens Consider encrypting: - Email addresses - Phone numbers - Home addresses - Names (GDPR requirements) DO NOT encrypt: - Data that needs to be searched/indexed - Public information - Foreign key relationships
Remember: Encrypted data cannot be searched or indexed efficiently. Plan your encryption strategy before building.
Key Rotation Best Practices
Text
Key Rotation Strategies: 1. Versioned Keys: - Keep multiple key versions - New data uses new key - Old data gradually re-encrypted 2. Key Wrapping Rotation: - Rotate master key only - Re-wrap data keys with new master key - No need to re-encrypt actual data 3. Scheduled Rotation: - Rotate keys every 90-365 days - Plan for downtime or background re-encryption
JavaScript
// Versioned key example const encryptionKeys = { 'v1': Buffer.from(process.env.ENCRYPTION_KEY_V1, 'hex'), 'v2': Buffer.from(process.env.ENCRYPTION_KEY_V2, 'hex'), 'active': 'v2' }; function encryptWithVersion(text) { const version = encryptionKeys.active; const key = encryptionKeys[version]; const encrypted = encrypt(text, key); return { version, ...encrypted }; } function decryptWithVersion(encryptedData) { const key = encryptionKeys[encryptedData.version]; return decrypt(encryptedData, key); }
Knowledge Check
Ready to test your understanding of 15. Encryption & Secure Data Storage?