首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >BCRYPTJS:对不同密码返回相同的散列

BCRYPTJS:对不同密码返回相同的散列
EN

Stack Overflow用户
提问于 2020-01-03 16:11:24
回答 1查看 372关注 0票数 0

我在google上没有发现有类似问题的人,不管用户输入密码,都会返回哈希,就好像密码是正确的一样,但是你可以输入任何东西,当它在数据库中找到时,它仍然会返回相同的哈希密码。

例如:

密码输入:asd

bcrypt:$2a$12$EkucFAxlupmAzec1CDnBmuYugwAO4cXj.5bt/thg8l/dG0JDhMScm

密码输入:astastas

bcrypt:$2a$12$EkucFAxlupmAzec1CDnBmuYugwAO4cXj.5bt/thg8l/dG0JDhMScm

代码:

代码语言:javascript
复制
    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图集用于存储散列密码,加密长度为12

如果有人需要解决办法:

代码语言:javascript
复制
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));
};
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-01-03 16:18:30

bcrypt.compare是异步的--它返回一个承诺。您的if语句将始终返回true,因为承诺是一个真实的值。您需要使用await.then()来解析承诺,以获得结果布尔值。

此外,您正在记录输入明文密码和存储的哈希-存储的哈希应该始终是相同的,这是重点。

票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/59581764

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档