bcrypt ruby密码生成和检查
我正在试用bcrypt ruby gem,我编写了以下代码来生成一个随机密码并验证它bcrypt ruby密码生成和检查,ruby,bcrypt,Ruby,Bcrypt,我正在试用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
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)
代码一直打印“不相等”而不是“相等”。我哪里做错了?谢谢:)bcrypt有自动加盐功能。不能比较同一字符串的两个bcrypts,它们会不同 试着这样比较:
def check_token(enc,tok)
if enc == tok #We compare it with the unencrypted string.
puts 'equal'
else
puts 'not equal'
end
end
诀窍在于,当创建一个新的bcrypt时,您将得到一个密码对象,该对象将覆盖=
操作符。它将根据未加密的字符串检查密码是否正确
也正因为如此,要小心:在上面的例子中,比较enc==tok
是有效的。
比较tok==enc
不会像您将使用类字符串中的标准=
那样
请在此处查看文档和来源:
请注意,您的加密\u令牌
方法不是很惯用。它应该是简单的:def encrypt_令牌(tok);BCrypt::Password.create(tok);结束
对不起,我是ruby新手。我还在学习它的编码惯例。