简体   繁体   English

Ruby BCrypt密码比较返回错误的评估

[英]Ruby BCrypt password comparisons return incorrect evaluation

In order to store my user's passwords securely, I'm attempting to use BCrypt in my Sinatra/Ruby application. 为了安全地存储用户密码,我试图在我的Sinatra / Ruby应用程序中使用BCrypt。

The following code is of my User model. 以下代码是我的用户模型的代码。

require 'mongo_mapper'
require 'bcrypt'

# User model
class User
    include MongoMapper::Document
    include BCrypt

    key     :email,         String,         length: 6..50,      unique: true
    key     :password,      String
    key     :password_hash, String

    def password
        @password ||= Password.new(password_hash)
    end

    def password=(new_password)
        @password = Password.create(new_password)
        self.password_hash = @password
    end

    def self.authenticate(requested_email, requested_password)
        u = self.find_by_email(requested_email)
        u if u && u.password_hash == requested_password
    end
end

# Test user account
if User.count == 0
    user = User.new(email: "bar@foo.com")
    user.password = "admin"
    user.save
end

When I call the authenticate method like so: User.authenticate("bar@foo.com", "admin") , the code returns false. 当我这样调用authenticate方法时: User.authenticate("bar@foo.com", "admin") ,代码返回false。 I am certain the user exists. 我确定该用户存在。

EDIT: u.password == requested_password returns false as well 编辑: u.password == requested_password返回false

Why does this happen, even when the values being passed to the method are valid and correct? 即使传递给该方法的值有效且正确,为什么还会发生这种情况?

create a key called secret, delete password and password_hash. 创建一个称为secret的密钥,删除password和password_hash。

Change your code to: 将您的代码更改为:

def password=(password)
  self.secret = BCrypt::Password.create(password)
end

def password
  return BCrypt::Password.new(secret) if self.secret
  nil
end

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM