cipher.update() 메서드는 지정된 인코딩 형식에 따라 수신된 데이터로 암호화 객체(cipher)를 갱신하는 데 사용됩니다. 이 메서드는 Node.js의 crypto 모듈 내 Cipher 클래스에서 기본적으로 제공하는 내장 메서드 중 하나입니다.
입력 인코딩(inputEncoding)이 지정되면 data 인자는 문자열(string)로 처리되고, 지정되지 않으면 data 인자는 버퍼(Buffer) 타입이어야 합니다.
문법(Syntax)
cipher.update(data, [inputEncoding], [outputEncoding])
매개변수(Parameters)
각 매개변수에 대한 설명은 다음과 같습니다.
data – 암호화 객체를 갱신하기 위해 전달되는 입력 데이터입니다.
inputEncoding – 입력 데이터의 인코딩 방식을 지정합니다. 가능한 값으로는
hex,base64,utf8등이 있습니다.outputEncoding – 출력 결과의 인코딩 방식을 지정하며, 문자열 타입입니다. 가능한 값으로는
hex,base64등이 있습니다.
예제 1: 동기 방식 키 생성
cipherUpdate.js라는 이름의 파일을 생성하고 아래 코드를 복사한 뒤, 다음 명령어로 실행해 보세요.
node cipherUpdate.js
cipherUpdate.js
// cipher.update() 메서드 사용 예제
// crypto 모듈 불러오기
const crypto = require('crypto');
// AES 알고리즘 초기화
const algorithm = 'aes-192-cbc';
// 키 생성에 사용할 비밀번호 설정
const password = '12345678123456789';
// scryptSync로 암호화 키 생성
const key = crypto.scryptSync(password, 'old data', 24);
// 고정 IV(초기화 벡터) 생성
const iv = Buffer.alloc(16, 0);
// 암호화 객체 생성
const cipher = crypto.createCipheriv(algorithm, key, iv);
// 새 데이터로 암호화 값을 갱신
let updatedValue = cipher.update('Welcome to tutorials point', 'utf8', 'hex');
// 갱신된 값과 최종 값 결합
updatedValue += cipher.final('hex');
// 결과 출력
console.log("Updated String:- " + updatedValue);실행 결과
C:\home\node>> node cipherUpdate.js Updated String:- a05e87569f3f04234812ae997da5684944c32b8776fae676b4abe9074b31cd2a
예제 2: 비동기 콜백 방식 키 생성
이번에는 crypto.scrypt()를 비동기 콜백 방식으로 사용하는 또 다른 예제를 살펴보겠습니다.
// cipher.update() 메서드 사용 예제 (비동기 방식)
// crypto 모듈 불러오기
const crypto = require('crypto');
// AES 알고리즘 초기화
const algorithm = 'aes-192-cbc';
// 키 생성에 사용할 비밀번호 설정
const password = '12345678123456789';
// scrypt를 비동기 방식으로 호출하여 키 생성
crypto.scrypt(password, 'salt', 24,
{ N: 512 }, (err, key) => {
if (err) throw err;
// 고정 IV(초기화 벡터) 생성
const iv = Buffer.alloc(16, 0);
// 암호화 객체 생성
const cipher = crypto.createCipheriv(algorithm, key, iv);
// 새 데이터로 암호화 값을 갱신
let updatedValue = cipher.update('Some new text data', 'utf8', 'hex');
// 갱신된 값과 최종 값 결합
updatedValue += cipher.final('hex');
// 결과 출력
console.log("Updated String:- " + updatedValue);
});실행 결과
C:\home\node>> node cipherUpdate.js Updated String:- 91d6d37e70fbae537715f0a921d15152194435b96ce3973d92fbbc4a82071074
정리
cipher.update()는 스트림 방식으로 데이터를 암호화할 때 핵심적인 역할을 하는 메서드입니다. 데이터를 한 번에 처리하지 않고 여러 번 나누어 갱신할 수 있으며, 마지막에는 반드시 cipher.final()을 호출하여 암호화를 완료해야 합니다. 대용량 파일이나 스트림 데이터를 다룰 때 특히 유용하게 활용됩니다.