如何在Ruby中使用BCrypt比较2个密码?

3
我正在使用名为"bcrypt"的宝石。这是一个Rack应用程序。一旦我创建了一个密码哈希并将其存储在我的数据库中,
    # register a user

    plain_pass = get_input_from_user
    pass_hash = BCrypt::Password.create(params["pass"])

    # store in db
    # ......

我该如何与用户提供的“纯文本”进行比较?
    email = get_user_email
    usr = User.first(email: params["email"])

    plain_pass = params["pass"]
    pass_hash = ?????
    if usr.pass_hash == pass_hash
      # ok, all good

问题在于Password.create每次都会创建一个新的密码,即使输入相同:
irb(main):038:0> BCrypt::Password.create("aaa")
=> "$2a$10$CCWMcREb5mP2ldFshb4qiua.VK2ABHXCtDSzj2WwYf/KsZQjoDGoO"

irb(main):039:0> BCrypt::Password.create("aaa")
=> "$2a$10$w9rAu9FmLZ/jQ7IQmXutW.nh272ucS0PsIrMYUMBrDQpt4U70wOqa"
1个回答

4

确保使用 == 进行比较。你的示例展示了赋值操作 (=)。

Bcrypt::Password 重写了 == 方法,这是你应该用来比较密码的方式:

crypted_password = Bcrypt::Password.create("foobarbaz")
# save crypted_password to db

# Presumably later on when your user returns
BCrypt::Password.new(crypted_password) == "foobarbaz" # => true

那对我有什么帮助呢? - jerry
你没有理解我的问题。 - jerry
确实,您还需要使用BCrypt::Password.new - Aaron Breckenridge
1
如果有人想要更详细的了解,请参考 https://dev59.com/W6Lia4cB1Zd3GeqPq_Bf#44778735。 - Sam

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接