密码加密

bcryptjs

使用bcryptjs对密码进行加密,

安装bcryptjs库:

1
npm i bcryptjs

bcryptjs使用方法:

1
2
3
4
5
6
7
const bcrypt = require('bcryptjs')

// 生成10位数的盐
const salt = bcrypt.genSaltSync(10)

// 对字符进行加密
const hash = bcrypt.hashSync('明字符串', salt)

简写:

1
const hash = bcrypt.hashSync('明文字符串', 10)

当表单获取到用户设置的password后,需要在传入数据库的过程中,对密码进行加密,
这一步需要在model字段对应的set函数中处理:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
password: {
type:DataTypes.STRING,
allowNull:false,
// validate:{
// notNull:{msg:'密码必须存在'},
// notEmpty:{msg:'密码不能为空'},
// len:{
// args:[8,30],
// msg:'密码长度应当在8-30个字符之间'
// }
// },
set(value){
if(!value){
throw new Error('密码必须填写')
}
if(value.length < 6 || value.length > 45){
throw new Error('密码长度必须在6~45之间')
}
// 进行加密
this.setDataValue(
'password',
bcrypt.hashSync(value, 10)
)
}
}

将来的登录时,需要使用bcrypt.compareSync对加密后的字符串和明文字符串进行比较:

1
const isPasswordValid = bcrypt.compareSync("12345","加密后的字符串")