Computer >> 컴퓨터 >  >> 프로그래밍 >> JavaScript

Node.js decipher.update() 메서드 완벽 가이드

Node.js decipher.update() 메서드란?

decipher.update() 메서드는 지정된 인코딩 형식에 따라 수신된 데이터를 사용해 복호화(decipher) 객체를 갱신하는 역할을 합니다. 이 메서드는 Node.js의 crypto 모듈Decipher 클래스에서 기본적으로 제공하는 내장 메서드 중 하나입니다.

입력 인코딩(input encoding)을 지정하면 data 인자는 문자열(string) 타입이 되고, 지정하지 않으면 Buffer 타입으로 처리됩니다.

문법(Syntax)

decipher.update(data, [inputEncoding], [outputEncoding])

매개변수(Parameters)

각 매개변수에 대한 설명은 다음과 같습니다.

  • data – 복호화 객체를 갱신하기 위해 전달되는 입력 데이터입니다.

  • inputEncoding – 입력 데이터의 인코딩 방식을 지정합니다. 사용 가능한 값으로는 hex, base64 등이 있습니다.

  • outputEncoding – 출력 결과의 인코딩 방식을 지정하며, 이 매개변수는 문자열 타입입니다. 사용 가능한 값으로는 hex, base64 등이 있습니다.

예제 1: decipher.update() 기본 사용법

decipherUpdate.js라는 이름의 파일을 생성하고 아래 코드를 복사한 뒤, 다음 명령어로 실행해 보세요.

node decipherUpdate.js
// decipher.final() 메서드 사용 예제

// crypto 모듈 불러오기
const crypto = require('crypto');

// AES 알고리즘 초기화
const algorithm = 'aes-192-cbc';
// 키 생성에 사용할 비밀번호 설정
const password = '12345678123456789';

// decipher 객체에 사용할 키 생성
const key = crypto.scryptSync(password, 'old data', 24);

// 고정 IV(초기화 벡터) 설정
const iv = Buffer.alloc(16, 0);

const decipher = crypto.createDecipheriv(algorithm, key, iv);

// 복호화할 암호문 지정
const encrypted = '083bfe1b2f91677e5d00add115be2f1b2e362e190406f5c6b60e86969bf03bff';

let decryptedValue = decipher.update(encrypted, 'hex', 'utf8');

decryptedValue += decipher.final('utf8');

// 결과 출력
console.log("복호화된 값 -- " + decryptedValue);

실행 결과

C:\home\node>> node decipherUpdate.js
복호화된 값 -- Some new text data

예제 2: 콜백 방식으로 scrypt 키 생성 후 복호화

이번에는 비동기 콜백 방식으로 키를 생성하여 복호화하는 또 다른 예제를 살펴보겠습니다.

// decipher.final() 메서드 사용 예제

// 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);

    // 알고리즘, 키, IV로 decipher 객체 초기화
    const decipher = crypto.createDecipheriv(algorithm, key, iv);
    const encrypted = '91d6d37e70fbae537715f0a921d15152194435b96ce3973d92fbbc4a82071074';

    // 복호화된 문자열 값 가져오기
    const decrypted = decipher.update(encrypted, 'hex', 'utf8');

    // 결과 출력
    console.log("복호화된 값:- " + decrypted);
});

실행 결과

C:\home\node>> node decipherUpdate.js
복호화된 값:- Some new text data

마무리

decipher.update()는 스트림 형태로 들어오는 암호화 데이터를 청크 단위로 복호화할 때 유용하게 활용됩니다. 마지막 데이터 처리 시에는 반드시 decipher.final() 메서드를 호출하여 패딩(padding) 검증 및 최종 복호화를 완료해야 한다는 점도 함께 기억해 두세요.