Module: CryptKeeper::Model::ClassMethods
- Defined in:
- lib/crypt_keeper/model.rb
Instance Method Summary collapse
-
#crypt_keeper(*args) ⇒ Object
Public: Setup fields for encryption.
-
#decrypt_table! ⇒ Object
Public: Decrypt a table (reverse of encrypt_table!).
-
#encrypt_table! ⇒ Object
Public: Encrypt a table for the first time.
- #search_by_plaintext(field, criteria) ⇒ Object
Instance Method Details
#crypt_keeper(*args) ⇒ Object
Public: Setup fields for encryption
args - An array of fields to encrypt. The last argument should be
a hash of . Note, an :encryptor is required. This should be
a class that takes a hash for initialize and provides an encrypt
and decrypt method.
Example
class MyModel < ActiveRecord::Base
crypt_keeper :field, :other_field, :encryptor => :aes, :key => 'super_good_password'
end
51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 |
# File 'lib/crypt_keeper/model.rb', line 51 def crypt_keeper(*args) class_attribute :crypt_keeper_fields class_attribute :crypt_keeper_encryptor class_attribute :crypt_keeper_options class_attribute :crypt_keeper_encoding self. = args. self.crypt_keeper_encryptor = .delete(:encryptor) self.crypt_keeper_encoding = .delete(:encoding) self.crypt_keeper_fields = args ensure_valid_encryptor! before_save :enforce_column_types_callback if self.crypt_keeper_encoding after_find :force_encodings_on_fields before_save :force_encodings_on_fields end crypt_keeper_fields.each do |field| serialize field, encryptor end end |
#decrypt_table! ⇒ Object
Public: Decrypt a table (reverse of encrypt_table!)
103 104 105 106 107 108 109 110 111 112 113 114 115 |
# File 'lib/crypt_keeper/model.rb', line 103 def decrypt_table! tmp_table = Class.new(ActiveRecord::Base).tap { |c| c.table_name = self.table_name } transaction do tmp_table.find_each do |r| crypt_keeper_fields.each do |field| r.send("#{field}=", encryptor.decrypt(r[field])) if r[field].present? end r.save! end end end |
#encrypt_table! ⇒ Object
Public: Encrypt a table for the first time.
85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 |
# File 'lib/crypt_keeper/model.rb', line 85 def encrypt_table! tmp_table = Class.new(ActiveRecord::Base).tap do |c| c.table_name = self.table_name c.inheritance_column = :type_disabled end transaction do tmp_table.find_each do |r| crypt_keeper_fields.each do |field| r.send("#{field}=", encryptor.encrypt(r[field])) if r[field].present? end r.save! end end end |
#search_by_plaintext(field, criteria) ⇒ Object
76 77 78 79 80 81 82 |
# File 'lib/crypt_keeper/model.rb', line 76 def search_by_plaintext(field, criteria) if crypt_keeper_fields.include?(field.to_sym) encryptor.search(all, field.to_s, criteria) else raise ArgumentError, "#{field} is not a crypt_keeper field" end end |