ency_pass = BCrypt::Password.create("testing")
new_pass = "testing"
Let’s look at how we compare two bcrypt hashes, one coming from the database & one from user input (like a form or something like that).
BCrypt::Password.new(ency_pass) == new_pass
# true
BCrypt::Password.new(ency_pass) == "testing2"
#false
The part on the left (BCrypt::Password.new)
is a BCrypt object, which takes the hash stored in the database as a parameter.
The part on the right (new_pass) is just the plain-text password that the user is trying to log in with.
Let's understand this things:
BCrypt uses something called a “salt”, which is a random value used to increase security against pre-computed hashes. The salt is stored in the hash itself.
BCrypt defines its own == method, which knows how to extract that “salt” value so that it can take that into account when comparing the passwords.
BCrypt#== takes the “salt” value from the stored hash, then it hashes the plain-text password (the user input) using this salt so that both hashes will be identical if the password is valid.
If you were to look at the source code it would look something like this:
def ==(secret)
super(
BCrypt::Engine.hash_secret(secret, @salt)
)
end
Remember that super will call the same method (in this case ==) on the parent class. The parent class of BCrypt::Password is String.