AWS SDK for Ruby
Developer Guide

Encrypting an Amazon S3 Bucket Object with a Public Key

The following example uses the PKey class to encrypt an object with a public key and 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_csepk.rb.

Add the required Amazon S3 and OpenSSL gems.


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

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

Set the bucket name, object name, and name of the file containing the public key. See Creating Public and Private Asymmetric Keys for information about creating a public key.

bucket = 'my_bucket' item = 'my_item' key_file = 'public_key.pem'

Get the file contents as a string; get the public key from the file and create a new RSA key to encrypt the bucket object.

contents = public_key = key =

Create an Amazon S3 encryption client and call put_object to upload the object to the bucket. Finally, display a message to the user about the results.

enc_client = key) # Add encrypted item to bucket enc_client.put_object( body: contents, bucket: bucket, key: item_name ) puts 'Added ' + item_name + ' to bucket ' + bucket + ' using key from ' + key_file

See the complete example on GitHub.