2016-04-25 78 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