Virtual attribute is not set before attr_encrypted uses said virtual attribute for encryption key

486 views Asked by At

When encryption_key is called by attr_encrypted, :passphrase hasn't been set. The encryption key ends up being a sha1 hash of the salt; it should be a sha1 hash of the passphrase and salt.

The salt is generated on creation and saved in the database.

How do I use the :passphrase virtual attribute in the encryption key?

Any suggestions?

For brevity I ommitted a bunch of code.

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

Thanks in advance!

1

There are 1 answers

2
Sean Huber On BEST ANSWER

Try setting ssn after passphrase and the other attributes

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