NestJS 공부 35일차

정인교·2021년 7월 12일
0

TIL(Today I Learned)

목록 보기
46/67
post-thumbnail

암호화와 해싱

암호화는 정보를 인코딩하여 다른 사용자들에게 유출시키지 않기 위해 사용되는 것입니다!
해싱은 주어진 키를 다른 값으로 변환하는 프로세스며 수학적으로 값을 생성합니다

암호화 기초

Node.js 는 crypto모듈을 이용하여 암호화를 하는데 알고리즘 종류를 선택하면된다. 제일 대표적인 것은 base64로 제일 짧기도 하고 잘 쓰입니다. hex방법도 사용해봤지만 여기서는 aes-256-ctr을 사용합니다.

import { createCipheriv, randomBytes, scrypt } from 'crypto';
import { promisify } from 'util';

const iv = randomBytes(16);
const password = 'asdf1234';

// In this case for aes256, it is 32 bytes.
const key = (await promisify(scrypt)(password, 'salt', 32)) as Buffer;
const cipher = createCipheriv('aes-256-ctr', key, iv);

const textToEncrypt = 'Nest';
const encryptedText = Buffer.concat([
  cipher.update(textToEncrypt),
  cipher.final(),
]);

위 코드가 암호화를 시켜주는 코든데, 보시다시피 crypto모듈을 가지고와서 aes-256-ctr를 사용합니다.

import { createDecipheriv } from 'crypto';

const decipher = createDecipheriv('aes-256-ctr', key, iv);
const decryptedText = Buffer.concat([
  decipher.update(encryptedText),
  decipher.final(),
]);

값 해독은 처음 만들었던 key를 이용하여 해독하니 key는 따로 저장해줘야합니다.

해싱 기초

해싱은 node.js에서 bcryptargon2를 사용하는데 주로 bcrypt를 주로 사용합니다. 모듈 설치는 아래처럼 해주면 됩니다.

npm i bcrypt
npm i -D @types/bcrypt

해싱 사용

import * as bcrypt from 'bcrypt';

const saltOrRounds = 10;
const password = 'asdf1234';
const hash = await bcrypt.hash(password, saltOrRounds);

hash는 saltOrRounds에 숫자를 넣고 hash를 통해서 해싱하면됩니다.
const salt = await bcrypt.genSalt();
salt 생성 시 위 코드를 사용하고
const isMatch = await bcrypt.compare(password, hash);
비밀번호 확인 시 compare기능을 사용하면됩니다.

profile
백엔드 개발자 정인교입니다!

0개의 댓글

관련 채용 정보