gpt4 book ai didi

ruby-on-rails - Bcrypt ruby​​ on rails

转载 作者:数据小太阳 更新时间:2023-10-29 08:30:41 26 4
gpt4 key购买 nike

大家好,我是 Rails 中 Bcrypt 的新手,我想知道如何正确使用这个 gem,到目前为止,我能够对密码进行哈希处理,但是当将它与用户输入的密码进行比较时,它不匹配。

这是我的加密和登录代码。

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 中,当使用 login 函数登录时,我使用 encrypt_password 函数对其进行加密。密码与数据库中加密的密码不匹配。我确定我没有以正确的方式做这件事,你能指出我在哪里做错了吗?谢谢。

最佳答案

这里的技巧是 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

这是有效的,因为密码对象的 == 方法被重写了。它没有进行文字字符串比较。

关于ruby-on-rails - Bcrypt ruby​​ on rails,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37717210/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com