Menu
AWS SDK for Go
Developer Guide

Encrypting an Amazon S3 Bucket Object with a User-Supplied AWS KMS Key

The following example uses the PutObject method to add the object myObject to the bucket myBucket.

Choose Copy to save the code locally.

Create the file encrypt_object.go.

Include the required packages.

import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/session" "github.com/aws/aws-sdk-go/service/kms" "github.com/aws/aws-sdk-go/service/s3" "github.com/aws/aws-sdk-go/service/s3/s3crypto" "fmt" "os" "strings" )

Get AWS KMS key from the command line, where key is an AWS KMS key ID as created in the Creating a CMK in AWS Key Management Service example, and set the bucket and object names.

if len(os.Args) != 2 { fmt.Println("You must supply a bucket name, object name, and key") os.Exit(1) } key := os.Args[0] bucket := "myBucket" object := "myObject"

Create a session and encryption client.

sess := session.Must(session.NewSessionWithOptions(session.Options{ SharedConfigState: session.SharedConfigEnable, })) handler := s3crypto.NewKMSKeyGenerator(kms.New(sess), key) svc := s3crypto.NewEncryptionClient(sess, s3crypto.AESGCMContentCipherBuilder(handler))

Create the input for and call PutObject to upload the object to the bucket, and display a success message.

input := &s3.PutObjectInput{ Body: strings.NewReader(object), Bucket: aws.String(bucket), Key: aws.String(object), } _, err := svc.PutObject(input) fmt.Println("Added object " + object + " to bucket " + bucket + " with AWS KMS encryption on the client")

See the complete example on GitHub.