rails 3.0 attr_encrypted现有数据库

时间:2011-06-13 06:18:36

标签: ruby-on-rails-3 encryption

在rails 3.0中,我需要加密现有的文本字段。 有一个表备忘录,其中包含文本字段“note”。我创建了一个encrypted_note字段 并添加到模型中:

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

现在,当我加载现有记录时,“note”为空。我假设attr_encrypted尝试解密...但该字段已经加密了!

attr_encrypted适用于新记录,但想知道加密现有记录的最佳策略是什么?

3 个答案:

答案 0 :(得分:2)

instance_variable_get('@note')read_attribute('note')是否有效?

如果是这样,你可以在Rails控制台中做这样的事情:

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

答案 1 :(得分:2)

这是清除未加密列的技巧,因为加密的列已填充!  在模型中添加:

before_update :clear_note

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

答案 2 :(得分:1)

假设您使用未加密的属性Thing开始使用模型note

1)添加迁移以添加字段encrypted_note并填充

  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)在模型中添加一行以指定加密属性:

    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)运行迁移

    rake db:migrate