即使字串完全相同,Bcrypt compare 和 compareSync 總是回傳 false?我有 console.log 它們來驗證它們是否相同,并且它們沒有被哈希兩次等。這是一個奇怪的問題。我已經嘗試過其他類似問題的解決方案。
模型.js
import mongoose from "mongoose";
import bcrypt from "bcryptjs";
const ResetTokenSchema = new mongoose.Schema({
owner: {
type: mongoose.Schema.Types.ObjectId,
ref: "Doctor",
required: true,
},
token: {
type: String,
required: true,
},
createdAt: {
type: Date,
expires: 3600, //expires after an hour
default: Date.now(),
},
});
// HASH token before storing
ResetTokenSchema.pre("save", async function (next) {
if (this.isModified("token")) {
const encryptedToken = await bcrypt.hash(this.token, 8);
this.token = encryptedToken;
console.log("the token is" this.token)
}
next();
});
ResetTokenSchema.methods.compareToken = async function (encryptedToken) {
const result = await bcrypt.compare(encryptedToken, this.token);
console.log(this.token)
console.log(encryptedToken)
console.log(result)
return result;
};
export default mongoose.model("ResetToken", ResetTokenSchema);
控制臺輸出:

uj5u.com熱心網友回復:
問題:
下面是.compare()函式的作用,來自bycryptjs 源代碼:
- 將給定資料與給定哈希進行異步比較。
- @param {string} s 要比較的資料
- @param {string} hash 要比較的資料
這是該功能的正確用法示例
const hash = await bcrypt.hash("foo", 8);
const res = await bcrypt.compare("foo", hash)
console.log(res) // true
您的代碼所做的是將字串與其自身進行比較,而不是將字串與其哈希進行比較。.compare(a,b)不一樣。_a===b
可能的解決方案:
在您的代碼中,您使用.pre()函式中的這行代碼將原始令牌重新分配給新的哈希令牌:
this.token = encryptedToken;
如果洗掉此行,您的代碼將起作用。
或者,如果您確實想要重新分配,那么您將不得不更改您正在做的事情,并將原始令牌存盤在其他地方,如果您想稍后與它進行比較。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/524248.html
