Decrypting an Amazon S3 Bucket Object with a Private Key - AWS SDK for Ruby

Decrypting an Amazon S3 Bucket Object with a Private Key

The following example uses the get_object method to get the object my_item from the bucket my_bucket in the us-west-2 region. Then it decrypts the contents with the PKey class.

  1. Create the file decrypt_object_csepk.rb.

  2. Add the required Amazon S3 and OpenSSL gems.


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

  1. Get the pass phrase from the command line.

  2. Set the bucket name, object name, and name of the private key file.

  3. Create an RSA key from the contents of the key file and passphrase.

6. Create an Amazon S3 encryption client, call get_object, get the contents of the object as text and print out the object’s contents.

# Copyright, Inc. or its affiliates. All Rights Reserved. # SPDX - License - Identifier: Apache - 2.0 require 'aws-sdk-s3' require 'openssl' # Downloads an object from an Amazon S3 bucket. The object's contents # were originally encrypted with an RSA public key. # # Prerequisites: # # - An Amazon S3 bucket. # - An object in this bucket. # # @param s3_encryption_client [Aws::S3::EncryptionV2::Client] An initialized # Amazon S3 encryption client. # @param bucket_name [String] The bucket's name. # @param object_key [String] The name of the object. # @return [String] The object's content; otherwise, information about the # failed download operation. # @example # puts download_object_with_private_key_encryption( # # encryption_key:'my-private-key.pem')), # key_wrap_schema: :rsa_oaep_sha1, # content_encryption_schema: :aes_gcm_no_padding, # security_profile: :v2, # region: 'us-east-1' # ), # 'doc-example-bucket', # 'my-file.txt' # ) def download_object_with_private_key_encryption( s3_encryption_client, bucket_name, object_key ) response = s3_encryption_client.get_object( bucket: bucket_name, key: object_key ) return rescue StandardError => e puts "Error downloading object: #{e.message}" end # Full example call: # Prerequisites: the same RSA key pair you originally used to encrypt the object. def run_me bucket_name = 'doc-example-bucket' object_key = 'my-file.txt' region = 'us-east-1' private_key_file = 'my-private-key.pem' private_key = # When initializing this Amazon S3 encryption client, note: # - For key_wrap_schema, use rsa_oaep_sha1 for asymmetric keys. # - For security_profile, for reading or decrypting objects encrypted # by the v1 encryption client, use :v2_and_legacy instead. s3_encryption_client = encryption_key: private_key, key_wrap_schema: :rsa_oaep_sha1, content_encryption_schema: :aes_gcm_no_padding, security_profile: :v2, region: region ) puts "The content of '#{object_key}' in bucket '#{bucket_name}' is:" puts download_object_with_private_key_encryption( s3_encryption_client, bucket_name, object_key ) end run_me if $PROGRAM_NAME == __FILE__

See the complete example on GitHub.