Class: DynamoSecret::Kms

Inherits:
Object
  • Object
show all
Defined in:
lib/dynamo_secret/kms.rb

Instance Method Summary collapse

Constructor Details

#initialize(config) ⇒ Kms

Returns a new instance of Kms.



6
7
8
9
# File 'lib/dynamo_secret/kms.rb', line 6

def initialize(config)
  @key_name = config[:key_name] || key_name
  @region = config.fetch(:region, region)
end

Instance Method Details

#create_keyObject



11
12
13
14
15
# File 'lib/dynamo_secret/kms.rb', line 11

def create_key
  return $stdout.puts "KMS alias #{@key_name} already exists" if key
  id = client.create_key(tags: [{ tag_key: 'Owner', tag_value: user_id }])..key_id
  client.create_alias(alias_name: "alias/#{@key_name}", target_key_id: id)
end

#decrypt(data) ⇒ Object



17
18
19
20
21
22
# File 'lib/dynamo_secret/kms.rb', line 17

def decrypt(data)
  client.decrypt(ciphertext_blob: data).plaintext
rescue Aws::KMS::Errors::InvalidCiphertextException
  $stderr.puts 'Key was found but KMS decrypt failed - skipping'
  data
end

#encrypt(data) ⇒ Object



24
25
26
# File 'lib/dynamo_secret/kms.rb', line 24

def encrypt(data)
  client.encrypt(key_id: key, plaintext: data).ciphertext_blob
end

#keyObject



28
29
30
31
32
# File 'lib/dynamo_secret/kms.rb', line 28

def key
  @key ||= client.list_aliases.aliases.map do |kms_alias|
    kms_alias.target_key_id if kms_alias.alias_name == "alias/#{@key_name}"
  end.compact.first
end