首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >对如何使用bcrypt-ruby感到困惑

对如何使用bcrypt-ruby感到困惑
EN

Stack Overflow用户
提问于 2011-06-23 13:54:54
回答 2查看 1.8K关注 0票数 0

我正在实现一个验证方案,并使用bcrypt-ruby gem。

代码语言:javascript
复制
require 'bcrypt'

    class User < ActiveRecord::Base

      include BCrypt

      attr_accessor :password

      attr_accessible :name, :email, :password, :password_confirmation

      validates :password, :presence => true, :on => :create,
                           :confirmation => true,
                           :length => {:within => 6..12}

     before_save :encrypt_password

      def has_password?(submitted_password)
      self.encrypted_password == submitted_password # this calls a method in bcrypt    

    # File lib/bcrypt.rb, line 171
    #     def ==(secret)
    #       super(BCrypt::Engine.hash_secret(secret, @salt))
    #     end

      end

    private

      def encrypt_password

           self.encrypted_password = Password.create(password, :cost => 5)  
       end
    end

现在,我在控制台中创建了一个新用户

代码语言:javascript
复制
>> user = User.create!(:name => "test", :email => "test@test.com", :password => "foobar", :password_confirmation => "foobar")

=> #<User id: 1, name: "test", email: "test@test.com", created_at: "2011-06-23 05:00:00", updated_at: "2011-06-23 05:00:00", encrypted_password: "$2a$10$I7Wy8NDMeVcNgOsE3J/ZyubiNAESyxA7Z49H4p1x5xxH...">

如果我检查密码是否有效,我会执行以下操作:

代码语言:javascript
复制
>> user.has_password?("foobar")
=> true

但是,如果我从数据库中获取用户,它将失败:

代码语言:javascript
复制
user = User.find(1)
user.has_password?("foobar")
=> false

为什么会发生这种情况?我如何实现bcrypt才能使其工作?

提前谢谢你。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2011-06-23 14:01:20

我的猜测是,由于密码作为字符串而不是BCrypt::encrypted_password存储在数据库中,因此您调用的不是BCrypt的==,而是字符串的==。您必须围绕字符串散列值实例化密码的实例。这就是我要找的地方。

票数 0
EN

Stack Overflow用户

发布于 2019-04-08 18:20:43

正如在here上所描述的,您必须使用口令类Bcrypt来利用==

代码语言:javascript
复制
def has_password?(submitted_password)
  Bcrypt::Password.new(self.encrypted_password) == submitted_password
end
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/6449879

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档