AWS SDK for Ruby
Developer Guide

Encrypting an Amazon S3 Bucket Object with an AWS KMS Key

The following example uses the put_object method to add the object my_item to the bucket my_bucket in the us-west-2 region.

Choose Copy to save the code locally.

Create the file encrypt_object_csekms.rb.

Add the required Amazon S3 gem.

Note

Version 2 of the AWS SDK for Ruby didn't have service-specific gems.

require 'aws-sdk-s3' # In v2: require 'aws-sdk'

Get the AWS KMS key from the command line, where key is an AWS KMS key ID as created in the Creating a CMK in AWS KMS example.

if ARGV.empty?() puts 'You must supply a key' exit 1 end key = ARGV[0]

Set the bucket and object name and get the contents of the object from the file as a string.

bucket = 'my_bucket' item = 'my_item' contents = File.read(item)

Create a AWS KMS and Amazon S3 encryption client, call put_object to upload the object to the bucket, and display a success message.

kms = Aws::KMS::Client.new # Create encryption client client = Aws::S3::Encryption::Client.new( kms_key_id: key, kms_client: kms ) # Add encrypted item to bucket client.put_object( body: contents, bucket: bucket, key: item ) puts 'Added client-side KMS encrypted item ' + item + ' to bucket ' + bucket

See the complete example on GitHub.