26

I'm confused with bcrypt, I would think I would need to store my salt, and then compare my plain text password + salt to the hashed password, however from documentation it does not look like storing the salt is necessary at all. Indeed I used this code to create salt and hashed password:

  let salt = await bcrypt.genSalt(10);

  const saltpasshash = await new Promise((resolve, reject) => {
    bcrypt.hash(plain_text_password, salt, function(err, hash) {
      if (err) reject(err)
      resolve(hash)
    });
  })

  //NOTE I SAVE saltpasshash as users pass and the salt in a separate field in the users table.

This works, what I am confused about is it will then return a valid result if I compare as follows:

valid = await bcrypt.compare(plain_text_password, user.saltpasshash);

I'm confused as to why this would be valid when I am not providing the salt, and if so, why store the salt at all?

edencorbin
  • 363
  • 1
  • 3
  • 7
  • 2
    As far as I know, bcrypt does store the salt alongside the number of iterations in the hash result itself. – Tobi Nary Apr 28 '18 at 14:46

1 Answers1

30

From a description of bcrypt at Wikipedia:

... The rest of the hash string includes the cost parameter, a 128-bit salt (Radix-64 encoded as 22 characters), and 184 bits of the resulting hash value (Radix-64 encoded as 31 characters)

Thus, the salt is automatically included in the output string which means there is no need to add it by yourself.

Steffen Ullrich
  • 184,332
  • 29
  • 363
  • 424
  • Hi Steffen:) Always happy to see my comments made into an answer;) – Tobi Nary Apr 28 '18 at 14:49
  • 2
    @SmokeDispenser: always a pleasure to beat you :) – Steffen Ullrich Apr 29 '18 at 17:35
  • 2
    Isn't storing the salt in the output a bad idea? If an attacker gets the hash, they already know the salt. – Titulum Jun 24 '19 at 07:03
  • 2
    @Titulum: I think you need to understand the purpose of the salt first. Then you'll understand why it does not matter if the attacker knows it. See for example [How to store salt?](https://security.stackexchange.com/questions/17421/how-to-store-salt) for an explanation. – Steffen Ullrich Jun 24 '19 at 07:10
  • 1
    I see, `The goal of the salt is only to prevent pre-generated databases from being created`. – Titulum Jun 24 '19 at 07:13