Rails 3.0 available attr_encrypted database

In rails 3.0, I need to encrypt an existing text box. There are tabular notes containing the text field "note". I created an encrypted_note field and added to the model:

attr_encrypted :note, :key => 'a secret key'

Now, when I load an existing entry, the “note” is empty. I assume attr_encrypted will try to decrypt ... but the field is encrypted again!

attr_encrypted works well for new entries, but I wonder what would be the best strategy for encrypting existing entries?

+4
source share
3 answers

Does it work instance_variable_get('@note')or read_attribute('note')?

If so, you can do something similar in the Rails console:

User.all.each do |user|
  user.note = user.instance_variable_get('@note')
  user.save
end
+2
source

, , !   :

before_update :clear_note

def clear_note
   if encrypted_note != nil && read_attribute('note') != nil
     write_attribute('note','')
   end
end
+2

Assuming you start with your model Thingusing an unencrypted attribute note.

1) Add a transition to add a field encrypted_noteand fill it

  class EncryptThing < ActiveRecord::Migration
    def up
      rename_column :things, :note, :old_note
      add_column :things, :encrypted_note, :string
      # if you want to use per-attribute iv and salt:
      # add_column :things, :encrypted_note_iv, :string
      # add_column :things, :encrypted_note_salt, :string

      Thing.find_each do |t|
        t.note = t.old_note
        t.save
      end

      remove_column :things, :old_note
    end

    def down
      raise ActiveRecord::IrreversibleMigration
    end
  end

2) Add a line to your model to specify an encrypted attribute:

    attr_encrypted :note, :key => Rails.application.config.key
    # if you want to use per-attribute iv and salt, add this to the line above:
    #   ,  :mode => :per_attribute_iv_and_salt

3) start the migration

    rake db:migrate
+1
source

All Articles