BCrypt::Password
是一个子类String
,和它覆盖== method https://github.com/codahale/bcrypt-ruby/blob/v3.0.1/lib/bcrypt.rb#L175-178使检查密码更加容易。当你这样做时
if @user_hash == BCrypt::Engine.hash_secret(params[:password], @user.password_salt.to_s)
你最终执行了哈希twice,所以它们不匹配。如果直接与@user.password_hash
而不是使用BCrypt::Password.new
你应该看到它们匹配。
使用 bcrypt-ruby 作为密码的更“正确”方法是不使用Engine
根本没有类,只是Password
班级。您不需要自己管理盐,bcrypt 会处理这个问题并将其包含在密码哈希字符串中:
password_salt = BCrypt::Engine.generate_salt
password_hash = BCrypt::Engine.hash_secret("s3kr1t!", password_salt)
puts password_salt
puts password_hash
产生这样的东西:
$2a$10$4H0VpZjyQO9SoAGdfEB5j.
$2a$10$4H0VpZjyQO9SoAGdfEB5j.oanIOc4zp3jsdTra02SkdmhAVpGK8Z6
如果运行它,您会得到稍微不同的结果,因为会生成不同的盐,但您可以看到密码哈希包含盐。
就你而言,你想要这样的东西:
post "/password_reset" do
user = User.first(:email => params[:email], :temp_password => params[:temp_password])
if dealer != nil then
password_hash = BCrypt::Password.create(params[:password])
user.set(:password_hash => password_hash) # no need to store the salt separately in the database
end
end
post "/auth" do
@user = User.first(:email => params[:email])
@user_hash = BCrypt::Password.new(@user.password_hash)
if @user_hash == params[:password] then # overridden == method performs hashing for us
auth = true
else
auth = false
end
end