Class: ROM::EncryptedAttribute::Decryptor

Inherits:
Object
  • Object
show all
Defined in:
lib/rom/encrypted_attribute/decryptor.rb

Constant Summary collapse

UnencryptedDataNotAllowed =
Class.new(RuntimeError)

Instance Method Summary collapse

Constructor Details

#initialize(derivator:, support_unencrypted_data: false) ⇒ Decryptor

Returns a new instance of Decryptor.



12
13
14
15
# File 'lib/rom/encrypted_attribute/decryptor.rb', line 12

def initialize(derivator:, support_unencrypted_data: false)
  @derivator = derivator
  @support_unencrypted_data = support_unencrypted_data
end

Instance Method Details

#decrypt(message) ⇒ Object



17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
# File 'lib/rom/encrypted_attribute/decryptor.rb', line 17

def decrypt(message)
  return nil if message.nil?

  payload = ROM::EncryptedAttribute::Payload.decode(message)

  cipher = OpenSSL::Cipher.new("aes-256-gcm")
  key = @derivator.derive(cipher.key_len)

  cipher.decrypt
  cipher.padding = 0
  cipher.key = key
  cipher.iv = payload.initialization_vector
  cipher.auth_tag = payload.auth_tag
  cipher.auth_data = ""
  cipher.update(payload.message) + cipher.final
rescue JSON::ParserError
  if @support_unencrypted_data
    message
  else
    raise UnencryptedDataNotAllowed
  end
end