■ Front-End ■/Node.js

[Node.js] crypto 모듈 - 해시코드 생성, 문자열 암호화 및 복호화

한길(One Way) 2023. 2. 26.
Node.js는 빠르고 쉬우며 확장 가능한 JavaScript 런타임이다.

 

1. 개요

crypto 모듈은 해시코드 생성, 암호화와 복호화와 관련된 모듈이다.

crypto 모듈을 사용하여 문자열을 해시코드를 만들 수 있고 입력값을 암호화하고 복호화를 할 수 있다.

2. 설치

먼저 다음의 명령어로 crypto 모듈을 설치한다.

> npm install crypto --save

 

3. 사용법

먼저 crypto 모듈을 선언한다. 입력 값은 'crypto module'로 하였다.

var crypto = require('crypto');

var input = 'crypto module';

1) Hash

crypto.createHash() 메서드를 호출하여 Hash 클래스의 인스턴스로 sha1을 정의한다. 그리고 sha1에 update() 메서드로 input 데이터를 해싱하고 digest() 함수를 호출하면 해시값을 얻을 수 있다. 참고로 SHA-1은 TLS, SSL, PGP, SSH, IPSec 등 많은 보안 프로토콜과 프로그램에서 사용하는 해시 알고리즘이다.

var sha1 = crypto.createHash('sha1');
sha1.update(input);
var sha1output = sha1.digest('hex');
console.log("sha1output = " + sha1output);

실행결과

sha1output = a234c4ba3f9db1510e3b2050f078e20446f4cdba

2) Cipher

아래는 aes192로 값을 암호화하는 코드이다. cpyto.createCipher() 메서드를 호출하여 Cipher 객체를 생성한다. 암호화, 복호화를 위한 키 값은 'oneway'로 하였다. cipher에 update() 메서드에 인코딩 방식을 정의하고 cipher.final() 메서드를 호출하면 결과 값을 얻을 수 있다. 참고로 AES는 보안을 유지하기 위해 미국 표준 기술 연구소(NIST)에 의해 제정된 대칭 블록 암호 알고리즘이다.

var cipher = crypto.createCipher('aes192', 'oneway');
cipher.update(input, 'utf8', 'base64');
var cipheredOutput = cipher.final('base64');
console.log('cipheredOutput = ' + cipheredOutput);

실행결과

cipheredOutput = jbdjadxwlEN5Nfu6GyNQjg==

3) Decipher

아래는 aes192로 값을 복호화하는 코드이다.

암호화 때 사용한 키 'oneway'를 그대로 사용한다. 키 값이 다르면 오류가 발생한다.

var decipher = crypto.createDecipher('aes192', 'oneway');
decipher.update(cipheredOutput, 'base64', 'utf8');
var decipherOutput = decipher.final('utf8');
console.log('decipherOutput = ' + decipherOutput);

실행결과

decipherOutput = crypto module

 

4) 전체 코드

var crypto = require('crypto');

var input = 'crypto module';
console.log('input = ' + input)

var sha1 = crypto.createHash('sha1');
sha1.update(input);
var sha1output = sha1.digest('hex');
console.log("sha1output = " + sha1output);

var cipher = crypto.createCipher('aes192', 'oneway');
cipher.update(input, 'utf8', 'base64');
var cipheredOutput = cipher.final('base64');
console.log('cipheredOutput = ' + cipheredOutput);

var decipher = crypto.createDecipher('aes192', 'oneway');
decipher.update(cipheredOutput, 'base64', 'utf8');
var decipherOutput = decipher.final('utf8');
console.log('decipherOutput = ' + decipherOutput);

결과화면

input = crypto module
sha1output = a234c4ba3f9db1510e3b2050f078e20446f4cdba
cipheredOutput = jbdjadxwlEN5Nfu6GyNQjg==
decipherOutput = crypto module

4. 참조 URL

728x90

댓글