Oleg Ivanytskyi
Oleg Ivanytskyi

Reputation: 1091

How does password checking in bcrypt work?

So, I found the following example in bcrypt docs:

password = b"super secret password"
hashed = bcrypt.hashpw(password, bcrypt.gensalt())
if bcrypt.checkpw(password, hashed):
    print("It Matches!")
else:
    print("It Does not Match :(")

And it seems to work. But I don't understand how. Shouldn't we use salt to generate a hash for checking?

I mean, we generated salt once and didn't save it in a variable. But then we want to compare the hash and the password with the function checkpw, but how does it know which salt to use to generate a hash for comparison?

Upvotes: 7

Views: 9778

Answers (2)

LSerni
LSerni

Reputation: 57418

The generated "hash" also contains the salt. It is in the Modular Crypt Format, documented here (thanks @Masklinn)

$2a$10$N9qo8uLOickgx2ZMRZoMyeIjZAgcfl7p92ldGxad68LJZdL17lhWy
      |<---    salt     --->||<---- confirmation hash ---->|

The "2a" part gives information on the modular hash being used, "10" is the logarithmic cost parameter (i.e. the algorithm is to be iterated 210 times).

So, to verify that a password matches, you'll restart the bcrypt using the decoding of N9qo8uLOickgx2ZMRZoMye as a salt.

Upvotes: 10

Tom B&#246;ttger
Tom B&#246;ttger

Reputation: 655

The salt gets saved in the hash itself. The scheme for bcrypt looks like the following:

$<used_algorithm>$<cost_factor>$<generated_salt><hash>$

Upvotes: 5

Related Questions