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?
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.
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