Bcrypt给用户系统加密 / 网络研习社#81

in STEEM CN/中文last year

crypto.jpg

MongoDB开发还蛮顺利,操作什么的基本也都摸熟了。现在开始设计数据库的格式和用户系统。在用户系统中的用户密码是需要加密保存的,用什么加密比较好呢?

Bcrypt是不错的方案! 在网上查了不少方法, Bcrypt被推荐得比较多。从各方面来比较, Bcrypt也算是比较适宜的方案。

基本使用:

import bcrypt from 'bcrypt'

const saltRounds = 10
const myPlaintextPassword = 's0/\/\P4$$w0rD'
const someOtherPlaintextPassword = 'not_bacon'

const salt = bcrypt.genSaltSync(saltRounds)
const hash = bcrypt.hashSync(myPlaintextPassword, salt)  //获取加密后的哈希值

// 密码校验
bcrypt.compareSync(myPlaintextPassword, hash) // true 
bcrypt.compareSync(someOtherPlaintextPassword, hash) // false

MongoDB Model

import mongoose from 'mongoose'

mongoose.connect('mongodb://jixxx:pwd@localhost:27017/users?authSource=admin') 
.then(() => console.log('Connected!'))
.catch(error => console.log(44, error))

const { Schema } = mongoose

// 定义一个用户模型,username是唯一的索引,表示不能被重复
const UserSchema = new Schema({
  username: { type: String, unique: true },
  password: { 
    type: String, 
    set(val) {
      let salt = bcrypt.genSaltSync(saltRounds)
      let hash = bcrypt.hashSync(val, salt)
      return hash
    }
  },
})

const User = mongoose.model('User', UserSchema)

在定义模型时,使用set(val) 对用户密码加密保存,感觉还是蛮顺利的。在用户登录时则使用bcrypt.compareSync(pwd, hash)来进行校验,为true 则是真实用户,反之则不通过。

Coin Marketplace

STEEM 0.20
TRX 0.14
JST 0.030
BTC 64870.15
ETH 3489.66
USDT 1.00
SBD 2.54