Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can i compare decrypted password and encrypted password by 'Bcrypt' Gem

I'm trying to use simple authentication for some post's comments.

Users type comment with instant id and password

and i use 'bcrypt' gem to store password in Database.

Like this in comments_controller.rb

@comment = Comment.new(comment_params)
bcrypted_pwd = BCrypt::Password.create(@comment.user_pwd)
@comment.user_pwd = bcrypted_pwd

and i use data-confirm-modal gem to confirm with data when user want to delete their comments

In this part, i have to decrypt user input password to compare with encrypted password in Database

how can i decrypt password and is there any good way to done this?

like image 760
PrepareFor Avatar asked Jun 27 '17 10:06

PrepareFor


1 Answers

ency_pass = BCrypt::Password.create("testing")
new_pass = "testing"

Let’s look at how we compare two bcrypt hashes, one coming from the database & one from user input (like a form or something like that).

BCrypt::Password.new(ency_pass) == new_pass
# true
BCrypt::Password.new(ency_pass) == "testing2"
#false

The part on the left (BCrypt::Password.new) is a BCrypt object, which takes the hash stored in the database as a parameter.

The part on the right (new_pass) is just the plain-text password that the user is trying to log in with.

Let's understand this things:

BCrypt uses something called a “salt”, which is a random value used to increase security against pre-computed hashes. The salt is stored in the hash itself. BCrypt defines its own == method, which knows how to extract that “salt” value so that it can take that into account when comparing the passwords.

BCrypt#== takes the “salt” value from the stored hash, then it hashes the plain-text password (the user input) using this salt so that both hashes will be identical if the password is valid.

If you were to look at the source code it would look something like this:

def ==(secret)
 super(
  BCrypt::Engine.hash_secret(secret, @salt)
 )
end

Remember that super will call the same method (in this case ==) on the parent class. The parent class of BCrypt::Password is String.

like image 62
Vishal Avatar answered Sep 27 '22 19:09

Vishal