Sha256: c63f105cbf560f15bdff5dff605290ad2eee718e01b94109ce069e3cae49cd44

Contents?: true

Size: 1.36 KB

Versions: 3

Compression:

Stored size: 1.36 KB

Contents

module KmsEncrypted
  module Clients
    class Vault < Base
      def encrypt(plaintext, context: nil)
        options = {
          plaintext: Base64.encode64(plaintext)
        }
        options[:context] = generate_context(context) if context

        response = KmsEncrypted.vault_client.logical.write(
          "transit/encrypt/#{key_id.sub("vault/", "")}",
          options
        )

        response.data[:ciphertext]
      end

      def decrypt(ciphertext, context: nil)
        options = {
          ciphertext: ciphertext
        }
        options[:context] = generate_context(context) if context

        response =
          begin
            KmsEncrypted.vault_client.logical.write(
              "transit/decrypt/#{key_id.sub("vault/", "")}",
              options
            )
          rescue ::Vault::HTTPClientError => e
            decryption_failed! if e.message.include?("unable to decrypt")
            raise e
          rescue ::Vault::HTTPServerError => e
            decryption_failed! if e.message.include?("message authentication failed")
            raise e
          rescue Encoding::UndefinedConversionError
            decryption_failed!
          end

        Base64.decode64(response.data[:plaintext])
      end

      private

      # turn hash into json
      def generate_context(context)
        Base64.encode64(super)
      end
    end
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
kms_encrypted-1.4.0 lib/kms_encrypted/clients/vault.rb
kms_encrypted-1.3.0 lib/kms_encrypted/clients/vault.rb
kms_encrypted-1.2.4 lib/kms_encrypted/clients/vault.rb