Home > Software design >  bcrypt comparesync always returns false for same strings
bcrypt comparesync always returns false for same strings

Time:10-30

Bcrypt compare and compareSync always returns false even though the strings are exactly the same? I have console.log them to verify they're the same, and that they're not being hashed twice etc. Such an odd issue. I have already tried the solutions on the other similar questions.

model.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);

console output:

enter image description here

CodePudding user response:

The problem:

Here is what the .compare() function does, from the bycryptjs source:

  • Asynchronously compares the given data against the given hash.
  • @param {string} s Data to compare
  • @param {string} hash Data to be compared to

Here is an example of proper usage for that function

  const hash = await bcrypt.hash("foo", 8);
  const res = await bcrypt.compare("foo", hash)
  console.log(res) // true

What your code is doing is comparing a string to itself, instead of comparing a string to its hash. .compare(a,b) is not the same as a===b.

Possible Solutions:

In your code, you reassign the original token to the new hashed one with this line of code in the .pre() function:

this.token = encryptedToken;

If you remove this line, your code will work.

Alternatively, if you really do want that reassignment, then you'll have to change what you're doing, and store the original token somewhere else if you want to compare against it later.

  • Related