2016-04-25 80 views
0

我是Ruby的新来者,所以如果这个问题已经得到解答,我很抱歉。我已经阅读了其他问题,但仍然无法弄清楚我做错了什么。红宝石BCrypt哈希比较不起作用

我在这样一个数据库存储创建散列密码:

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

我然后靠在输入的用户名检查检索数据库的用户,然后检查密码这样的:

# Get user from the database 
def self.get_user(check_user_name) 
db = User.open_db 
user = User.new 
user_arr = db.execute("SELECT * FROM user_data WHERE user_name = ?", check_user_name).first 
db.close 
# 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 
end 
# Parse the db user into a user class if password guess is correct 
stored_password = BCrypt::Password.new(user_arr[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 
end 
:no_user 

我的问题是,VAR stored_pa​​ssword返回一个哈希和!= user_input_password_attempt 我已阅读ŧ他Ruby的文档和Google搜索这个广泛

+0

根据[documentation](http://bcrypt-ruby.rubyforge.org/classes/BCrypt/Password.html),'=='是'Password'的自定义方法之一。所以,认为它应该是'如果stored_pa​​ssword == user_input_password_attempt',而不是相反。 –

+0

它的工作原理是这样的:if BCrypt :: Password.new(user_arr [2])== user_input_password_attempt – alexi2

回答

0

当您使用==你实际上是在呼吁左侧的对象上定义的==方法,将右侧作为参数:

a == b 

相当于到

a.==(b) 

根据您调用==方法的对象,您可能会收到不同的结果。换句话说:

a == b 

可能会或可能不会返回不同的结果比

b == a 

虽然我个人认为这是废话,平等运营商应该是transitivesymetricreflexive的BCrypt人民决定实现它以另一种方式:

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

(从http://bcrypt-ruby.rubyforge.org/classes/BCrypt/Password.html#M000009拍摄)

这意味着你必须写:

stored_password = BCrypt::Password.new(user_arr[2]) 
if stored_password == user_input_password_attempt 
    ... 
end 

为了呼吁Password实例==方法。

+0

是的,现在完美。 – alexi2