2012-08-04 100 views
3

我尝试了bcrypt-红宝石的宝石,我写了下面的代码来生成一个随机密码并验证它bcrypt-ruby的密码生成和校验

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) 

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

+1

请注意,你的'encrypt_token'方法不是很地道。它应该很简单:'def encrypt_token(tok); BCrypt :: Password.create(TOK);结束' – Phrogz 2012-08-04 03:41:38

+0

对不起,我是红宝石新手。我仍然在学习它的编码习惯。 – 2012-08-04 03:46:03

回答

3

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不会因为你会使用标准的==class String

看看的doc和这里的源: http://bcrypt-ruby.rubyforge.org/