Class: KmsTools::CLI::Encrypt

Inherits:
Object
  • Object
show all
Defined in:
lib/kms-tools/cli/encrypt.rb

Overview

Class for handling encrypt operations from the CLI

Instance Method Summary collapse

Constructor Details

#initialize(global_options, options) ⇒ Encrypt

Set up encryption handler

Parameters:

  • global_options (Hash)
  • options (Hash)

Options Hash (global_options):

  • :master_key (String)

    Master key to use if provided by CLI options

  • :profile (String)

    AWS credential profile to us if provided by CLI options

  • :region (String)

    AWS region to use if provided by CLI options

Options Hash (options):

  • :data_key (String)

    Existing data key to use if provided by CLI options



14
15
16
17
18
19
# File 'lib/kms-tools/cli/encrypt.rb', line 14

def initialize(global_options, options)
  @enc = KmsTools::Encrypter.new(global_options)
  @output = options[:output]
  abort "You must specify a key alias as a flag when encrypting stdin!" unless STDIN.tty? || global_options[:k]
  @enc.use_key_alias = Helpers.select_key(@enc) if @enc.master_key.nil?
end

Instance Method Details

#encrypt(source) ⇒ String

Handle encrypt command

Parameters:

  • source (String)

    Plaintext source to encrypt. Can be a string for direct encryption or a path to a file to encrypt

Returns:

  • (String)

    Returns Base64 encoded ciphertext if a string is provided

  • (String)

    Returns path to encrypted file if a source path is provided



26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
# File 'lib/kms-tools/cli/encrypt.rb', line 26

def encrypt(source)
  if File.file?(source)
    save_path = encrypt_file(source)
    Output.say("Encrypted file saved to: #{save_path}")
  elsif source.is_a?(String)
    encrypted_response = @enc.encrypt_string(source)
    if STDIN.tty?
      Output.say("Encrypted ciphertext (copy all text without surrounding whitespace):\n\n#{encrypted_response}\n\n")
    else
      print encrypted_response
    end
  else
    raise "Unknown input to encrypt..."
  end

  # clear source from memory for good measure
  source = nil
end

#encrypt_file(source) ⇒ String

Encrypt a file from source path

Parameters:

  • source (String)

    path to file to encrypt

Returns:

  • (String)

    path to encrypted file



49
50
51
52
53
54
55
56
57
58
# File 'lib/kms-tools/cli/encrypt.rb', line 49

def encrypt_file(source)
  ef = KmsTools::EncryptedFile.new(encrypter: @enc)
  ef.create_from_file(source)
  save_path = Helpers::get_save_path({
    :prompt => "Save encrytped file to",
    :suggested_path => File.absolute_path(source.sub File.extname(source), ".kms")
    })
  ef.save_encrypted(save_path)
  save_path
end