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 :
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 == tokworks.Comparing
tok == encwon’t as you’ll be using the standard==from theclass StringTake a look at the doc and the source here :
http://bcrypt-ruby.rubyforge.org/