0

I am using bcryptjs to hash passwords and some other data (All strings), the problem is, when the value of my hashed variable goes over a certain length, bcryptjs compares only the first 71 characters.

Bcrypt in code represents bcrpytjs module:

const bcrypt = require("bcryptjs");

Then I made a random 140 char long string, and hashed it:

const generatedToken = `asdawvuirtienberyntrooniyuetnryuuweyrtwqertynt9ryw954t867q35vb9yupeo8iu798n87vq76t5tvr657tfodgiutiyun98w47ywb6n6e678aretuybaert6yae87br6ta87`;
const hashedToken = await bcrypt.hash(generatedToken, 12);

Then I set a new variable to only the first 75 characters of my generated Token compare the 2 and log the result:

const insertedToken = "asdawvuirtienberyntrooniyuetnryuuweyrtwqertynt9ryw954t867q35vb9yupeo8iu798"
const comparisonResult = await bcrypt.compare(insertedToken, hashedToken);
console.log(comparisonResult);

And I get true, I even get true if after the first 75 characters, there is more that doesn't match :

const insertedToken = "asdawvuirtienberyntrooniyuetnryuuweyrtwqertynt9ryw954t867q35vb9yupeo8iu798 RANDOM TEXT THAT DOES NOT MATCH"

But if only the first 71 characters match, I finally get false. so this method is only viable for variables less than 71 characters.

Is this on bcryptjs ? should I use something else or am I simply using it wrong?

Caliph Hamid
  • 335
  • 1
  • 10
  • 2
    See the fourth paragraph of the description on https://www.npmjs.com/package/bcryptjs . For background also see https://en.wikipedia.org/wiki/Bcrypt#Maximum_password_length . – dave_thompson_085 Jul 31 '22 at 17:27
  • 1
    This is by design, BCrypt has a maximum input length. But, what reason could you have for feeding such a long string to BCrypt? BCrypt is specifically for protecting short human-generated passwords, typically of questionable quality. BCrypt has no use when your inputs are long and cryptographically random. You probably want one of the SHA* family of functions for this purpose. – user229044 Aug 02 '22 at 16:12
  • I had a limit of 128 characters for passwords, after realizing the limit changed it to 64, 128 is very long but I dont like the idea of putting many limits on my password field, altho if the package (and afew others that I checked) dont support over 72 characters, allowing for more to my user is pointless – Caliph Hamid Aug 03 '22 at 13:07
  • @CaliphHamid - There is no reason to limit the password length, just accept any input the user enters. Even BCrypt will accept longer passwords, but uses "only" 72 chars of it, but this is more than enough form the viewpoint of security. – martinstoeckli Aug 08 '22 at 09:27

1 Answers1

0

Just to include the answer here, bcryptjs has a limit on 72 characters when it comes to hashing, anything after that gets ignored.

As a small note, its the hashing that has the limit, not .compare, anything after the 71th character gets totally ignored while hashing a string.

Caliph Hamid
  • 335
  • 1
  • 10