Todos os produtos
Search
Central de documentação

Object Storage Service:Criptografia no lado do servidor (OSS SDK for Go 1.0)

Última atualização: Jul 03, 2026

O Object Storage Service (OSS) criptografa os dados enviados no servidor, processo conhecido como criptografia no lado do servidor. Ao receber dados, o OSS criptografa e armazena o conteúdo de forma persistente. Durante o download, o serviço descriptografa os dados e retorna o conteúdo original. Além disso, adiciona um cabeçalho à resposta para indicar que a criptografia ocorreu no servidor.

Observações

  • 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, utilize um endpoint interno. Para mais detalhes sobre regiões e endpoints do OSS, consulte Regiões e endpoints.

  • As credenciais de acesso neste tópico são obtidas de variáveis de ambiente. Para saber como configurar credenciais de acesso, consulte Configurar credenciais de acesso.

  • Este tópico demonstra como criar uma instância OSSClient com um endpoint do OSS. Para configurações alternativas, como uso de domínio personalizado ou autenticação com credenciais do Security Token Service (STS), consulte Configurar um cliente (Go SDK V1).

  • A configuração da criptografia no lado do servidor em um bucket exige a permissão oss:PutBucketEncryption. A consulta das configurações requer a permissão oss:GetBucketEncryption, enquanto a exclusão exige a permissão oss:DeleteBucketEncryption. Para mais informações, consulte Conceder uma política personalizada.

Código de exemplo

Código de exemplo

Configure server-side encryption for a bucket

O código a seguir mostra como definir um método de criptografia padrão para um bucket. Após a configuração, todos os objetos enviados ao bucket sem especificação de criptografia serão protegidos automaticamente pelo método padrão.

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")
}

Query the server-side encryption configurations of a bucket

O exemplo abaixo ilustra 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)
}

Delete the server-side encryption configurations of a bucket

Use o código a seguir para 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 sobre criptografia no lado do servidor, visite o GitHub.

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

  • Sobre a operação de API para consulta das configurações de criptografia no lado do servidor, veja GetBucketEncryption.

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