Do I need to store the salt with bcrypt?
Asked Answered
R

1

209

bCrypt's javadoc has this code for how to encrypt a password:

String pw_hash = BCrypt.hashpw(plain_password, BCrypt.gensalt()); 

To check whether a plaintext password matches one that has been hashed previously, use the checkpw method:

if (BCrypt.checkpw(candidate_password, stored_hash))
    System.out.println("It matches");
else
    System.out.println("It does not match");

These code snippets imply to me that the randomly generated salt is thrown away. Is this the case, or is this just a misleading code snippet?

Roughandready answered 10/11, 2008 at 4:14 Comment(0)
D
237

The salt is incorporated into the hash (encoded in a base64-style format).

For example, in traditional Unix passwords the salt was stored as the first two characters of the password. The remaining characters represented the hash value. The checker function knows this, and pulls the hash apart to get the salt back out.

Demineralize answered 10/11, 2008 at 4:33 Comment(6)
The salt IS incorporated in the password. So you don't have to save the salt.Antennule
Thanks for that. I wish they said that in the javadoc :) (I've looked at the source and confirmed - but I didn't know what I was looking for before)Roughandready
Thanks - I was trying to figure this out too! Now I'm wondering if this is a good idea. Is there an advantage/disadvantage to keeping the salt in the hash over storing it separately?Subcontraoctave
@Subcontraoctave - As the salt is randomly generated, it means you don't need to have a method of associating the two things in your database.Roughandready
I took a look at the source code and discovered that although the JavaDoc for the salt argument is "perhaps generated using BCrypt.gensalt", I found that you have to use the genSalt() method or you get exceptions =/Brachylogy
Or have the salt in a very particular format. They may as well have excluded the salt as a parameter for the method and just called it internally. Testing the code with my own salt confirmed this (P.S. sorry for the double comment). This leads me to wonder just how secure this code really is (it may be fine... I'm just wondering)Brachylogy

© 2022 - 2024 — McMap. All rights reserved.