Todos os produtos
Search
Central de documentação

Object Storage Service:Criptografia no lado do servidor (Go SDK V2)

Última atualização: Jul 03, 2026

O OSS oferece suporte à criptografia no lado do servidor (SSE). Ao fazer upload de dados, o OSS criptografa e armazena as informações. Durante o download, o OSS descriptografa os dados automaticamente e retorna o conteúdo original. O cabeçalho de resposta HTTP indica que a criptografia ocorreu no servidor.

Observações

  • Antes de configurar a criptografia no lado do servidor, certifique-se de compreender esse recurso. Para mais informações, consulte Criptografia no lado do servidor.

  • O código de exemplo neste tópico utiliza o ID da região China (Hangzhou) cn-hangzhou e um endpoint público. Caso acesse o OSS a partir de outro serviço da Alibaba Cloud na mesma região, utilize um endpoint interno. Para obter mais detalhes sobre regiões e endpoints do OSS, consulte Regiões e endpoints.

  • Este tópico emprega variáveis de ambiente para ler credenciais de acesso. Para saber como configurar essas credenciais, consulte Configurar credenciais de acesso.

  • Para definir a criptografia do bucket, você precisa da permissão oss:PutBucketEncryption. Para consultar as configurações, é necessária a permissão oss:GetBucketEncryption. Para excluir essas configurações, você deve ter a permissão oss:DeleteBucketEncryption. Para mais informações, consulte Conceder políticas de acesso personalizadas a usuários RAM.

Código de exemplo

Configure bucket encryption

Use o código abaixo para defina o método de criptografia padrão de um bucket. Após essa configuração, todos os objetos enviados ao bucket sem um método específico serão criptografados conforme o padrão estabelecido.

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 global variables.
var (
	region     string // The storage region.
	bucketName string // The bucket name.
)

// The init function is 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 bucket name is empty.
	if len(bucketName) == 0 {
		flag.PrintDefaults()
		log.Fatalf("invalid parameters, bucket name required")
	}

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

	// Load the default configurations and set 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 set the encryption rule for the bucket.
	request := &oss.PutBucketEncryptionRequest{
		Bucket: oss.Ptr(bucketName), // The bucket name.
		ServerSideEncryptionRule: &oss.ServerSideEncryptionRule{
			ApplyServerSideEncryptionByDefault: &oss.ApplyServerSideEncryptionByDefault{
				SSEAlgorithm:      oss.Ptr("KMS"), // Use the KMS encryption algorithm.
				KMSDataEncryption: oss.Ptr("SM4"), // Use the SM4 data encryption algorithm.
			},
		},
	}

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

	// Print the result of setting the encryption rule for the bucket.
	log.Printf("put bucket encryption result:%#v\n", result)
}

Get bucket encryption configurations

Use o código a seguir para recuperar a configuração de criptografia do 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 global variables.
var (
	region     string // The storage region.
	bucketName string // The bucket name.
)

// The init function is 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 bucket name is empty.
	if len(bucketName) == 0 {
		flag.PrintDefaults()
		log.Fatalf("invalid parameters, bucket name required")
	}

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

	// Load the default configurations and set 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 get the bucket encryption configuration.
	request := &oss.GetBucketEncryptionRequest{
		Bucket: oss.Ptr(bucketName), // The bucket name.
	}

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

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

Delete bucket encryption configurations

Use o código abaixo para exclua a configuração de criptografia do 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 global variables.
var (
	region     string // The storage region.
	bucketName string // The bucket name.
)

// The init function is 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 bucket name is empty.
	if len(bucketName) == 0 {
		flag.PrintDefaults()
		log.Fatalf("invalid parameters, bucket name required")
	}

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

	// Load the default configurations and set 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 bucket encryption configuration.
	request := &oss.DeleteBucketEncryptionRequest{
		Bucket: oss.Ptr(bucketName), // The bucket name.
	}

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

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

Referências