Class: Serket::FieldEncrypter

Inherits:
Object
  • Object
show all
Defined in:
lib/serket/field_encrypter.rb

Overview

Used to encrypt a field given a public key, field delimiter, symmetric algorithm, encoding and format (:json or :delimited)

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(options = {}) ⇒ FieldEncrypter

Returns a new instance of FieldEncrypter.



10
11
12
13
14
15
16
17
18
# File 'lib/serket/field_encrypter.rb', line 10

def initialize(options = {})
  options ||= {}

  @public_key_filepath    = Serket.configuration.public_key_path
  @field_delimiter        = options[:field_delimiter]     || Serket.configuration.delimiter 
  @symmetric_algorithm    = options[:symmetric_algorithm] || Serket.configuration.symmetric_algorithm
  @format                 = options[:format]              || Serket.configuration.format
  @encoding               = options[:encoding]            || Serket.configuration.encoding
end

Instance Attribute Details

#encodingObject

Returns the value of attribute encoding.



8
9
10
# File 'lib/serket/field_encrypter.rb', line 8

def encoding
  @encoding
end

#field_delimiterObject

Returns the value of attribute field_delimiter.



8
9
10
# File 'lib/serket/field_encrypter.rb', line 8

def field_delimiter
  @field_delimiter
end

#public_key_filepathObject

Returns the value of attribute public_key_filepath.



8
9
10
# File 'lib/serket/field_encrypter.rb', line 8

def public_key_filepath
  @public_key_filepath
end

#symmetric_algorithmObject

Returns the value of attribute symmetric_algorithm.



8
9
10
# File 'lib/serket/field_encrypter.rb', line 8

def symmetric_algorithm
  @symmetric_algorithm
end

Instance Method Details

#encrypt(field) ⇒ Object

Return encrypted string according to specified format. Return nil if field is whitespace.



22
23
24
25
26
27
28
# File 'lib/serket/field_encrypter.rb', line 22

def encrypt(field)
  return if field !~ /\S/
  aes = OpenSSL::Cipher.new(symmetric_algorithm)
  aes_key = aes.random_key
  iv = aes.random_iv
  encrypt_data(iv, aes_key, field.force_encoding(encoding))
end