백엔드 기술/NodeJS
[NodeJS] 비밀번호 hashing - bcrypt
pogles
2023. 3. 2. 23:47
웹서비스 등 회원가입을 통해 회원들의 정보를 저장할 때 비밀번호 등 보안을 위해서 hashing 이 필요하다.
해커들이 hashing 에 대한 공격으로 rainbow table 을 진행할 수 있지만 bcrypt 는 rainbow table 공격을 막아준다
bcrypt
A bcrypt library for NodeJS.. Latest version: 5.1.0, last published: 5 months ago. Start using bcrypt in your project by running `npm i bcrypt`. There are 3767 other projects in the npm registry using bcrypt.
www.npmjs.com
npm 설치
npm i bcrypt
hasing 방법
- saltRounds 는 의미그대로 소금을 뿌리는 것처럼 hashing 한 값을 예측하기 더 어렵게 해준다. 값만큼 해싱을 해준다
bcrypt.hash(myPlaintextPassword, saltRounds, function(err, hash) {
// Store hash in your password DB.
});
적용해보기
import mongoose from "mongoose";
import bcrypt from "bcrypt";
const UserSchema = new mongoose.Schema({
email: {type: String, required: true, unique: true },
username : {type: String, required: true, unique: true },
password : {type: String, required: true }, // 보안을 위해 해싱(hashing)시켜야함
name : { type: String, required: true},
location : String,
});
// save 하기전 실행하는 함수
// this 는 save 할 User data
UserSchema.pre("save", async function() {
console.log("Users password:", this.password);
this.password = await bcrypt.hash(this.password, 5); // salt round = 5
console.log("Hashed password:", this.password);
});
const User = mongoose.model("User", UserSchema);
export default User;