Class: PatientHttp::Encryptor

Inherits:
Object
  • Object
show all
Defined in:
lib/patient_http/encryptor.rb

Overview

Handles encryption and decryption of payloads for secure storage.

This class provides a simple interface for encrypting data before storage and decrypting it after retrieval. It supports pluggable encryption and decryption logic, allowing you to use any encryption library or method that fits your needs.

Instance Method Summary collapse

Constructor Details

#initialize(encryption: nil, decryption: nil) ⇒ Encryptor

Initialize a new Encryptor with optional encryption and decryption callables.

Parameters:

  • encryption (#call, nil) (defaults to: nil)

    A callable object that takes data and returns encrypted data

  • decryption (#call, nil) (defaults to: nil)

    A callable object that takes encrypted data and returns decrypted data



14
15
16
17
# File 'lib/patient_http/encryptor.rb', line 14

def initialize(encryption: nil, decryption: nil)
  @encryption = encryption
  @decryption = decryption
end

Instance Method Details

#decrypt(data) ⇒ Hash?

Decrypt data using the provided decryption callable. If no decryption callable is set, or if the data is not marked as encrypted, returns the original data.

Parameters:

  • data (Hash)

    The data to be decrypted

Returns:

  • (Hash, nil)

    The decrypted data as a hash or the original data if no decryption callable is set or if data is not encrypted

Raises:

  • (JSON::ParserError)

    If the decrypted data cannot be parsed as JSON



47
48
49
50
51
52
53
54
55
56
57
# File 'lib/patient_http/encryptor.rb', line 47

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

  raise ArgumentError.new("Data is not a Hash") unless data.is_a?(Hash)

  return data unless @decryption && data["__encrypted__"]
  return nil if data["value"].nil?

  decrypted = @decryption.call(base64_decode(data["value"]))
  JSON.parse(decrypted)
end

#encrypt(data) ⇒ Hash?

Encrypt data using the provided encryption callable. If no encryption callable is set, returns the original data.

Parameters:

  • data (Hash)

    The data to be encrypted

Returns:

  • (Hash, nil)

    The encrypted data as a hash or the original data if no encryption callable is set

Raises:

  • (JSON::GeneratorError)

    If the data cannot be serialized to JSON



25
26
27
28
29
30
31
32
33
34
35
36
37
38
# File 'lib/patient_http/encryptor.rb', line 25

def encrypt(data)
  return nil if data.nil?

  raise ArgumentError.new("Data is not a Hash") unless data.is_a?(Hash)

  return data unless @encryption

  json = JSON.generate(data)

  {
    "__encrypted__" => true,
    "value" => base64_encode(@encryption.call(json))
  }
end