Class: ResponseEncryption::SymmetricEncrypter

Inherits:
ActiveModelService show all
Defined in:
lib/response_encryption/symmetric_encrypter.rb

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Methods inherited from ActiveModelService

#valid?

Constructor Details

#initialize(options = {}) ⇒ SymmetricEncrypter

Returns a new instance of SymmetricEncrypter.



5
6
7
8
9
10
# File 'lib/response_encryption/symmetric_encrypter.rb', line 5

def initialize(options={})
  validate(options)
  @cipher = ResponseEncryption.cipher
  @iv = Base64.decode64(options[:encoded_iv])
  @key = Base64.decode64(options[:encoded_key])
end

Instance Attribute Details

#cipherObject (readonly)

Returns the value of attribute cipher.



3
4
5
# File 'lib/response_encryption/symmetric_encrypter.rb', line 3

def cipher
  @cipher
end

#encrypted_dataObject (readonly)

Returns the value of attribute encrypted_data.



3
4
5
# File 'lib/response_encryption/symmetric_encrypter.rb', line 3

def encrypted_data
  @encrypted_data
end

#ivObject (readonly)

Returns the value of attribute iv.



3
4
5
# File 'lib/response_encryption/symmetric_encrypter.rb', line 3

def iv
  @iv
end

#keyObject (readonly)

Returns the value of attribute key.



3
4
5
# File 'lib/response_encryption/symmetric_encrypter.rb', line 3

def key
  @key
end

Class Method Details

.encoded_nonceObject



32
33
34
# File 'lib/response_encryption/symmetric_encrypter.rb', line 32

def encoded_nonce
  Base64.encode64(ResponseEncryption.cipher.random_iv)
end

Instance Method Details

#encrypt(data, encode_data = true) ⇒ String

Returns with the encrypted and encoded information.

Parameters:

  • data (Object)

    which respond to #to_s

  • encode_data (Boolean) (defaults to: true)

Returns:

  • (String)

    with the encrypted and encoded information



15
16
17
18
19
20
21
22
23
24
# File 'lib/response_encryption/symmetric_encrypter.rb', line 15

def encrypt(data, encode_data = true)
  return data if data.blank?
  cipher.encrypt
  cipher.key = key
  # This is the initial vector that we will use as nonce code.
  # This nonce is going in the headers as a 'Replay-Nonce'
  cipher.iv = iv
  encrypted = cipher.update(data.to_s) + cipher.final
  @encrypted_data = encode_data ? Base64.encode64(encrypted) : encrypted
end

#validate(options) ⇒ Object



26
27
28
29
# File 'lib/response_encryption/symmetric_encrypter.rb', line 26

def validate(options)
  errors.add(:param_missing, 'You must to set the encoded_iv (nonce) option') if options[:encoded_iv].blank?
  errors.add(:param_missing, 'You must to set the encoded_key (symmetric-key) option') if options[:encoded_key].blank?
end