node.bcrypt.js icon indicating copy to clipboard operation
node.bcrypt.js copied to clipboard

bcrypt.compare is always returning true for jwt tokens

Open saiprasad31 opened this issue 3 years ago • 2 comments

  • What went wrong? I'm using bcrypt to hash and store the refresh tokens (created by jsonwebtoken library) in the database. I'm trying to compare previous refresh token with the hashed token(of previous refresh token) while issuing new tokens.

bcrypt.compare() function is returning true every time even if I pass a different jwt token which is not stored in the DB(jwt which is created using the same payload. It's returning false for the jwt created with a different payload)

I'm assuming it's not hashing or comparing the signature part of the jwt because the payload and header part of the jwt is identical every time.

  • What did you expect to happen? To return false if the token and hashed token are different

  • Which version of nodejs and OS? Node version = 16.13.2 OS = windows 10

saiprasad31 avatar Jun 05 '22 11:06 saiprasad31

I believe this may be caused by the limitations outlined here.

Per bcrypt implementation, only the first 72 bytes of a string are used. Any extra bytes are ignored when matching passwords. Note that this is not the first 72 characters. It is possible for a string to contain less than 72 characters, while taking up more than 72 bytes (e.g. a UTF-8 encoded string containing emojis).

JoltCode avatar Jun 18 '22 09:06 JoltCode

Faced with the same issue,.. decided to use 'argon2'

additional info: https://www.monterail.com/blog/more-secure-passwords-bcrypt

anboch avatar Aug 28 '22 01:08 anboch

bcrypt uses the first 72 bytes, which, depending on what is inside your JWT token is probably the same.

Either run SHA-256 on the value first and then pass to bcrypt or use a different algorithm.

Also, you are probably using JWT tokens in an incorrect way. You should not be storing tokens, instead storing certain attributes of it, like an id. The point of JWT is to be as stateless as possible

recrsn avatar Nov 07 '22 08:11 recrsn