62 lines
1.9 KiB
JavaScript
62 lines
1.9 KiB
JavaScript
const crypto = require('crypto');
|
|
require('dotenv').config();
|
|
|
|
// 환경 변수에서 암호화 키 가져오기
|
|
const RAW_ENCRYPTION_KEY = process.env.ENCRYPTION_KEY || '안전한_암호화_키_설정';
|
|
// 키를 정확히 32바이트(256비트)로 변환
|
|
let ENCRYPTION_KEY;
|
|
try {
|
|
// 동기적으로 키 생성 (초기화 시 한 번만 실행됨)
|
|
ENCRYPTION_KEY = crypto.createHash('sha256').update(RAW_ENCRYPTION_KEY).digest();
|
|
} catch (error) {
|
|
console.error('암호화 키 생성 오류:', error);
|
|
throw new Error('암호화 키 생성 실패');
|
|
}
|
|
|
|
const IV_LENGTH = 16; // AES 블록 크기
|
|
|
|
/**
|
|
* 문자열을 암호화하는 함수
|
|
* @param {string} text - 암호화할 텍스트
|
|
* @returns {string} - 암호화된 텍스트 (base64 인코딩)
|
|
*/
|
|
function encrypt(text) {
|
|
if (!text) return null;
|
|
|
|
const iv = crypto.randomBytes(IV_LENGTH);
|
|
const cipher = crypto.createCipheriv('aes-256-cbc', Buffer.from(ENCRYPTION_KEY), iv);
|
|
|
|
let encrypted = cipher.update(text);
|
|
encrypted = Buffer.concat([encrypted, cipher.final()]);
|
|
|
|
// IV와 암호화된 데이터를 함께 저장 (복호화 시 필요)
|
|
return iv.toString('hex') + ':' + encrypted.toString('hex');
|
|
}
|
|
|
|
/**
|
|
* 암호화된 문자열을 복호화하는 함수
|
|
* @param {string} text - 복호화할 암호화된 텍스트
|
|
* @returns {string} - 복호화된 원본 텍스트
|
|
*/
|
|
function decrypt(text) {
|
|
if (!text) return null;
|
|
|
|
const textParts = text.split(':');
|
|
if (textParts.length !== 2) return null;
|
|
|
|
const iv = Buffer.from(textParts[0], 'hex');
|
|
const encryptedText = Buffer.from(textParts[1], 'hex');
|
|
|
|
const decipher = crypto.createDecipheriv('aes-256-cbc', Buffer.from(ENCRYPTION_KEY), iv);
|
|
|
|
let decrypted = decipher.update(encryptedText);
|
|
decrypted = Buffer.concat([decrypted, decipher.final()]);
|
|
|
|
return decrypted.toString();
|
|
}
|
|
|
|
module.exports = {
|
|
encrypt,
|
|
decrypt
|
|
};
|