嗨我刚刚接触到Bcrypt在rails中,我想知道如何正确使用这个gem,截至目前我能够使密码进行哈希处理但是当它与用户输入的密码相比时它不匹配。< / p>
这是我的加密和登录代码。
def self.login(user)
hashed_password = encrypt_password(user["password"])
result = User.where({:username => user["username"], :password => hashed_password})
return result
end
def self.add_user(user)
hashed_password = encrypt_password(user["password"])
result = User.create({:username => user["username"],
:password => hashed_password,
:firstname => user["firstname"],
:middle_initial => user["middle_initial"],
:lastname => user["lastname"],
:advisory_class => user["advisory_class"]})
return result
end
def self.encrypt_password(password)
password_salt = BCrypt::Engine.generate_salt
password_hash = BCrypt::Engine.hash_secret(password,password_salt)
end
在add_user中,当使用登录功能登录时,我使用encrypt_password函数对其进行加密。密码与数据库中生成的密码不匹配。我确定我不是以正确的方式做到这一点,你能指出我在做错的地方。感谢。
答案 0 :(得分:5)
这里的诀窍是BCrypt每次使用相同的密码按设计运行时都会创建不同的结果。这使得函数的输出极不可预测,因此强制猜测密码是不切实际的。
您验证的方式是:
hashed_password = BCrypt::Password.create(user['password'])
您验证的方式是:
if @user = User.where(username: user['username'])
# User found
if BCrypt::Password.new(@user.password) == user['password']
# Success!
else
# Invalid password
end
else
# User not found
end
这是有效的,因为密码对象会覆盖==
方法。它没有进行文字字符串比较。