第三方模块bcrypt
Galloping_Leo 2020-02-12 node第三方模块
# 第三方模块 bcrypt
密码加密 bcrypt
是一种使用哈希算法加密的第三方模块,只能加密不能解密。在加密的密码中加入随机字符串可以增加密码被破解的难度。
# 环境要求
bcrypt
依赖的环境
python 2.x
首先安装
python 2.x
node-gyp
然后使用
npm install -g node-gyp
安装node-gyp
windows-build-tools
最后安装
npm install --global --production windows-build-tools
# 使用
# 密码加密
首先导入bcrypt
模块
const bcrypt = require('bcrypt')
1
生成随机字符串(盐)
let salt = await bcrypt.genSalt(10)
1
使用随机字符串,对密码进行加密
let pass = await bcrypt.hash('明文密码', salt)
1
注意
bcrypt.genSalt(num)
此函数生成一个随机字符串(salt
)。参数为一个数值,数值越大,生成的字符串复杂度越高,默认值是10。
# 密码比对
密码比对
let isEqual = await bcrypt.compare('明文密码', '加密密码')
1
注意
bcrypt.genSalt
、bcrypt.hash
方法返回的是promise
对象。可在异步函数中使用await
关键字,改成同步代码。
# 示例
const bcrypt = require('bcrypt')
let run = async ()=> {
let salt = await bcrypt.genSalt(10)
let pass = await bcrypt.hash('123456', salt)
let isEqual = await bcrypt.compare('123', pass)
console.log('salt: ' + salt)
console.log('pass: ' + pass)
console.log('isEqual: ' + isEqual)
}
run()
/*
结果
salt: $2b$10$DDxjIUOmaXCZuiFYYVrLoe
pass: $2b$10$DDxjIUOmaXCZuiFYYVrLoeGZ2.Wqv9zYvjbt5G2o4OV2Xuc0aiYDK
isEqual: false
*/
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19