require 'bcrypt'
class User < ActiveRecord::Base
# users.password_hash in the database is a :string
include BCrypt
def password
@password ||= Password.new(password_hash)
end
def password=(new_password)
@password = Password.create(new_password)
self.password_hash = @password
end
end
似乎要访问密码方法,需要从create方法中调用它作为属性:
@user.password = user_params[:password]
@user.save
好的...那么呢?但是盐现在存储在哪里?我完全不明白,这怎么还算得上是安全的呢?
要检索哈希密码,您需要使用此方法:
def password
@password ||= Password.new(password_hash)
end
将其称为属性:
if @user.password == params[:password]
give_token
else
false
end
所以似乎没有盐也可以正常工作...它是如何做到的?
这意味着我现在只需要一个与密码有关的数据库列,对吧?使用password
或password_hash
代替password_salt | password_hash
?
那么为什么github页面会说这个:
But even this has weaknesses -- attackers can just run lists of possible passwords through the same algorithm, store the results in a big database, and then look up the passwords by their hash:
PrecomputedPassword.find_by_hash(<unique gibberish>).password #=> "secret1" Salts
然后这就是真正让我困扰的地方:
The solution to this is to add a small chunk of random data -- called a salt -- to the password before it's hashed:
为什么他们要解释这些,如果bcrypt已经自动处理了所有事情?
hash(salt + p) #=> <really unique gibberish>
The salt is then stored along with the hash in the database, and used to check potentially valid passwords:
<really unique gibberish> =? hash(salt + just_entered_password)
bcrypt-ruby automatically handles the storage and generation of these salts for you.
有人能解释一下bcrypt如何存储和生成这些盐值吗?为什么它说它会处理这一切,然后又告诉我如何生成盐值?我需要在我的模型中运行像这样的东西吗:self.password_hash = hash(salt + p)
?我曾经完全理解盐值和哈希值,现在他们改变了一切,让我感到困惑。文档很糟糕,不清晰......它们似乎向您展示如何使用没有盐值的bcrypt,并且有很多示例,然后在底部简要提到如何正确地使用盐值。
请问有人能给我一个如何使用新版本的bcrypt来生成盐值和哈希值以及如何进行身份验证的示例吗?
has_secure_password
。它可以为你管理存储密码这一极其复杂的任务,确保密码的安全性。 - user229044has_secure_password
使用 bcrypt,但我可能错了。 - user229044has_secure_password
,所以一切都很好。 - Starkers