const crypto = require('crypto'); // The encryption key must be exactly 32 bytes for AES-256 const getEncryptionKey = () => { const key = process.env.ENCRYPTION_KEY || 'default_secret_key_needs_32_bytes!'; // Ensure it's 32 bytes by hashing it if it's not exactly 32 bytes if (key.length !== 32) { return crypto.createHash('sha256').update(key).digest(); } return Buffer.from(key); }; const algorithm = 'aes-256-cbc'; function encrypt(text) { const iv = crypto.randomBytes(16); const cipher = crypto.createCipheriv(algorithm, getEncryptionKey(), iv); let encrypted = cipher.update(text, 'utf8', 'hex'); encrypted += cipher.final('hex'); return { iv: iv.toString('hex'), encryptedData: encrypted }; } function decrypt(encryptedData, ivHex) { const iv = Buffer.from(ivHex, 'hex'); const decipher = crypto.createDecipheriv(algorithm, getEncryptionKey(), iv); let decrypted = decipher.update(encryptedData, 'hex', 'utf8'); decrypted += decipher.final('utf8'); return decrypted; } module.exports = { encrypt, decrypt };