我正在尝试使用Sinatra和BCrypt实现一种看似非常简单的身份验证方法,但显然我遗漏了一些东西...
用户会预先分配一个临时密码,该密码以明文形式存储在DB中。
我根据临时口令进行身份验证,然后创建salt和password_hash,并将它们作为字符串写入db(本例中为mongo)。
为了进行身份验证,我从db和用户口令中获取salt进行比较。
post "/password_reset" do
user = User.first(:email => params[:email], :temp_password => params[:temp_password])
if dealer != nil then
password_salt = BCrypt::Engine.generate_salt
password_hash = BCrypt::Engine.hash_secret(params[:password], password_salt)
user.set(:password_hash => password_hash)
user.set(:password_salt => password_salt)
end
end
post "/auth" do
@user = User.first(:email => params[:email])
@user_hash = BCrypt::Password.new(@user.password_hash) #because the password_hash is stored in the db as a string, I cast it as a BCrypt::Password for comparison
if @user_hash == BCrypt::Engine.hash_secret(params[:password], @user.password_salt.to_s) then
auth = true
else
auth = false
end
end
bcrypt::Engine.hash_secret返回的值(Params[:password],password_salt)与db中存储的值不同(两者都属于bcrypt::password,但不匹配)。
我错过了什么?非常感谢您的洞察力!
MARC
bcrypt::password
是String
的子类,它重写==
方法,以便更容易地检查密码。当你做的时候
if @user_hash == BCrypt::Engine.hash_secret(params[:password], @user.password_salt.to_s)
您将执行两次散列,因此它们不匹配。如果您直接与@user.password_hash
进行比较,而不是使用bcrypt::password.new
进行比较,您应该会看到它们是匹配的。
对密码使用bcrypt-ruby的更“正确”的方法是完全不使用engine
类,只使用password
类。您不需要自己管理salt,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
如果运行它,您将得到一些稍微不同的东西,因为将生成不同的salt,但您可以看到密码哈希包含salt。
在您的情况下,您需要这样的东西:
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