AWS SDK for Go
Developer Guide

Requiring Encryption on the Server to Upload Amazon S3 Bucket Objects

The following example uses the PutBucketPolicy method to require that objects uploaded to an Amazon S3 bucket have Amazon S3 encrypt the object with an AWS KMS key. Attempts to upload an object without specifying that Amazon S3 encrypt the object with an AWS KMS key raise an Aws::S3::Errors::AccessDenied exception.

Avoid using this configuration option if you use default server-side encryption as described in Setting Default Server-Side Encryption for an Amazon S3 Bucket as they could conflict and result in unexpected results.

Choose Copy to save the code locally.

Create the file require_server_encryption.go.

Import the required packages.

import ( "" "" "" "fmt" "os" "encoding/json" )

Set the name of the bucket, create a session, and create an Amazon S3 client.

SharedConfigState: session.SharedConfigEnable, })) svc := s3.New(sess)

Create an Amazon S3 policy that requires server-side KMS encryption on objects uploaded to the bucket.

"Version": "2012-10-17", "Statement": []map[string]interface{}{ { "Sid": "DenyIncorrectEncryptionHeader", "Effect": "Deny", "Principal": "*", "Action": "s3:PutObject", "Resource": "arn:aws:s3:::" + bucket + "/*", "Condition": map[string]interface{}{ "StringNotEquals": map[string]interface{}{ "s3:x-amz-server-side-encryption": "aws:kms", }, }, }, { "Sid": "DenyUnEncryptedObjectUploads", "Effect": "Deny", "Principal": "*", "Action": "s3:PutObject", "Resource": "arn:aws:s3:::" + bucket + "/*", "Condition": map[string]interface{}{ "Null": map[string]interface{}{ "s3:x-amz-server-side-encryption": "true", }, }, }, }, }

Convert the policy into JSON, create the input for and call PutBucketPolicy, apply the policy to the bucket, and print a success message.

if err != nil { Bucket: aws.String(bucket), Policy: aws.String(string(policy)), } if err != nil {

See the complete example on GitHub.