Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

bcrypt-ruby password generation and checking

Tags:

ruby

bcrypt

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 :)

like image 398
niravb Avatar asked Sep 02 '25 05:09

niravb


1 Answers

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/

like image 197
Anthony Alberto Avatar answered Sep 05 '25 00:09

Anthony Alberto