I was trying out the bcrypt-ruby gem and i wrote the following code to generate a random password and verify it
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)
The code keeps printing 'not equal' instead of 'equal'. Where am I going wrong? Thanks :)
bcrypt has an automatic-salt feature. You can't compare two bcrypts of the same string, they'll be different.
Try to compare like this :
def check_token(enc,tok)
if enc == tok #We compare it with the unencrypted string.
puts 'equal'
else
puts 'not equal'
end
end
The trick is that when creating a new bcrypt, you end up with a Password object that overrides the ==
operator. It'll check if the password is correct against an unencrypted string.
Also because of this, be careful : in the example above, comparing enc == tok
works.
Comparing tok == enc
won't as you'll be using the standard ==
from the class String
Take a look at the doc and the source here : http://bcrypt-ruby.rubyforge.org/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With