bcrypt

npm - bcrypt
bcrypt는 hash function의 한 종류이다.
npm package 중에서 bcrypt해주는 package를 정리해보자.
이 패키지로 password hashing 을 해서 보안을 강화할 수 있다.


Bcrypt 사용

설치

npm install bcrypt --save

비밀번호 hashing하기

const bcrypt = require('bcrypt');

const PW = 'abcd1234'
const salt = 12;

// hash 비동기콜백
bcrypt.hash(PW, salt, (err, encryptedPW) => {

})

// hashSync 동기
const hash = bcrypt.hashSync(PW, salt);

// async/await 사용
const hash = await bcrypt.hash(PW, salt)

비밀번호 검증하기

사용자가 입력한 비밀번호와 DB에 hash 되어 저장된 값을 비교해야한다.
입력 비밀번호도 hashing하여 DB 값과 같은지 확인하면 되고, 이 때 compare 메서드를 활용해서 간편하게 할 수 있다.

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

// 비동기 콜백
bcrypt.compare(PW , hash, (err, same) => {
  console.log(same);  //=> true
})

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

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

결과

Attachments/Picture/Pasted image 20240107180215.png
비밀번호가 암호화 되어 저장된다.

rerference