-
Notifications
You must be signed in to change notification settings - Fork 3
/
kms-encrypt.rb
executable file
·49 lines (42 loc) · 1.26 KB
/
kms-encrypt.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
#!/usr/bin/ruby
# frozen_string_literal: true
require 'pp'
require 'rubygems'
require 'openssl'
require 'aws-sdk-kms'
require 'base64'
require 'json'
if ARGV[0].nil?
puts 'Usage: encrypt.rb INPUTFILE'
exit 1
end
# This uses the envelope-encryption model.
# The cleartext is not sent to AWS KMS,
# rather an encryption key is generated by KMS
# and stored alongside the ciphertext.
# keyid looks like 6d83e627-bf08-1111-9999-23b0a0df19b1
keyid = ENV['KEYID']
plaintext = IO.read(ARGV[0])
kms = Aws::KMS::Client.new(region: 'us-east-1')
# Encryption_context can be thought of as part of the key;
# it must match on both the encrypt and decrypt end.
kmsresponse = kms.generate_data_key(
key_id: keyid,
encryption_context: { 'KeyType' => 'Some descriptive text here' },
key_spec: 'AES_256'
)
alg = 'AES-256-CBC'
iv = OpenSSL::Cipher.new(alg).random_iv
aes = OpenSSL::Cipher.new(alg)
aes.encrypt
aes.key = kmsresponse['plaintext']
aes.iv = iv
cipher = aes.update(plaintext)
cipher << aes.final
cipher64 = Base64.strict_encode64(cipher)
outputhash = { 'ciphertext' => cipher64,
'iv' => Base64.strict_encode64(iv),
'datakey' => Base64.strict_encode64(
kmsresponse.ciphertext_blob
) }
puts JSON.pretty_generate(outputhash)