import crypto from 'crypto'; const ENCRYPTION_KEY = process.env.ENCRYPTION_SECRET || 'fallback_secret_do_not_use_in_production_12345'; // Must be 32 chars for aes-256-gcm const IV_LENGTH = 16; const ALGORITHM = 'aes-256-gcm'; /** * Encrypts a piece of sensitive text (like a private key) */ export function encrypt(text: string): string { // Ensure key is 32 bytes const key = crypto.createHash('sha256').update(ENCRYPTION_KEY).digest(); 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().toString('hex'); // Format: iv:authTag:encrypted return `${iv.toString('hex')}:${authTag}:${encrypted}`; } /** * Decrypts an encrypted string back to its original form */ export function decrypt(encryptedText: string): string { try { const parts = encryptedText.split(':'); if (parts.length !== 3) throw new Error('Invalid encrypted text format'); const iv = Buffer.from(parts[0], 'hex'); const authTag = Buffer.from(parts[1], 'hex'); const encrypted = parts[2]; const key = crypto.createHash('sha256').update(ENCRYPTION_KEY).digest(); const decipher = crypto.createDecipheriv(ALGORITHM, key, iv); decipher.setAuthTag(authTag); let decrypted = decipher.update(encrypted, 'hex', 'utf8'); decrypted += decipher.final('utf8'); return decrypted; } catch (error) { console.error('Decryption failed:', error); throw new Error('Critical: Could not decrypt sensitive data. Check ENCRYPTION_SECRET.'); } }