[Nest.js] 암호화, 해싱

Woong·2022년 12월 15일
0

Nestjs

목록 보기
15/28

암호화

  • 양방향 암호화

  • ex) AES 암호화 예제

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

const iv = randomBytes(16);
const password = 'Password used to generate key';

// The key length is dependent on the algorithm.
// 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(),
]);
  • 복호화
import { createDecipheriv } from 'crypto';

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

해싱

설치

npm i bcrypt 
npm i -D @types/bcrypt

해싱

import * as bcrypt from 'bcrypt';

const saltOrRounds = 10;
const password = 'random_password';
const hash = await bcrypt.hash(password, saltOrRounds);
  • salt 생성
const salt = await bcrypt.genSalt();
  • 해시값과 비교
const isMatch = await bcrypt.compare(password, hash);

reference

0개의 댓글