[英]BCRYPTJS: returning same hash for different passwords
我没有在谷歌上找到任何有类似问题的人,无论用户输入密码,它都会返回哈希值,就好像那是正确的密码一样,但是你可以输入任何内容,它仍然会在找到时返回与该邮件相同的哈希密码数据库中。
例如:
密码输入: asd
bcrypt: $2a$12$EkucFAxlupmAzec1CDnBmuYugwAO4cXj.5bt/thg8l/dG0JDhMScm
密码输入: astastas
bcrypt: $2a$12$EkucFAxlupmAzec1CDnBmuYugwAO4cXj.5bt/thg8l/dG0JDhMScm
代码:
exports.login = (req, res, next) => {
const email = req.body.email;
const password = req.body.password;
Users.findOne({ email: email }).then(result => {
if (!result) {
throw new Error('No user with that email');
}
else if (crypt.compare(password, result.password)) {
const token = jwebtoken.sign({ email: result.email },
'thisisatokenyoucantfake', { expiresIn: '1h' });
res.status(200).json({ token: token });
console.log(password);
console.log(result.password);
} else {
throw new Error('No user');
}
}).catch(err => console.log(err));
};
mongodb
atlas 用于存储散列密码,加密长度为12 。
如果有人需要解决方案:
exports.login = (req, res, next) => {
const email = req.body.email;
const password = req.body.password;
Users.findOne({ email: email }).then(result => {
if (!result) {
throw new Error('No user with that email');
} else {
return crypt.compare(password, result.password);
}
}).then(result => {
if (result) {
const token = jwebtoken.sign({ email: result.email },
'thisisatokenyoucantfake', { expiresIn: '1h' });
res.status(200).json({ token: token });
} else {
throw new Error('Wrong password');
}
}).catch(err => console.log(err));
};
bcrypt.compare是异步的——它返回一个承诺。 您的 if 语句将始终返回 true,因为 promise 是一个真实值。 您需要使用await
或.then()
来解析 promise 以获得结果布尔值。
此外,您正在记录输入的明文密码和存储的散列 - 存储的散列应始终与重点相同。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.