且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

密码加密问题在Rails Devise宝石

更新时间:2022-10-15 07:38:36

令人难过的是没有人回答我的问题......



然而,我认为我已经找到了答案,尽管它不像我想像的那样漂亮。



首先,创建加密类初始化程序:

 模块设计
模块加密程序
class MySha1< Base
def self.digest(password,salt)
摘要:: SHA1.hexdigest(#{salt} -----#{password})
end

def self.salt(email)
摘要:: SHA1.hexdigest(#{Time.now} -----#{email})
end
end
end
end

其次,覆盖User模型中的一些方法: / p>

 #覆盖此方法,以便正确调用encryptor类
def encrypt_password
除非@ password.blank ?
self.password_salt = self.class.encryptor_class.salt(email)
self.encrypted_pa​​ssword = self.class.encryptor_class.digest(@password,self.password_salt)
end
end

#因为当database_authenticatable编写了以下方法来重新生成密码,然后再将密码错误传递给encrypt_password,这些覆盖就是需要的!
def password =(password)
@password = password
end
def password_digest(pwd)
self.class.encryptor_class.digest(pwd,self.password_salt)
end

最后,我们必须教什么时候加密密码:

  before_save:encrypt_password 


I am now currently changed to use the Gem Devise for user authentication. But I don't know how to match the encryption!

I knew that we could write a new encryptor and assign it in initializers, but the point is the encryptor accepts 4 arguments only (password, stretches, salt, pepper). But in my case, I do included the user's email and a customized salt in the encryption.

Is it possible to pass the user's email and customized salt into the encryptor?

ps. I am using database_authenticatable

It's sad that no one answered my question......

However, I think I've found the answer, although it's not as pretty as I imagined.

First, create the encryption class in the initializers:

module Devise
  module Encryptors
    class MySha1 < Base
      def self.digest(password, salt)
        Digest::SHA1.hexdigest("#{salt}-----#{password}")
      end

      def self.salt(email)
        Digest::SHA1.hexdigest("#{Time.now}-----#{email}")
      end
    end
  end
end

Secondly, overwrite some methods in the User model:

# overwrite this method so that we call the encryptor class properly
def encrypt_password
  unless @password.blank?
    self.password_salt = self.class.encryptor_class.salt(email)
    self.encrypted_password = self.class.encryptor_class.digest(@password, self.password_salt)
  end
end

# Because when the database_authenticatable wrote the following method to regenerate the password, which in turn passed incorrect params to the encrypt_password, these overwrite is needed!
def password=(password)
  @password = password
end
def password_digest(pwd)
  self.class.encryptor_class.digest(pwd, self.password_salt)
end

And finally, we have to teach when to encrypt the password:

before_save :encrypt_password