Bcrypt๋ node.js์์ ๋น๋ฐ๋ฒํธ ํด์ฌํ๋ฅผ ๋์์ฃผ๋ ๋ผ์ด๋ธ๋ฌ๋ฆฌ๋ค.
ํด์ฌํ๋ ๋จ๋ฐฉํฅ์ผ๋ก ํด์ฌ์๊ณ ๋ฆฌ์ฆ์ ์ด์ฉํ์ฌ ๋น๋ฐ๋ฒํธ๋ฅผ ์ํธํ์ํจ๋ค. ๋จ๋ฐฉํฅ์ด๋ฏ๋ก ๋ณต๊ตฌ๋ ๋ถ๊ฐ๋ฅํ๋ค.
์ํธํ๋ ์๋ฐฉํฅ์ผ๋ก ๋ณต๊ตฌ ๊ฐ๋ฅํ๋ค.
npm install -D bcrypt
npm install -D @types/bcrypt // ํ์
์คํฌ๋ฆฝํธ ์ฌ์ฉํ๋ ๊ฒฝ์ฐ
import bcrypt from 'bcrypt'
const hashing = async () => {
const password = "cloud1589"
const saltRound = 10
const salt = await bcrypt.genSalt(saltRound)
// genSlat() ๋ฉ์๋๋ฅผ ํตํด ์๊ธ ์์ฑ
// ๋น๋๊ธฐ ๋ฐฉ์ ํ๋ผ๋ฏธํฐ๋ก ๋ฃ์ 10์ ์ํธํ์ ์ฌ์ฉ๋๋ saltOrRounds๋ก, ๊ฐ์ด ๋์์๋ก ์ํธํ ์ฐ์ฐ์ด ์ฆ๊ฐํ๋ค.
// ํ์ง๋ง ๊ทธ๋งํผ ์๋๊ฐ ๋๋ ค์ง๋ค.
const hashedPassword = await bcrypt.hash(password, salt) // password ํด์ฌํ ์์ฑ
// ๋น๋ฐ๋ฒํธ๋ฅผ ํด์ฌํํ์ฌ, ์ดํ DB์๋ ํด์ฌํ ์ํธ๋ฅผ ์ ์ฅํ๋ค.
}
์ฌ์ฉ์๊ฐ ๋ก๊ทธ์ธ ํ ๋, ์ ๋ ฅ๋ฐ์ ๋น๋ฐ๋ฒํธ์ DB์ ์ ์ฅ๋ ํด์ฌํ๋ ๋น๋ฐ๋ฒํธ๋ฅผ ๋น๊ตํ์ฌ true๊ฐ ๋์ค๋ฉด ๋ก๊ทธ์ธ์ ์ฑ๊ณต์ํจ๋ค.
import bcrypt from 'bcrypt'
const check = await bcrypt.compare(password, hashedPassword)
if(check) {
console.log('๋ก๊ทธ์ธ!')
} else {
console.log('์คํจ')
}
๊ณต๊ฒฉ์๊ฐ ์ํธ๋ฅผ ์ ์ถํ ์ ์๋๋ก, ํ๋ฌธ ๋ฐ์ดํฐ์ ์๋ฏธ ์๋ ๋ฐ์ดํฐ๋ฅผ ๋ฟ๋ ค ๋ฃ๋๋ฐ, ์ด๊ฒ์ salt๋ผ๊ณ ํ๋ค.
"data too long!"
์ด๋๋ DB password์ length๋ฅผ ๋๋ ค์ฃผ๋ฉด ๋๋ค.
์๋ฌ๊ฐ ๋ฐ์ํ๋ฉด console.log๋ก ์ฐ์ด๋ณด๋ ์ต๊ด์ ๊ฐ์ง์!