205

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?

RodeoClown
  • 13,338
  • 13
  • 52
  • 56

1 Answers1

234

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.

ircmaxell
  • 163,128
  • 34
  • 264
  • 314
Greg Hewgill
  • 951,095
  • 183
  • 1,149
  • 1,285
  • 64
    The salt IS incorporated in the password. So you don't have to save the salt. – Swapnonil Mukherjee Nov 10 '08 at 08:57
  • 2
    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) – RodeoClown Nov 10 '08 at 22:17
  • 1
    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? – Adam Jan 12 '11 at 21:58
  • 8
    @Adam - As the salt is randomly generated, it means you don't need to have a method of associating the two things in your database. – RodeoClown Jan 26 '11 at 20:39
  • 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 =/ – the_new_mr Jan 31 '13 at 18:17
  • 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) – the_new_mr Jan 31 '13 at 18:34