Sha256: 2fffafbdc42c6b88c4a6979f5c66c4d4ea6622c47046f19cc7cc7043bca8ca54

Contents?: true

Size: 1.41 KB

Versions: 3

Compression:

Stored size: 1.41 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") || e.message.include?("message authentication failed")
            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.6.0 lib/kms_encrypted/clients/vault.rb
kms_encrypted-1.5.1 lib/kms_encrypted/clients/vault.rb
kms_encrypted-1.5.0 lib/kms_encrypted/clients/vault.rb