在attr_encrypted使用加密密钥的所述虚拟属性之前,不设置虚拟属性

时间:2012-05-31 19:04:50

标签: ruby-on-rails virtual-attribute attr-accessible attr-accessor attr-encrypted

encryption_key调用attr_encrypted时,:passphrase尚未设置。加密密钥最终成为salt的sha1哈希; 应该是密码和盐的sha1哈希。

盐在创建时生成并保存在数据库中。

如何在加密密钥中使用:passphrase虚拟属性?

有什么建议吗?

为简洁起见,我省略了一堆代码。

class Employee < ActiveRecord::Base
    require 'digest/sha1'
    attr_accessor :passphrase, :ssn
    attr_accessible :passphrase, :ssn
    attr_encrypted :ssn, :key => proc { |employee| "#{employee.encryption_key}" }

    def encryption_key
        unless salt?
            self.salt = Digest::SHA1.hexdigest(generate_salt)
        end

        Digest::SHA1.hexdigest([passphrase, self.salt].join)
    end
end

class EmployeesController < ApplicationController
    def create
        @employee = @parent.employees.new(params[:employee])
        if @employee.save
            redirect_to @parent
        else
            render action: "new"
        end
    end
end

提前致谢!

1 个答案:

答案 0 :(得分:0)

尝试在密码短语和其他属性

之后设置ssn
class EmployeesController < ApplicationController
  def create
    ssn = params[:employee].delete(:ssn)
    @employee = @parent.employees.new(params[:employee])
    @employee.ssn = ssn
    if @employee.save
        redirect_to @parent
    else
        render action: "new"
    end
  end
end