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 with server-side AWS KMS encryption where you provide the key. See Creating a CMK in AWS KMS for information on creating an AWS KMS key.

Amazon S3 uses, but does not store, the AWS KMS key that you provide.

Choose Copy to save the code locally.

Create the file encrypt_object_sseck.rb.

Add the required Amazon S3 and md5 gems.

Note

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

require 'aws-sdk-s3' # In v2: require 'aws-sdk' require 'digest/md5'

Get the key from the command-line. If there is no command-line argument, print an error message and quit. Otherwise, create an MD5 hash of the key. Amazon S3 uses the hash to ensure the integrity of the key.

if ARGV.empty?() puts 'You must supply the key' exit 1 end key = ARGV[0] # KMS key is a string md5 = Digest::MD5.digest(key)

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

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

Create an Amazon S3 client and call put_object to upload the object to the bucket. Notice that the server_side_encryption property is set to aws:kms, indicating that Amazon S3 encrypts the object using the provided AWS KMS key. Finally, display a success message to the user.

client = Aws::S3::Client.new(region: 'us-west-2') # Encrypt item with user-supplied KMS key on server client.put_object( body: contents, bucket: bucket, key: item, sse_customer_algorithm: 'aws:kms', sse_customer_key: key, sse_customer_key_md5: md5 ) puts 'Added item ' + item + ' to bucket ' + bucket

See the complete example on GitHub.