1

My question is about hashing procedure.

const bcrypt = require('bcrypt');
const saltRounds = 10;
var password = "Fkdj^45ci@Jad";  // Original Password
var password2 = "djlfhjd(456"; // Wrong Password
bcrypt.hash(password, saltRounds, function(err, hash) {
    bcrypt.compare(password2, hash, function(err, result) {
        ...
    });
});

This is a code snippet for hashing with salt and comparing. I can't understand how it is possible to compare hash and password without knowing salt. bcrypt is using Blowfish now, but how is it possible for a having algorithm to compare a password and a hash value without knowing salt?

tkius123
  • 26
  • 2

1 Answers1

1

It isn't. The output of bcrypt.hash includes that information. For example, when I run your code, the value of hash is:

$2b$10$ytoRP21isLcU43jpdiDi4ebR5aKfydE.cHt6VkoH3suODa64JUvEy

This is the "2b" format, with a cost of 10, a salt of ytoRP21isLcU43jpdiDi4e (first 22 characters) and a hash of bR5aKfydE.cHt6VkoH3suODa64JUvEy (last 31 characters). The salt and hash are "radix-64 encoded," which is similar to Base64 encoding, but uses a different table.

When you pass this to .compare, it uses the same cost and salt. This is why you need a special .compare method rather than just computing the hash on both inputs and comparing the outputs.

Rob Napier
  • 286,113
  • 34
  • 456
  • 610
  • It seems that the position and the length of salt are fixed in the hash. Then what makes this hash more unpredictable as long as we can tell salt from hash? – tkius123 Sep 30 '22 at 18:13
  • What do you mean by "more unpredictable" here? For a given input, hashes are completely predictable. The unpredictability of the output comes from the salt (which is part of the input) being random. – Rob Napier Sep 30 '22 at 18:45
  • Thanks for your reply. What I want to know is if we add salt, what benefit we get. – tkius123 Oct 03 '22 at 17:30
  • You avoid rainbow tables. If there is no salt, I can just hash a bunch of well-known and likely passwords into a big database, and then I can quickly look up if you have a well-known password. If every user has a different salt (because they're random), then the thing hashed will be unique, even if the password is common. So my database won't work. https://stackoverflow.com/questions/420843/how-does-password-salt-help-against-a-rainbow-table-attack – Rob Napier Oct 04 '22 at 03:17