Sha256: 4b118c7de1263ec17f62ab8d301501a3fbc446661cb5ac0b38857b79d6f5bd2a

Contents?: true

Size: 1.01 KB

Versions: 2

Compression:

Stored size: 1.01 KB

Contents

# frozen_string_literal: true

require "dry/types"
require "dry/struct"
require "base64"

module ROM
  class EncryptedAttribute::Payload < Dry::Struct
    class Types
      include Dry.Types()
    end

    attribute :message, Types::Strict::String
    attribute :initialization_vector, Types::Strict::String
    attribute :auth_tag, Types::Strict::String

    def self.decode(database_value)
      payload = JSON.parse(database_value)
      new(
        message: decode64(payload["p"]),
        initialization_vector: decode64(payload.dig("h", "iv")),
        auth_tag: decode64(payload.dig("h", "at"))
      )
    end

    def self.decode64(value)
      Base64.strict_decode64(value)
    end

    def encode
      payload =
        {
          "p" => encode64(message),
          "h" => {
            "iv" => encode64(initialization_vector),
            "at" => encode64(auth_tag)
          }
        }

      JSON.dump(payload)
    end

    private

    def encode64(value)
      Base64.strict_encode64(value)
    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
rom-encrypted_attribute-0.0.4 lib/rom/encrypted_attribute/payload.rb
rom-encrypted_attribute-0.0.3 lib/rom/encrypted_attribute/payload.rb