簡體   English   中英

BCRYPTJS:為不同的密碼返回相同的哈希值

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM