Class: EncryptedParams

Inherits:
Object
  • Object
show all
Defined in:
lib/encrypted_parameter_filter/encrypted_params.rb

Constant Summary collapse

ENCRYPTED =
"[ENCRYPTED]"

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(parameters_to_encrypt) ⇒ EncryptedParams

Returns a new instance of EncryptedParams.



8
9
10
11
12
13
14
15
16
17
18
# File 'lib/encrypted_parameter_filter/encrypted_params.rb', line 8

def initialize(parameters_to_encrypt)
  @parameters_to_encrypt = stringify_nested_array(parameters_to_encrypt)
  key_generator = ActiveSupport::KeyGenerator.new(
    Rails.application.secret_key_base,
    iterations: 1000,
    hash_digest_class: OpenSSL::Digest::SHA1
  )
  salt = "encrypted_params:encryption".dup.force_encoding("UTF-8")
  secret = key_generator.generate_key(salt, 32)
  @encryptor = ActiveSupport::MessageEncryptor.new(secret, cipher: "aes-256-gcm")
end

Class Method Details

.filter(*parameters_to_encrypt) ⇒ Object



4
5
6
# File 'lib/encrypted_parameter_filter/encrypted_params.rb', line 4

def self.filter(*parameters_to_encrypt)
  new(parameters_to_encrypt).to_proc_array
end

Instance Method Details

#decrypt(encrypted_value) ⇒ Object



29
30
31
32
# File 'lib/encrypted_parameter_filter/encrypted_params.rb', line 29

def decrypt(encrypted_value)
  encrypted_value = encrypted_value.gsub(ENCRYPTED, "")
  @encryptor.decrypt_and_verify(encrypted_value)
end

#encrypt(value) ⇒ Object



24
25
26
27
# File 'lib/encrypted_parameter_filter/encrypted_params.rb', line 24

def encrypt(value)
  encrypted_value = @encryptor.encrypt_and_sign(value)
  ENCRYPTED + encrypted_value
end

#to_proc_arrayObject



20
21
22
# File 'lib/encrypted_parameter_filter/encrypted_params.rb', line 20

def to_proc_array
  Array(Proc.new { |key, value, original_params| filter(key, value, original_params) })
end