3

我正在尝试 bcrypt-ruby gem,我编写了以下代码来生成随机密码并验证它

require 'bcrypt'
require 'securerandom'

def encrypt_token(tok)
    BCrypt::Password.create(tok)
end

def check_token(enc,tok)

    g = BCrypt::Password.new(enc)

    if tok==g
       puts 'equal'
    else
       puts 'not equal'
    end 
end

s = SecureRandom.hex(12)

puts s

e = encrypt_token(s)

puts e

check_token(e,s)

代码不断打印“不等于”而不是“等于”。我哪里错了?谢谢 :)

4

1 回答 1

3

bcrypt 具有自动加盐功能。您不能比较同一字符串的两个 bcrypt,它们会有所不同。

尝试像这样比较:

def check_token(enc,tok)

  if enc == tok #We compare it with the unencrypted string.
    puts 'equal'
  else
    puts 'not equal'
  end 

end

诀窍是当创建一个新的 bcrypt 时,你最终会得到一个覆盖==操作符的 Password 对象。它将针对未加密的字符串检查密码是否正确。

也正因为如此,要小心:在上面的例子中,比较enc == tok有效。比较tok == enc不会,因为您将使用==来自class String

看看这里的文档和源代码:http: //bcrypt-ruby.rubyforge.org/

于 2012-08-04T03:38:28.383 回答