2
router.post("/login", async (req, res) => {
  try {
    const user = await User.findOne({ email: req.body.email });
    if (!user) return res.status(401).json("Wrong Credentials!");
    var salt = process.env.SALT; //SALT
    var hashedPassword = CryptoJS.PBKDF2(req.body.masterPassword, salt, {
      //HASHED PWD
      keySize: 256 / 32,
    });
    const decryptedPassword = CryptoJS.AES.decrypt(
      user.masterPassword,
      process.env.PASS_SEC
    ).toString();
    console.log(decryptedPassword+" "+hashedPassword)

    if (hashedPassword === decryptedPassword) {
      res.status(200).json(user);
    } else {
      res.status(401).json("pwd dont match!");
    }
  } catch (err) {
    res.status(500).json(err);
  }
});

console.log(decryptedPassword+" "+hashedPassword) returns 8da9d88c32a0246a66ed3a70b8e3a9c34d46112ebb3b2e891172e5773bfa80dd 8da9d88c32a0246a66ed3a70b8e3a9c34d46112ebb3b2e891172e5773bfa80dd

  • Not sure, but this question may be related : https://stackoverflow.com/questions/32845912/nodejs-crypto-pbkdf2-result-is-different-from-cryptojs-pbkdf2 – Jeremy Thille Jan 06 '22 at 08:54
  • Blind guess, try adding `.lean()` to your Mongoose query, so you get pure JSON and not a collection of Mongoose objects (Mongoose can be weird). Optionally, also add `.exec()` so you get a true Promise instead of a thenable. `User.findOne({...}).lean().exec()` – Jeremy Thille Jan 06 '22 at 08:56
  • @JeremyThille as for the link you have sent i dont have such issues since I'm only using crypto js and my hashes from db and user are identical but still postman returns 401, as for mongoose my query works fine because if I clg user it returns user object – saahil sabu Jan 06 '22 at 09:12
  • 1
    Your query returns a Mongoose object, not JSON data. There is a chance that it is related to your problem. You can also try to `.trim()` both strings. Also check that they are both strings and not weird objects with `typeof decryptedPassword` and `typeof hashedPassword`, but really, other than that, I don't know. – Jeremy Thille Jan 06 '22 at 12:00
  • @JeremyThille thank you soo much Jeremy typeof decryptedPassword and typeof hashedPassword were returning object and string . – saahil sabu Jan 07 '22 at 04:59
  • 1
    Ha nice, I was suspecting something like that :) – Jeremy Thille Jan 07 '22 at 07:40

0 Answers0