반응형
데이터베이스에 비밀번호를 암호화해서 저장하기 위해 bcrypt라이브러리를 사용한다.
비밀번호를 유추할 수 없게 하기 위해 솔팅, 키스트레칭을 해서 해시를 하는데 bcrypt를 사용하면 해시된 비밀번호에 솔트값도 같이 저장이 되기 때문에 비밀번호를 비교하기 쉽다.
설치
npm install bcrypt
사용
const bcrypt = require('bcrypt');
const saltRounds = 10;
const myPlaintextPassword = 's0/\/\P4$$w0rD'; // 얘를 암호화할거
const someOtherPlaintextPassword = 'not_bacon';
비밀번호 암호화하기
// 1. 솔트값을 만들고 해당 솔트값으로 해싱
bcrypt.genSalt(saltRounds, function(err, salt) {
bcrypt.hash(myPlaintextPassword, salt, function(err, hash) {
// Store hash in your password DB.
});
});
// 2. 위 작업을 한번에 하는거(둘다 같은 결과가 나온다)
bcrypt.hash(myPlaintextPassword, saltRounds, function(err, hash) {
// Store hash in your password DB.
});
(db에 저장된)암호화된 비밀번호와 입력 비밀번호 비교
// Load hash from your password DB.
bcrypt.compare(myPlaintextPassword, hash, function(err, result) {
// result == true
});
bcrypt.compare(someOtherPlaintextPassword, hash, function(err, result) {
// result == false
});
회원가입에 적용
app.post('/users', async (req, res) => {
const {email, nickname, password, profileImage} = req.body;
const hashedPassword = await bcrypt.hash(password, 10);
await myDataSource.query(
`INSERT INTO users (email, nickname, password, profile_image)
VALUES (?, ?, ?, ?)`
, [email, nickname, hashedPassword, profileImage]);
res.status(201).json({"message" : "userCreated"});
});
확인
bcrypt.compare("encrypted", "$2b$10$AumIqWJxz6Lu194MKWmLeeeBPqUT61ggANG6uobtT8tvS/Jomd4be", (err, result)=>{console.log(result);});
// true
원래 비밀번호랑 비교해보면 같다고 잘 나온다.
참고
반응형
'TIL' 카테고리의 다른 글
NestJS | production/development환경 각각 다른 DB 사용하기(dotenv) (2) | 2022.11.19 |
---|---|
NestJS | 패키지 버전 지정해서 세팅하기 (0) | 2022.11.19 |
node.js | 인스타그램: 게시글 CRUD (1) | 2022.10.04 |
node.js | 인스타그램: 서버-db연결, 회원가입 (1) | 2022.10.03 |
node.js | express, TypeORM 적용한 CRUD API만들기 - 2 API작성 (0) | 2022.10.02 |