import { createCipheriv, createDecipheriv, randomBytes } from 'crypto'; const ALGORITHM = 'aes-256-gcm'; // 환경 변수 체크 추가 if (!process.env.ENCRYPTION_KEY) { throw new Error("ENCRYPTION_KEY가 .env.local 파일에 정의되지 않았습니다."); } // .env.local에 저장한 키를 가져옵니다. const KEY = Buffer.from(process.env.ENCRYPTION_KEY!, 'hex'); const IV_LENGTH = 12; export function encrypt(text: string): string { const iv = randomBytes(IV_LENGTH); const cipher = createCipheriv(ALGORITHM, KEY, iv); let encrypted = cipher.update(text, 'utf8', 'hex'); encrypted += cipher.final('hex'); const authTag = cipher.getAuthTag().toString('hex'); // IV:인증태그:암호문 형태로 결합 return `${iv.toString('hex')}:${authTag}:${encrypted}`; } export function decrypt(encryptedData: string): string { const [ivHex, authTagHex, encryptedText] = encryptedData.split(':'); const iv = Buffer.from(ivHex, 'hex'); const authTag = Buffer.from(authTagHex, 'hex'); const decipher = createDecipheriv(ALGORITHM, KEY, iv); decipher.setAuthTag(authTag); let decrypted = decipher.update(encryptedText, 'hex', 'utf8'); decrypted += decipher.final('utf8'); return decrypted; }