Bcryptjs是一个用于对密码进行哈希和验证的库,它提供了同步和异步的解决方案。下面是使用Bcryptjs的同步和异步方法的代码示例:
同步解决方案:
const bcrypt = require('bcryptjs');
const password = 'myPassword';
const salt = bcrypt.genSaltSync(10);
const hash = bcrypt.hashSync(password, salt);
console.log('Password hash:', hash);
const isMatch = bcrypt.compareSync(password, hash);
console.log('Password match:', isMatch);
异步解决方案:
const bcrypt = require('bcryptjs');
const password = 'myPassword';
bcrypt.genSalt(10, function(err, salt) {
bcrypt.hash(password, salt, function(err, hash) {
console.log('Password hash:', hash);
bcrypt.compare(password, hash, function(err, isMatch) {
console.log('Password match:', isMatch);
});
});
});
在上述代码示例中,我们首先生成一个salt,然后使用该salt和密码进行哈希。哈希后,我们可以使用同步的compareSync
方法或异步的compare
方法来验证密码是否匹配。