Skip to content

Instantly share code, notes, and snippets.

@jamesridgway
Created May 22, 2017 21:20
Show Gist options
  • Save jamesridgway/70ede0107d39741ca3559fb625a04afa to your computer and use it in GitHub Desktop.
Save jamesridgway/70ede0107d39741ca3559fb625a04afa to your computer and use it in GitHub Desktop.
This is an example of how to use AWS KMS to encrypt and decrypt data.
=begin
----------
KMS Encyrption/Decryption Example
This is an example of how to use KMS to encrypt and decrypt data. This script will take the plaintext or ciphertext
via stdin (base 64 encoded).
Encrypt example:
$ echo "Hello world" | ruby kms_crypto.rb --region eu-west-2 --key-id a723bd --encrypt
Round-robin example:
$ echo "Hello world" | ruby kms_crypto.rb --region eu-west-2 --key-id a723bd --encrypt \
ruby kms_crypto.rb --region eu-west-2 --key-id a723bd --decrypt
----------
=end
require 'aws-sdk'
require 'optparse'
class KmsCrypto
def initialize(region, key_id)
@kms = Aws::KMS::Client.new(region: region)
@key_id = key_id
end
def encrypt(plaintext)
Base64.encode64(@kms.encrypt(key_id: @key_id, plaintext: plaintext).ciphertext_blob)
end
def decrypt(ciphertext)
@kms.decrypt(ciphertext_blob: Base64.decode64(ciphertext)).plaintext
end
end
if __FILE__ == $0
options = {}
OptionParser.new do |opts|
opts.banner = "Usage: #{__FILE__} [options]"
opts.on('-r', '--region REGION', 'AWS region') do |region|
options[:region] = region
end
opts.on('-k', '--key-id KEY_ID', 'Key ID') do |key_id|
options[:key_id] = key_id
end
opts.on('-e', '--encrypt', 'Encrypt data') do |encrypt|
options[:mode] = :encrypt
end
opts.on('-d', '--decrypt', 'Encrypt data') do |decrypt|
options[:mode] = :decrypt
end
end.parse!
raise ArgumentError.new("Argument '--region' required.") if options[:region].nil?
raise ArgumentError.new("Argument '--key-id' required.") if options[:key_id].nil?
crypto = KmsCrypto.new(options[:region], options[:key_id])
if options[:mode] == :encrypt
puts crypto.encrypt($stdin.read)
elsif options[:mode] == :decrypt
puts crypto.decrypt($stdin.read)
else
$stderr.puts "Mode not recognised expecting '--encrypt' or '--decrypt'."
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment