Todos los productos
Search
Centro de documentos

Object Storage Service:Cifrado del lado del servidor (OSS SDK for Go 1.0)

Última actualización: Sep 22, 2026

Object Storage Service (OSS) cifra los datos cargados directamente en el servidor. A este proceso se le conoce como cifrado del lado del servidor. Cuando usted carga datos en OSS, el servicio los cifra y después almacena de forma persistente la versión cifrada. Al descargar datos desde OSS, el servicio los descifra y devuelve la información original. Además, se agrega un encabezado a la respuesta para indicar que los datos se cifraron en el servidor.

Notas

  • Antes de configurar el cifrado del lado del servidor, asegúrese de conocer bien esta función. Para obtener más información, consulte Server-side encryption.

  • En este tema se utiliza el endpoint público de la región China (Hangzhou). Si necesita acceder a OSS desde otros servicios de Alibaba Cloud ubicados en la misma región, utilice un endpoint interno. Para obtener más información sobre las regiones y los endpoints de OSS, consulte Regions and endpoints.

  • Las credenciales de acceso de este tema se obtienen a partir de variables de entorno. Para obtener más información sobre cómo configurar las credenciales de acceso, consulte Configure access credentials.

  • Este tema muestra cómo crear una instancia de OSSClient con un endpoint de OSS. Para configuraciones alternativas, como usar un dominio personalizado o autenticarse con credenciales de Security Token Service (STS), consulte Configure a client (Go SDK V1).

  • Para configurar el cifrado del lado del servidor de un bucket, necesita el permiso oss:PutBucketEncryption. Para consultar la configuración de cifrado del lado del servidor de un bucket, necesita el permiso oss:GetBucketEncryption. Para eliminar la configuración de cifrado del lado del servidor de un bucket, necesita el permiso oss:DeleteBucketEncryption. Para obtener más información, consulte Grant a custom policy.

Código de ejemplo

Código de ejemplo

Configure server-side encryption for a bucket

A continuación se muestra un ejemplo de código para configurar un método de cifrado predeterminado en un bucket. Una vez establecido, todos los objetos que se carguen en el bucket sin especificar un método de cifrado utilizarán automáticamente el método predeterminado.

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

El siguiente código de ejemplo muestra cómo consultar la configuración de cifrado del lado del servidor de un 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

El siguiente código de ejemplo muestra cómo eliminar la configuración de cifrado del lado del servidor de un 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")
}

Referencias

  • Para consultar el código de ejemplo completo del cifrado del lado del servidor, visite GitHub.

  • Para obtener más información sobre la operación de API que permite configurar el cifrado del lado del servidor, consulte SetBucketEncryption.

  • Para obtener más información sobre la operación de API que permite consultar la configuración de cifrado del lado del servidor, consulte GetBucketEncryption.

  • Para obtener más información sobre la operación de API que permite eliminar la configuración de cifrado del lado del servidor, consulte DeleteBucketEncryption.