alexi2 alexi2 - 5 months ago 6x
Ruby Question

Ruby BCrypt hash comparison not working

I am a new comer to Ruby, so apologies if this question has already been answered. I have read the other questions and still cannot figure out what I am doing wrong.

I am creating hashed passwords for storing in a db like this:

new_user.password = BCrypt::Password.create(unhashed_password)
# Write the user to database

I then retrieve the user from the db by checking against the inputed user name, and then check the password like this:

# Get user from the database
def self.get_user(check_user_name)
db = User.open_db
user =
user_arr = db.execute("SELECT * FROM user_data WHERE user_name = ?", check_user_name).first
# if the user exists check the password
if user_arr.size != 0
print "Enter your password : "
# Get password from user
user_input_password_attempt = gets.chomp
# Parse the db user into a user class if password guess is correct
stored_password =[2])
if user_input_password_attempt == stored_password
@@users_logged_in += 1
user.user_id = user_arr[0]
user.user_name = user_arr[1]
user.password = user_arr[2]
return user


My problem is that the var stored_password is returning a hash and != user_input_password_attempt
I have read the Ruby-Doc and googled this extensively


When you use == you are actually calling the == method defined on the object on the left hand side, passing the right hand side as argument:

a == b

is equivalent to


Depending on the object you call the == method you might receive a different result. In other words:

a == b

might or might not return a different result than

b == a

While personally I think this is nonsense and equality operators should be transitive, symetric and reflexive the BCrypt people have decided to implement it in another way:

def ==(secret)
  super(BCrypt::Engine.hash_secret(secret, @salt))

(taken from

This means that you have to write:

stored_password =[2])
if stored_password == user_input_password_attempt

in order to call the == method on the Password instance.