import crypto from 'crypto'; const ALGORITHM = 'aes-256-gcm'; const IV_LENGTH = 16; const SALT_LENGTH = 16; const AUTH_TAG_LENGTH = 16; const KEY_LENGTH = 32; function deriveKey(secret: string, salt: Buffer): Buffer { return crypto.scryptSync(secret, salt, KEY_LENGTH); } function getSecret(): string { const secret = process.env.SESSION_SECRET; if (!secret) { throw new Error('SESSION_SECRET environment variable is required for encryption'); } return secret; } export function encrypt(text: string): string { if (!text) return text; const secret = getSecret(); const salt = crypto.randomBytes(SALT_LENGTH); const key = deriveKey(secret, salt); const iv = crypto.randomBytes(IV_LENGTH); const cipher = crypto.createCipheriv(ALGORITHM, key, iv); let encrypted = cipher.update(text, 'utf8', 'hex'); encrypted += cipher.final('hex'); const authTag = cipher.getAuthTag(); // Format: salt:iv:authTag:ciphertext (4 parts — v2) return `${salt.toString('hex')}:${iv.toString('hex')}:${authTag.toString('hex')}:${encrypted}`; } export function decrypt(encryptedText: string): string { if (!encryptedText || !encryptedText.includes(':')) return encryptedText; try { const secret = getSecret(); const parts = encryptedText.split(':'); if (parts.length === 4) { // v2 format: salt:iv:authTag:ciphertext const salt = Buffer.from(parts[0], 'hex'); const iv = Buffer.from(parts[1], 'hex'); const authTag = Buffer.from(parts[2], 'hex'); const encrypted = parts[3]; const key = deriveKey(secret, salt); const decipher = crypto.createDecipheriv(ALGORITHM, key, iv, { authTagLength: AUTH_TAG_LENGTH }); decipher.setAuthTag(authTag); let decrypted = decipher.update(encrypted, 'hex', 'utf8'); decrypted += decipher.final('utf8'); return decrypted; } if (parts.length === 3) { // v1 format: iv:authTag:ciphertext (fixed salt 'salt') const key = crypto.scryptSync(secret, 'salt', KEY_LENGTH); const iv = Buffer.from(parts[0], 'hex'); const authTag = Buffer.from(parts[1], 'hex'); const encrypted = parts[2]; const decipher = crypto.createDecipheriv(ALGORITHM, key, iv, { authTagLength: AUTH_TAG_LENGTH }); decipher.setAuthTag(authTag); let decrypted = decipher.update(encrypted, 'hex', 'utf8'); decrypted += decipher.final('utf8'); return decrypted; } return encryptedText; } catch (error) { console.error('Decryption failed:', error); return encryptedText; } }