Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does password checking in bcrypt work?

Tags:

python

bcrypt

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?

like image 684
Oleg Ivanytskyi Avatar asked Jul 17 '26 07:07

Oleg Ivanytskyi


2 Answers

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.

like image 198
LSerni Avatar answered Jul 19 '26 19:07

LSerni


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

$<used_algorithm>$<cost_factor>$<generated_salt><hash>$
like image 35
Tom Böttger Avatar answered Jul 19 '26 21:07

Tom Böttger