본문 바로가기
FrontEnd/Next.js

[Next.js] bcrypt 를 통해 비밀번호 암호화

by 위그든씨 2023. 1. 23.
bcrypt.hashpw(password,bcrypt.gensalt())

Bcrypt 란?

  • 1999년에 출시된 password-hashing function이다.
  • Blowfish 암호를 기반으로 설계된 암호화 함수이며 현재까지 가장 강력한 해시 매커니즘 중 하나
  • 보안으로 유명한 OpenBSD에서 사용 중
  • 반복횟수를 늘려 연산 속도를 늦출 수 있으므로 연산 능력이 증가하더라고 brute-force 공격 대비 가능
  • 구현이 쉽고 비교적 걍력하다

사용법

1. 설치

yarn add bcrypt

2. 비밀번호 암호화

  • hash는 동기, hashSync는 비동기 방식
  • 파라미터로 넣은 숫자는 암호화에 사용되는 Salt로, 값이 높을수록 암호화 연산이 증가함.(속도는 느려짐)
//비밀번호 암호화

const bcrypt = require("bcrypt");
const hash = bcrypt.hashSync(information.password, 12);
const user = await client.user.create({
    data: {
        name: information.name,
        email: information.email,
        password: hash,
    },
});

/**
	bcrypt.hash(PW, 12,(err,encryptedPW) =>{
    	//hash 비동기 콜백
    });
    
    //hashSync 비동기
    const hash = bcrypt.hasySync(PW,salt);
    
    // async/await 사용
    const hash = await bcrypt.hash(PW,salt);
*/
// 비밀번호 검증하기

const PW = 'abcd1234';
const hash = bcrypt.hashSync(PW,12);

bcrypt.compare(PW,hash,(err,same)=>{
	console.log('same');
})

const match = bcrypt.compareSync(PW,hash);
if(match){
	//login
}
const match = await bcrypt.compare(PW,hash);
if(match){
	//login
}