Node.js crypto 모듈: 데이터 암호화, 해시, 인증코드 생성

Node.js crypto 모듈: 데이터 암호화, 해시, 인증코드 생성

이 글에서는 Node.js의 crypto 모듈을 사용하여 보안 기능을 구현하는 방법에 대해 알아보겠습니다. crypto 모듈은 암호화, 해시 생성, 인증 코드 생성 등 다양한 보안 작업에 사용됩니다.

crypto 모듈 개요

crypto 모듈은 Node.js에서 제공하는 내장 모듈로, 보안 관련 작업을 수행하는 데 사용됩니다. 이 모듈은 다양한 암호화 알고리즘, 해싱 함수, 키 생성 함수 등을 제공합니다.

기본 사용법

먼저, crypto 모듈을 사용하려면 해당 모듈을 불러와야 합니다.

const crypto = require('crypto');

해시 생성 예제

다음은 SHA-256 해시를 생성하는 예제입니다:

const hash = crypto.createHash('sha256'); // SHA-256 해시 알고리즘 사용
hash.update('Hello, world!'); // 'Hello, world!' 문자열을 해시 객체에 추가
console.log(hash.digest('hex')); // 해시 값을 16진수 문자열로 출력
해시 생성 예제 결과

랜덤 바이트 생성 예제

다음은 랜덤 바이트를 생성하여 인증 코드로 사용하는 예제입니다.

const verificationCode = crypto.randomBytes(3).toString('hex').toUpperCase();
console.log(verificationCode);
랜덤 바이트 생성 예제 결과 화면

데이터 암호화 예제

다음은 AES-256-CBC 알고리즘을 사용하여 데이터를 암호화하는 예제입니다.

const algorithm = 'aes-256-cbc';
const key = crypto.randomBytes(32);
const iv = crypto.randomBytes(16);

const cipher = crypto.createCipheriv(algorithm, key, iv);
let encrypted = cipher.update('Hello, world!', 'utf8', 'hex');
encrypted += cipher.final('hex');
console.log(encrypted);

데이터 복호화 예제

다음은 위에서 암호화한 데이터를 복호화하는 예제입니다.

const decipher = crypto.createDecipheriv(algorithm, key, iv);
let decrypted = decipher.update(encrypted, 'hex', 'utf8');
decrypted += decipher.final('utf8');
console.log(decrypted);
데이터 암호화, 복호화 예제 실행 결과

참고할 만한 사이트

관련 이전 게시글

이 글이 도움이 되셨다면 공유 부탁 드립니다.

위로 스크롤