在使用bcryptjs进行密码加密之前,首先安装bcryptjs模块。然后,使用以下代码示例来加密密码并将其存储到MongoDB中:
const bcrypt = require('bcryptjs'); const saltRounds = 10; // 盐值轮数可以自由设定
// 用户注册时生成加密密码 const password = 'myPassword'; bcrypt.genSalt(saltRounds, function(err, salt) { bcrypt.hash(password, salt, function(err, hash) { if(err) throw err; // 将密码哈希值存储到MongoDB User.create({username: 'myUsername', password: hash}, function(err, user) { if (err) console.log(err); console.log(user); }); }); });
在用户登录时,使用以下代码示例来验证密码是否匹配:
const password = 'myPassword'; User.findOne({username: 'myUsername'}, function(err, user) { if(err) throw err; bcrypt.compare(password, user.password, function(err, result) { if (err) throw err; if(result == true){ console.log('Passwords match!'); } else { console.log('Passwords do not match!'); } }); });
这样,即使黑客获得了您的数据库的访问权限,他们也不能看到用户的密码,因为它们被存储为加密哈希值。