All Products
Search
Document Center

Object Storage Service:Server-side encryption using OSS SDK for Go

Last Updated:Feb 27, 2025

Server-side encryption for uploaded data is supported. When you upload data, OSS encrypts the received data and stores the encrypted data. When you download the encrypted data, OSS automatically decrypts the data, returns the original data to you, and declares in the header of the response that the data had been encrypted on the server.

Notes

  • Make sure that you are familiar with this feature before you configure server-side encryption. For more information, see server-side encryption.

  • The sample code in this topic uses the region ID of the China (Hangzhou) region. By default, the public endpoint is used to access resources in a bucket. If you want to access resources in the bucket by using other Alibaba Cloud services in the same region in which the bucket is located, use an internal endpoint. For more information about supported regions and endpoints, see OSS regions and endpoints.

  • In this topic, access credentials are obtained from environment variables. For more information about how to configure access credentials, see Configure access credentials.

  • The oss:PutBucketEncryption permission is required for the configuration of server-side encryption for a bucket. The oss:GetBucketEncryption permission is required for querying the server-side encryption configurations of a bucket. The oss:DeleteBucketEncryption permission is required for deleting the server-side encryption configurations of a bucket. For more information, see Grant custom policy to RAM users.

Sample code

Configure server-side encryption for a bucket

The following code provides an example of how to configure the default encryption method for a bucket. After the method is configured, all objects that are uploaded to the bucket without encryption methods configured are encrypted using the default encryption method.

package main

import (
	"context"
	"flag"
	"log"

	"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss"
	"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss/credentials"
)

// Define the global variables.
var (
	region     string // The region in which your bucket is located. 
	bucketName string // The name of your bucket.
)

// Specify the init function used to initialize command line parameters.
func init() {
	flag.StringVar(&region, "region", "", "The region in which the bucket is located.")
	flag.StringVar(&bucketName, "bucket", "", "The name of the bucket.")
}

func main() {
	// Parse command line parameters.
	flag.Parse()

	// Check whether the name of your bucket is specified.
	if len(bucketName) == 0 {
		flag.PrintDefaults()
		log.Fatalf("invalid parameters, bucket name required")
	}

	// Check whether the region is specified.
	if len(region) == 0 {
		flag.PrintDefaults()
		log.Fatalf("invalid parameters, region required")
	}

	// Load the default configurations and specify the credential provider and region.
	cfg := oss.LoadDefaultConfig().
		WithCredentialsProvider(credentials.NewEnvironmentVariableCredentialsProvider()).
		WithRegion(region)

	// Create an OSS client.
	client := oss.NewClient(cfg)

	// Create a request to configure encryption rules for your bucket.
	request := &oss.PutBucketEncryptionRequest{
		Bucket: oss.Ptr(bucketName), // The name of the bucket
		ServerSideEncryptionRule: &oss.ServerSideEncryptionRule{
			ApplyServerSideEncryptionByDefault: &oss.ApplyServerSideEncryptionByDefault{
				SSEAlgorithm:      oss.Ptr("KMS"), // Use the Key Management Service (KMS)-based encryption algorithm.
				KMSDataEncryption: oss.Ptr("SM4"), // Use the SM4 encryption algorithm.
			},
		},
	}

	// Send the request for configuring encryption rules for your bucket.
	result, err := client.PutBucketEncryption(context.TODO(), request)
	if err != nil {
		log.Fatalf("failed to put bucket encryption %v", err)
	}

	// Display the result.
	log.Printf("put bucket encryption result:%#v\n", result)
}

Query the server-side encryption configurations of a bucket

The following code provides an example of how to query the server-side encryption configurations of a bucket.

package main

import (
	"context"
	"flag"
	"log"

	"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss"
	"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss/credentials"
)

// Define the global variables.
var (
	region     string // The region in which your bucket is located.
	bucketName string // The name of your bucket.
)

// Specify the init function used to initialize command line parameters.
func init() {
	flag.StringVar(&region, "region", "", "The region in which the bucket is located.")
	flag.StringVar(&bucketName, "bucket", "", "The name of the bucket.")
}

func main() {
	// Parse command line parameters.
	flag.Parse()

	// Check whether the name of your bucket is specified.
	if len(bucketName) == 0 {
		flag.PrintDefaults()
		log.Fatalf("invalid parameters, bucket name required")
	}

	// Check whether the region is specified.
	if len(region) == 0 {
		flag.PrintDefaults()
		log.Fatalf("invalid parameters, region required")
	}

	// Load the default configurations and specify the credential provider and region.
	cfg := oss.LoadDefaultConfig().
		WithCredentialsProvider(credentials.NewEnvironmentVariableCredentialsProvider()).
		WithRegion(region)

	// Create an OSS client.
	client := oss.NewClient(cfg)

	// Create a request to query the server-side encryption configurations of your bucket.
	request := &oss.GetBucketEncryptionRequest{
		Bucket: oss.Ptr(bucketName), // The name of the bucket
	}

	// Run the query and process the result.
	result, err := client.GetBucketEncryption(context.TODO(), request)
	if err != nil {
		log.Fatalf("failed to get bucket encryption %v", err)
	}

	// Display the result.
	log.Printf("get bucket encryption result:%#v\n", result)
}

Delete the server-side encryption configurations of a bucket

The following code provides an example of how to delete the server-side encryption configurations of a bucket.

package main

import (
	"context"
	"flag"
	"log"

	"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss"
	"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss/credentials"
)

// Define the global variables.
var (
	region     string // The region in which your bucket is located.
	bucketName string // The name of the bucket.
)

// Specify the init function used to initialize command line parameters.
func init() {
	flag.StringVar(&region, "region", "", "The region in which the bucket is located.")
	flag.StringVar(&bucketName, "bucket", "", "The name of the bucket.")
}

func main() {
	// Parse command line parameters.
	flag.Parse()

	// Check whether the name of your bucket is specified.
	if len(bucketName) == 0 {
		flag.PrintDefaults()
		log.Fatalf("invalid parameters, bucket name required")
	}

	// Check whether the region is specified.
	if len(region) == 0 {
		flag.PrintDefaults()
		log.Fatalf("invalid parameters, region required")
	}

	// Load the default configurations and specify the credential provider and region.
	cfg := oss.LoadDefaultConfig().
		WithCredentialsProvider(credentials.NewEnvironmentVariableCredentialsProvider()).
		WithRegion(region)

	// Create an OSS client.
	client := oss.NewClient(cfg)

	// Create a request to delete the server-side encryption configurations of your bucket.
	request := &oss.DeleteBucketEncryptionRequest{
		Bucket: oss.Ptr(bucketName), // The name of the bucket
	}

	// Delete the server-side encryption configurations and process the result
	result, err := client.DeleteBucketEncryption(context.TODO(), request)
	if err != nil {
		log.Fatalf("failed to delete bucket encryption %v", err)
	}

	// Display the result.
	log.Printf("delete bucket encryption result:%#v\n", result)
}

References