我如何比较'Bcrypt'宝石的解密密码和加密密码 [英] How can i compare decrypted password and encrypted password by 'Bcrypt' Gem

查看:76
本文介绍了我如何比较'Bcrypt'宝石的解密密码和加密密码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试对某些帖子的评论使用简单的身份验证.

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

用户输入带有即时ID和密码的评论

Users type comment with instant id and password

然后我使用"bcrypt" gem将密码存储在数据库中.

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

在comments_controller.rb

Like this in comments_controller.rb

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

当用户想要删除他们的评论时,我使用data-confirm-modal gem来确认数据

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"

让我们看看我们如何比较两个bcrypt散列,其中一个来自数据库&.

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

左侧的部分( BCrypt :: Password.new)是BCrypt对象,该对象将存储在数据库中的哈希值作为参数.

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

右侧(new_pass)只是用户尝试登录时使用的纯文本密码.

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

让我们了解以下内容:

BCrypt使用一种称为盐"的东西,这是一个随机值,用于提高针对预先计算的哈希的安全性.盐存储在哈希自身中.BCrypt定义了自己的==方法,该方法知道如何提取该盐"值,以便在比较密码时可以将其考虑在内.

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#==从存储的哈希中获取"salt"值,然后使用该盐对纯文本密码(用户输入)进行哈希处理,这样,如果密码有效,则两个哈希将相同.

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

请记住,super将在父类上调用相同的方法(在本例中为==).BCrypt :: Password的父类是String.

这篇关于我如何比较'Bcrypt'宝石的解密密码和加密密码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆