import { createCipheriv, createDecipheriv, randomBytes } from 'crypto'; import { config } from '../config'; const ALGORITHM = 'aes-256-gcm'; const IV_LENGTH = 12; function getKey(): Buffer { return Buffer.from(config.ENCRYPTION_KEY, 'hex'); } export function encrypt(plain: string): string { const iv = randomBytes(IV_LENGTH); const cipher = createCipheriv(ALGORITHM, getKey(), iv); const encrypted = Buffer.concat([cipher.update(plain, 'utf8'), cipher.final()]); const tag = cipher.getAuthTag(); return `${iv.toString('base64')}:${tag.toString('base64')}:${encrypted.toString('base64')}`; } export function decrypt(ciphertext: string): string { const [ivB64, tagB64, dataB64] = ciphertext.split(':'); if (!ivB64 || !tagB64 || !dataB64) { throw new Error('Invalid encrypted password format'); } const iv = Buffer.from(ivB64, 'base64'); const tag = Buffer.from(tagB64, 'base64'); const data = Buffer.from(dataB64, 'base64'); const decipher = createDecipheriv(ALGORITHM, getKey(), iv); decipher.setAuthTag(tag); return Buffer.concat([decipher.update(data), decipher.final()]).toString('utf8'); }