crypto.createDecipheriv()는 Node.js의 crypto 모듈에서 제공하는 프로그래밍 인터페이스입니다. 이 메서드는 함수에 전달된 알고리즘(algorithm), 키(key), 초기화 벡터(iv) 및 옵션(options)에 따라 Decipher(복호화) 객체를 생성하여 반환합니다. 암호화된 데이터를 지정된 방식으로 안전하게 복호화해야 할 때 필수적으로 사용되는 메서드입니다.
문법(Syntax)
crypto.createDecipheriv(algorithm, key, iv, [options])
매개변수(Parameters)
각 매개변수에 대한 자세한 설명은 다음과 같습니다.
algorithm – 복호화에 사용할 알고리즘을 지정합니다. 사용 가능한 값으로는 aes192, aes256 등이 있으며, 실제로는 'aes-192-cbc', 'aes-256-cbc'처럼 운영 모드까지 포함한 문자열 형태로 지정하는 것이 일반적입니다.
key – 알고리즘에서 사용할 원시 키(raw key)를 입력받습니다. 값의 타입은 string, Buffer, TypedArray 또는 DataView가 가능하며, 필요에 따라 KeyObject 타입의 비밀 키 객체도 사용할 수 있습니다. 키 길이는 선택한 알고리즘의 요구 사항에 맞아야 합니다.
iv – 초기화 벡터(Initialization Vector)라고도 불립니다. 이 매개변수는 암호화 결과를 예측 불가능하고 고유하게 만들어 주는 역할을 합니다. iv는 비밀로 유지할 필요는 없지만, 암호화 시 사용한 것과 동일한 값을 복호화 시에 전달해야 합니다. 값의 타입은 string, Buffer, TypedArray, DataView가 가능하며, 사용하는 암호화 방식에서 iv가 필요 없다면 null을 전달할 수 있습니다.
options – 스트림 동작을 제어하기 위한 선택적 매개변수입니다. 다만 CCM 또는 OCB 모드(예: 'aes-256-ccm')를 사용하는 경우에는 authTagLength 옵션을 반드시 지정해야 하므로 생략할 수 없습니다.
예제 1: 기본적인 복호화 수행
먼저 createDecipheriv.js라는 이름의 파일을 생성하고 아래 코드를 복사합니다. 파일 생성 후에는 다음 명령어로 코드를 실행할 수 있습니다.
node createDecipheriv.js
createDecipheriv.js
// Node.js 데모 프로그램: 데이터 복호화
// crypto 모듈 가져오기
const crypto = require('crypto');
// 알고리즘 초기화
const algorithm = 'aes-192-cbc';
// 비밀번호 정의 및 초기화
const password = '123456789';
// scryptSync를 사용해 키 초기화
const key = crypto.scryptSync(password, 'TutorialsPoint', 24);
// 초기화 벡터(iv) 생성
const iv = Buffer.alloc(16, 0);
// 위에서 정의한 매개변수로 Decipher 객체 생성
const decipher = crypto.createDecipheriv(algorithm, key, iv);
let decrypted = '';
// readable 이벤트로 데이터를 읽으며 복호화 진행
decipher.on('readable', () => {
let chunk;
while (null !== (chunk = decipher.read())) {
decrypted += chunk.toString('utf8');
}
});
// 종료(end) 이벤트 처리
decipher.on('end', () => {
console.log(decrypted);
});
// 복호화할 암호화된 데이터
const encrypted = 'uqeQEkXy5dpJjQv+JDvMHw==';
// base64 형식으로 암호문을 스트림에 기록 후 종료
decipher.write(encrypted, 'base64');
decipher.end();
console.log("Completed... !");
실행 결과
C:\home\node>> node createDecipheriv.js Completed... ! TutorialsPoint
위 예제에서는 scryptSync 함수로 파생 키를 생성하고, base64로 인코딩된 암호문을 스트림 방식으로 복호화하여 원래 문자열인 'TutorialsPoint'를 출력했습니다.
예제 2: 암호화와 복호화 함께 구현하기
이번에는 encrypt 함수와 decrypt 함수를 직접 구현하여 데이터를 암호화한 뒤 다시 복호화하는 과정을 살펴보겠습니다.
// Node.js 데모 프로그램: 암호화 및 복호화
// crypto 모듈 가져오기
const crypto = require('crypto');
// 알고리즘 초기화
const algorithm = 'aes-256-cbc';
// 비밀번호 정의 및 초기화
const password = '123456789';
// 랜덤 바이트로 키 초기화 (32바이트)
const key = crypto.randomBytes(32);
// 랜덤 바이트로 초기화 벡터(iv) 생성 (16바이트)
const iv = crypto.randomBytes(16);
// 데이터를 암호화하는 함수
function encrypt(text) {
// 위에서 정의한 매개변수로 Cipher 객체 생성
let cipher =
crypto.createCipheriv('aes-256-cbc', Buffer.from(key), iv);
// 텍스트를 암호화
let encrypted = cipher.update(text);
// 버퍼 연결로 최종 암호문 완성
encrypted = Buffer.concat([encrypted, cipher.final()]);
// iv와 암호화된 데이터를 함께 반환
return { iv: iv.toString('hex'),
encryptedData: encrypted.toString('hex') };
}
// 데이터를 복호화하는 함수
function decrypt(text) {
let iv = Buffer.from(text.iv, 'hex');
let encryptedText =
Buffer.from(text.encryptedData, 'hex');
// 알고리즘, 키, iv로 Decipher 객체 생성
let decipher = crypto.createDecipheriv(
'aes-256-cbc', Buffer.from(key), iv);
// 텍스트 복호화
let decrypted = decipher.update(encryptedText);
decrypted = Buffer.concat([decrypted, decipher.final()]);
// 복호화된 결과 반환
return decrypted.toString();
}
// 데이터 암호화 후 결과 출력
var output = encrypt("Welcome to TutorialsPoint !");
console.log("Encrypted data -- ", output);
// 복호화된 데이터 출력
console.log("Decrypted data -- ", decrypt(output));
실행 결과
C:\home\node>> node createDecipheriv.js
Encrypted data -- { iv: '3fb2c84290e04d9bfb099bc65a7ac941',
encryptedData:
'4490777e90c5a78037cb92a99d561ae250562e2636af459b911cfa01c0191e3f' }
Decrypted data -- Welcome to TutorialsPoint !
두 번째 예제에서 주목할 점은 암호화 시 사용한 iv를 hex 문자열로 변환해 결과 객체에 함께 저장하고, 복호화 시 그대로 꺼내 사용한다는 것입니다. CBC 모드처럼 iv가 필요한 알고리즘에서는 암호화와 복호화 과정에서 반드시 동일한 iv를 사용해야 올바른 결과를 얻을 수 있습니다.
정리
crypto.createDecipheriv() 메서드는 Node.js에서 대칭키 기반 복호화를 수행하는 핵심 API입니다. 알고리즘, 키, 초기화 벡터를 정확히 일치시키는 것이 성공적인 복호화의 핵심이며, 실무에서는 randomBytes나 scryptSync 같은 함수를 활용해 안전한 키와 iv를 생성하는 것이 권장됩니다.