AWS SDK for Ruby
Developer Guide

Encrypting an Amazon S3 Bucket Object on the Server

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 encryption set KMS.

Note that this differs from Setting Default Server-Side Encryption for an Amazon S3 Bucket, is in that case, the objects are encrypted without you having to explicitly perform the operation.

Choose Copy to save the code locally.

Create the file encrypt_object_sse.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'

Set the bucket and object name and get 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 KMS. Finally, display a success message to the user.

client = Aws::S3::Client.new(region: 'us-west-2') client.put_object( body: contents, bucket: bucket, key: item, server_side_encryption: 'aws:kms' ) puts 'Added item ' + name + ' to bucket ' + bucket

See the complete example on GitHub.