Todos os produtos
Search
Central de documentação

Object Storage Service:Server-side encryption (OSS SDK for Go 1.0)

Última atualização: Sep 22, 2026

O Object Storage Service (OSS) pode criptografar os dados carregados no servidor. Esse processo é chamado de criptografia no lado do servidor. Ao fazer upload de dados para o OSS, o serviço criptografa os dados carregados e os armazena de forma persistente. Ao baixar dados do OSS, o serviço descriptografa os dados e retorna o conteúdo descriptografado. Além disso, o OSS adiciona um cabeçalho à resposta para indicar que os dados foram criptografados no servidor.

Observações

  • Antes de configurar a criptografia no lado do servidor, certifique-se de estar familiarizado com este recurso. Para mais informações, consulte Server-side encryption.

  • Este tópico usa o endpoint público da região China (Hangzhou). Para acessar o OSS a partir de outros serviços da Alibaba Cloud na mesma região, use um endpoint interno. Para obter mais informações sobre regiões e endpoints do OSS, consulte Regions and endpoints.

  • Neste tópico, o código obtém as credenciais de acesso a partir de variáveis de ambiente. Para saber como configurar as credenciais de acesso, consulte Configure access credentials.

  • Este tópico demonstra como criar uma instância OSSClient com um endpoint do OSS. Para configurações alternativas, como usar um domínio personalizado ou autenticar com credenciais do Security Token Service (STS), consulte Configure a client (Go SDK V1).

  • Para configurar, consultar e excluir as configurações de criptografia no lado do servidor de um bucket, você precisa ter as permissões oss:PutBucketEncryption, oss:GetBucketEncryption e oss:DeleteBucketEncryption, respectivamente. Para mais informações, consulte Grant a custom policy.

Código de exemplo

Código de exemplo

Configurar a criptografia no lado do servidor para um bucket

O código de exemplo a seguir mostra como configurar um método de criptografia padrão para um bucket. Após essa configuração, o OSS criptografa automaticamente com o método padrão todos os objetos carregados no bucket que não especificarem um método de criptografia.

package main

import (
	"log"

	"github.com/aliyun/aliyun-oss-go-sdk/oss"
)

func main() {
	// Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured. 
	provider, err := oss.NewEnvironmentVariableCredentialsProvider()
	if err != nil {
		log.Fatalf("Error creating credentials provider: %v", err)
	}

	// Create an OSSClient instance. 
	// Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. Specify your actual endpoint. 
	// Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou. Specify the actual region.
	clientOptions := []oss.ClientOption{oss.SetCredentialsProvider(&provider)}
	clientOptions = append(clientOptions, oss.Region("yourRegion"))
	// Specify the version of the signature algorithm.
	clientOptions = append(clientOptions, oss.AuthVersion(oss.AuthV4))
	client, err := oss.New("yourEndpoint", "", "", clientOptions...)
	if err != nil {
		log.Fatalf("Error creating OSS client: %v", err)
	}

	// Initialize an encryption rule. In this example, the AES-256 encryption algorithm is used. 
	config := oss.ServerEncryptionRule{
		SSEDefault: oss.SSEDefaultRule{
			SSEAlgorithm: "AES256",
		},
	}

	// Configures encryption rules for the OSS bucket.
	err = client.SetBucketEncryption("yourBucketName", config)
	if err != nil {
		log.Fatalf("Error setting bucket encryption: %v", err)
	}

	log.Println("Bucket encryption set successfully")
}

Consultar as configurações de criptografia no lado do servidor de um bucket

O código de exemplo a seguir mostra como consultar as configurações de criptografia no lado do servidor de um bucket:

package main

import (
	"log"

	"github.com/aliyun/aliyun-oss-go-sdk/oss"
)

func main() {
	// Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured. 
	provider, err := oss.NewEnvironmentVariableCredentialsProvider()
	if err != nil {
		log.Fatalf("Error creating credentials provider: %v", err)
	}

	// Create an OSSClient instance. 
	// Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. Specify your actual endpoint. 
	// Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou. Specify the actual region.
	clientOptions := []oss.ClientOption{oss.SetCredentialsProvider(&provider)}
	clientOptions = append(clientOptions, oss.Region("yourRegion"))
	// Specify the version of the signature algorithm.
	clientOptions = append(clientOptions, oss.AuthVersion(oss.AuthV4))
	client, err := oss.New("yourEndpoint", "", "", clientOptions...)
	if err != nil {
		log.Fatalf("Error creating OSS client: %v", err)
	}

	// Obtain the encryption rule configured for the bucket.
	ret, err := client.GetBucketEncryption("yourBucketName")
	if err != nil {
		log.Fatalf("Error getting bucket encryption: %v", err)
	}

	// Display the encryption rule. 
	log.Printf("Encrypt rule: %s", ret.SSEDefault.SSEAlgorithm)
}

Excluir as configurações de criptografia no lado do servidor de um bucket

O código de exemplo a seguir mostra como excluir as configurações de criptografia no lado do servidor de um bucket:

package main

import (
	"log"

	"github.com/aliyun/aliyun-oss-go-sdk/oss"
)

func main() {
	// Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured. 
	provider, err := oss.NewEnvironmentVariableCredentialsProvider()
	if err != nil {
		log.Fatalf("Error creating credentials provider: %v", err)
	}

	// Create an OSSClient instance. 
	// Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. Specify your actual endpoint. 
	// Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou. Specify the actual region.
	clientOptions := []oss.ClientOption{oss.SetCredentialsProvider(&provider)}
	clientOptions = append(clientOptions, oss.Region("yourRegion"))
	// Specify the version of the signature algorithm.
	clientOptions = append(clientOptions, oss.AuthVersion(oss.AuthV4))
	client, err := oss.New("yourEndpoint", "", "", clientOptions...)
	if err != nil {
		log.Fatalf("Error creating OSS client: %v", err)
	}

	// Delete the encryption rule configured for the bucket. 
	err = client.DeleteBucketEncryption("yourBucketName")
	if err != nil {
		log.Fatalf("Error deleting bucket encryption: %v", err)
	}

	log.Println("Bucket encryption deleted successfully")
}

Referências

  • Para obter o código de exemplo completo de criptografia no lado do servidor, acesse o GitHub.

  • Para mais detalhes sobre a operação de API que configura a criptografia no lado do servidor, consulte SetBucketEncryption.

  • Para saber mais sobre a operação de API que consulta as configurações de criptografia no lado do servidor, consulte GetBucketEncryption.

  • Para excluir as configurações de criptografia no lado do servidor via API, consulte DeleteBucketEncryption.