【问题标题】:Bcrypt ruby on railsBcrypt Ruby on rails
【发布时间】:2016-10-09 14:09:39
【问题描述】:

嗨,我是 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 功能对其进行加密。密码与数据库中加密的密码不匹配。我确定我没有以正确的方式这样做,你能指出我在哪里做错了吗?谢谢。

【问题讨论】:

  • 请注意,在 x({...}) 形式的调用中可以省略散列括号,因为它们在 Ruby 中是隐含的。例如:User.create(:username => user['username'], ...) 甚至更好的 User.create(username: user['username'], ...) 使用现代哈希表示法。
  • 感谢您的留言,但这不是我现在最关心的问题。

标签: ruby-on-rails ruby bcrypt


【解决方案1】:

这里的诀窍是 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

这是因为 == 方法被 Password 对象覆盖。它不是在进行文字字符串比较。

【讨论】:

  • 我已将登录功能更改为此。 def self.login(user) result = false hashed_pa​​ssword = encrypt_password(user["password"]) user = User.where({:username => user["username"]}) if BCrypt::Password.new(hashed_pa​​ssword) == user[0].password result = true end 返回结果 end 并给出无效哈希的结果。这是什么意思?
  • 我不得不在这里进行编辑,因为我混淆了useruser
猜你喜欢
  • 2014-04-17
  • 1970-01-01
  • 1970-01-01
  • 2013-10-10
  • 2011-04-15
  • 2015-03-02
  • 2011-04-18
  • 2018-11-20
  • 2014-03-20
相关资源
最近更新 更多