Ruby on rails Bcrypt ruby on rails

Ruby on rails Bcrypt ruby on rails,ruby-on-rails,ruby,bcrypt,Ruby On Rails,Ruby,Bcrypt,嗨,我是rails中Bcrypt的新手,我想知道如何正确使用这个gem,到目前为止,我能够对密码进行哈希处理,但是当将它与用户输入的密码进行比较时,它不匹配 这是我的加密和登录代码 def self.login(user) hashed_password = encrypt_password(user["password"]) result = User.where({:username => user["username"], :password => hashed

嗨,我是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_用户中,当使用login函数登录时,我使用encrypt_password函数对其进行加密。密码与数据库中加密的密码不匹配。我肯定我做得不对,你能指出我做错了什么吗。谢谢。

这里的诀窍是,每次使用设计相同的密码运行时,都会创建不同的结果。这使得函数的输出极不可预测,因此暴力猜测密码是不切实际的

您验证的方式是:

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
您验证的方式是:

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

这是因为密码对象的
=
方法被覆盖。它没有进行文本字符串比较。

请注意,可以在
x({…})
形式的调用中省略哈希大括号,因为它们在Ruby中是隐式的。例如:
User.create(:username=>User['username'],…)
或者更好的
User.create(username:User['username'],…)
使用现代散列符号。谢谢你的提示,但这不是我现在最关心的问题。我已经将登录功能更改为这个。def self.login(user)result=false散列密码=encrypt密码(user[“password”])user=user.where({:username=>user[“username”]})if BCrypt::password.new(散列密码)==user[0]。password result=true end返回结果end并给出无效散列的结果。这意味着什么?我不得不在这里进行编辑,因为我混淆了
user
user