我正在试用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)代码继续打印“不相等”而不是“相等”。我哪里错了?谢谢:)
发布于 2012-08-04 11:38:28
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是可行的。由于您将使用class String中的标准==,因此不会比较tok == enc
在这里查看文档和源代码:http://bcrypt-ruby.rubyforge.org/
https://stackoverflow.com/questions/11805678
复制相似问题