gpt4 book ai didi

ruby - bcrypt-ruby 密码生成和检查

转载 作者:数据小太阳 更新时间:2023-10-29 08:01:06 24 4
gpt4 key购买 nike

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

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 具有自动加盐功能。您不能比较同一字符串的两个 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 时,您最终会得到一个覆盖 == 运算符的密码对象。它将根据未加密的字符串检查密码是否正确。

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

的标准 ==

在此处查看文档和源代码: http://bcrypt-ruby.rubyforge.org/

关于ruby - bcrypt-ruby 密码生成和检查,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11805678/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com