.env 파일에 암호화된 값을 넣고 코드에서 복호화하는 방법에 대해 알아보겠습니다.
1. 패키지 설치
npm install crypto
npm install dotenv
npm install fs
2. 패스워드를 암호화해서 .env 파일에 넣기 (EncryptEnv.js)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
|
const fs = require('fs');
const crypto = require('crypto');
const ENCRYPTION_KEY = 'my-encryption-key-32-bytes-long!!!!'; // 32바이트 키
const IV_LENGTH = 16; // AES IV 크기 (128비트)
// 암호화 함수
function encrypt(text) {
const iv = crypto.randomBytes(IV_LENGTH);
const cipher = crypto.createCipheriv('aes-256-cbc', Buffer.from(ENCRYPTION_KEY), iv);
let encrypted = cipher.update(text, 'utf8', 'hex');
encrypted += cipher.final('hex');
return `${iv.toString('hex')}:${encrypted}`;
}
// 암호화된 값 생성
const plainTextPassword = 'my-secret-password';
const encryptedPassword = encrypt(plainTextPassword);
console.log('Encrypted Password:', encryptedPassword);
// .env 파일에 추가
fs.appendFileSync('.env', `DATABASE_PASSWORD=${encryptedPassword}\n`, 'utf8');
console.log('.env file updated with encrypted password.');
|
cs |
3. .env에서 DATABASE_PASSWORD를 받아와서 출력(DecryptEnv.js)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
|
require('dotenv').config(); // dotenv로 .env 파일 로드
const crypto = require('crypto');
// 대칭 암호화를 위한 키 (환경변수나 안전한 키 관리 시스템에서 가져와야 함)
const ENCRYPTION_KEY = 'my-encryption-key-32-bytes-long!'; // 32바이트 키
const IV_LENGTH = 16; // AES IV 크기 (128비트)
// 복호화 함수
function decrypt(encryptedText) {
const [iv, encrypted] = encryptedText.split(':');
const decipher = crypto.createDecipheriv(
'aes-256-cbc',
Buffer.from(ENCRYPTION_KEY),
Buffer.from(iv, 'hex')
);
let decrypted = decipher.update(encrypted, 'hex', 'utf8');
decrypted += decipher.final('utf8');
return decrypted;
}
// .env 파일에서 암호화된 값 가져오기
const encryptedPassword = process.env.DATABASE_PASSWORD;
if (!encryptedPassword) {
console.error('DATABASE_PASSWORD is missing in .env');
process.exit(1);
}
// 복호화
const decryptedPassword = decrypt(encryptedPassword);
console.log('Decrypted Database Password:', decryptedPassword);
|
cs |
4. 결과