1. 개요
crypto 모듈은 해시코드 생성, 암호화와 복호화와 관련된 모듈이다.
crypto 모듈을 사용하여 문자열을 해시코드를 만들 수 있고 입력값을 암호화하고 복호화를 할 수 있다.
2. 설치
먼저 다음의 명령어로 crypto 모듈을 설치한다.
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
'■ Front-End ■ > Node.js' 카테고리의 다른 글
[Node.js] url (Uniform Resource Locator)모듈로 URL을 파싱 (0) | 2023.02.26 |
---|---|
[Node.js] os 모듈을 사용하여 운영체제와 시스템 정보를 조회 (0) | 2023.02.26 |
[Node.js] w3cschool의 MySQL 튜토리얼 실행할 때 유용한 팁 (0) | 2023.02.26 |
[Node.js] exports와 require를 사용하여 모듈을 구성한다. (0) | 2023.02.26 |
[Node.js] 어디든지 사용 가능한 전역변수와 전역함수, 전역객체 (0) | 2023.02.26 |
댓글