Method: DaffyLib::CachingEncryptor.zt_encrypt

Defined in:
lib/daffy_lib/caching_encryptor.rb

.zt_encrypt(*args, &_block) ⇒ Object



9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
# File 'lib/daffy_lib/caching_encryptor.rb', line 9

def self.zt_encrypt(*args, &_block)
  data, partition_guid, encryption_epoch, expires_in, cmk_key_id = validate_encrypt_params(*args)

  kms = DaffyLib::KeyManagementService.new(partition_guid, expires_in, cmk_key_id)

  key_info = kms.find_or_create_encryption_key(encryption_epoch)

  plaintext_key = kms.retrieve_plaintext_key(key_info)

  encryption_result = PorkyLib::Symmetric.instance.encrypt_with_key(data, plaintext_key)

  # The value returned from this method is stored in the encrypted_{attr} field in the DB, but there isn't a way to tell the attr_encrypted library
  # the value of the nonce/IV to store or the value of the encryption key to store. As a result, we will store a JSON object as the encrypted_{attr},
  # with the raw byte values Base64 encoded.
  {
    key_guid: key_info.guid,
    # Store this with the data in case we need to decrypt outside the platform
    key: key_info.encrypted_data_encryption_key,
    data: Base64.encode64(encryption_result.ciphertext),
    nonce: Base64.encode64(encryption_result.nonce)
  }.to_json
rescue DaffyLib::KeyManagementService::KeyManagementServiceException => e
  Rails.logger.error("KeyManagementService exception on encrypt: #{e.message}")

  raise EncryptionFailedException
rescue RbNaCl::CryptoError, RbNaCl::LengthError => e
  Rails.logger.error("RbNaCl exception on encrypt: #{e.message}")

  raise EncryptionFailedException
end