Module: Cryptonite

Extended by:
ActiveSupport::Concern, KeyExtractor
Defined in:
lib/cryptonite.rb,
lib/cryptonite/coder.rb,
lib/cryptonite/version.rb,
lib/cryptonite/key_extractor.rb

Overview

Cryptonite

Enables the encryption of specific ActiveRecord attributes.

Defined Under Namespace

Modules: ClassMethods, KeyExtractor Classes: Coder

Constant Summary collapse

VERSION =
'0.1.0'

Class Method Summary collapse

Class Method Details

.decrypt_model_attributes(model, *attributes) ⇒ Object

Decrypts attributes of a specific model. This method is indended for migration purposes. It takes the same arguments as the ‘attr_encrypted` class method. It requires a private key to decrypt the data.



74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
# File 'lib/cryptonite.rb', line 74

def decrypt_model_attributes(model, *attributes) # rubocop:disable Metrics/MethodLength, Metrics/AbcSize
  fail ArgumentError, "ActiveRecord::Base expected, got #{model.inspect}" unless model <= ActiveRecord::Base

  options = attributes.extract_options!
  encrypted_attributes = attributes.map(&:to_s) & model.column_names
  coder = Coder.new extract_private_key(options)

  model.find_each do |record|
    updated_columns =
      encrypted_attributes.each_with_object({}) do |attribute, values|
        values[attribute] = coder.decrypt(record.read_attribute_before_type_cast attribute)
      end

    record.update_columns(updated_columns)
  end
end

.encrypt_model_attributes(model, *attributes) ⇒ Object

Encrypts attributes of a specific model. This method is indended for migration purposes. It takes the same arguments as the ‘attr_encrypted` class method.



55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
# File 'lib/cryptonite.rb', line 55

def encrypt_model_attributes(model, *attributes) # rubocop:disable Metrics/MethodLength, Metrics/AbcSize
  fail ArgumentError, "ActiveRecord::Base expected, got #{model.inspect}" unless model <= ActiveRecord::Base

  options = attributes.extract_options!
  encrypted_attributes = attributes.map(&:to_s) & model.column_names
  coder = Coder.new extract_public_key(options)

  model.find_each do |record|
    updated_columns =
      encrypted_attributes.each_with_object({}) do |attribute, values|
        values[attribute] = coder.encrypt(record.typecasted_attribute_value attribute)
      end

    record.update_columns(updated_columns)
  end
end