Node.js 使用bcryptjs模块进行密码加密
在提交表单时,有一些敏感数据(如密码)必须对任何人都不可见,甚至对数据库管理员也不可见。为了避免敏感数据对任何人可见,Node.js使用“bcryptjs”。
该模块使得将密码存储为哈希密码而不是明文密码成为可能。
安装bcryptjs模块:
您可以访问链接以安装bcryptjs模块。您可以使用以下命令来安装该包。
npm install bcryptjs
安装bcryptjs模块后,您可以使用以下命令在命令提示符中检查您的请求版本。
npm version bcryptjs
之后,您可以创建一个文件夹,并添加一个名为index.js的文件,要运行此文件,您需要运行以下命令。
node index.js
示例:
// Requiring module
const bcrypt = require('bcryptjs');
const password = 'pass123';
const hashedPassword;
// Encryption of the string password
bcrypt.genSalt(10, function (err, Salt) {
// The bcrypt is used for encrypting password.
bcrypt.hash(password, Salt, function (err, hash) {
if (err) {
return console.log('Cannot encrypt');
}
hashedPassword = hash;
console.log(hash);
bcrypt.compare(password, hashedPassword,
async function (err, isMatch) {
// Comparing the original password to
// encrypted password
if (isMatch) {
console.log('Encrypted password is: ', password);
console.log('Decrypted password is: ', hashedPassword);
}
if (!isMatch) {
// If password doesn't match the following
// message will be sent
console.log(hashedPassword + ' is not encryption of '
+ password);
}
})
})
})
运行应用程序的步骤: 使用以下命令运行应用程序:
node index.js
输出: 我们将在控制台屏幕上看到以下输出。
$2a$10$4DRBPlbjKO7WuL2ndpbisOheLfgVwDlngY7t18/ZZBFNcW3HdWFGm 加密密码为:pass123 解密密码为:$2a$10$4DRBPlbjKO7WuL2ndpbisOheLfgVwDlngY7t18/ZZBFNcW3HdWFGm
极客教程