Todos los productos
Search
Centro de documentos

Object Storage Service:Server-side encryption

Última actualización: Sep 12, 2026

Cuando usted carga un objeto a un bucket con el cifrado del lado del servidor habilitado, Object Storage Service (OSS) cifra el objeto antes de almacenarlo. Cuando descarga el objeto mediante una solicitud GetObject, OSS descifra automáticamente el objeto y se lo devuelve. El encabezado x-oss-server-side-encryption en la respuesta indica que el objeto se cifró del lado del servidor.

Nota

Para obtener más información sobre el encabezado de respuesta x-oss-server-side-encryption, consulte GetObject.

Escenarios

OSS protege los datos en reposo mediante el cifrado del lado del servidor. Esta función es adecuada para aplicaciones con requisitos estrictos de seguridad o cumplimiento en el almacenamiento de datos. Por ejemplo, resulta útil al almacenar archivos de muestra para aprendizaje profundo o datos de documentos colaborativos en línea.

Métodos de cifrado

OSS ofrece dos métodos de cifrado del lado del servidor para distintos escenarios. Seleccione el método que mejor se ajuste a sus necesidades.

Método de cifrado

Descripción

Escenarios

Notas

Facturación

Cifrar y descifrar datos con claves administradas por Key Management Service (KMS) (SSE-KMS)

Utilice la clave maestra del cliente (CMK) predeterminada administrada por KMS o una CMK específica para cifrar y descifrar datos. Los datos se cifran y descifran sin enviarse por la red al servidor de KMS.

Recomendado cuando necesita usar claves propias que pueda especificar por motivos de seguridad y cumplimiento.

  • La clave utilizada para cifrar un objeto también se cifra y se almacena en los metadatos del objeto.

  • El método de cifrado SSE-KMS cifra únicamente los datos del objeto, no sus metadatos.

  • La clave de KMS creada de forma predeterminada en la consola de OSS no genera cargos.

  • Si utiliza su propia clave de KMS, se generan cargos en KMS. Para obtener más información, consulte KMS pricing.

Cifrar y descifrar datos con claves administradas por OSS (SSE-OSS)

Utilice una clave administrada completamente por OSS para cifrar cada objeto. Para mayor seguridad, OSS también usa una clave maestra para cifrar la propia clave de cifrado de datos.

Diseñado para escenarios donde solo requiere un cifrado básico y no necesita administrar claves.

Ninguna.

Sin costo.

Notas

  • Cuando cargue, descargue o acceda a objetos en un bucket con el cifrado SSE-KMS habilitado, asegúrese de tener permisos para usar el ID de CMK especificado y de que la solicitud no sea anónima. De lo contrario, la solicitud fallará y se devolverá el error This request is forbidden by kms.

  • Los objetos replicados a un bucket mediante back-to-origin basado en duplicación no se cifran de forma predeterminada.

  • Habilitar o modificar el método de cifrado de un bucket no afecta la configuración de cifrado de los objetos existentes en dicho bucket.

  • Solo se puede aplicar un método de cifrado del lado del servidor a un objeto a la vez.

  • Si configura el cifrado para un bucket, aún puede especificar un método de cifrado distinto para un objeto individual al cargarlo o copiarlo. En este caso, prevalece el método de cifrado especificado para el objeto. Para obtener más información, consulte PutObject.

Permisos

A continuación se describen los permisos que necesita un usuario de Resource Access Management (RAM) para utilizar el cifrado del lado del servidor en distintos escenarios.

Nota

Para obtener más información sobre cómo otorgar permisos a un usuario de RAM, consulte Grant custom permissions to a RAM user.

  • Configurar el método de cifrado de un bucket

    • Permisos de administración sobre el bucket de destino.

    • Los permisos PutBucketEncryption y GetBucketEncryption.

    • Si establece el método de cifrado en SSE-KMS y especifica un ID de CMK, también se requieren los permisos ListKeys, ListAliases, ListAliasesByKeyId y DescribeKey. A continuación se muestra un ejemplo de directiva de RAM para este escenario:

      {
        "Version": "1",
        "Statement": [
          {
            "Effect": "Allow",
            "Action": [
              "kms:List*",
              "kms:DescribeKey"    
            ],
            "Resource": [
              "acs:kms:*:141661496593****:*" // This policy lets you call all KMS keys under the Alibaba Cloud account ID. To allow the use of only a specific CMK, enter the corresponding CMK ID.
            ]
          }
        ]
      }
  • Cargar un objeto a un bucket cifrado

    • Permisos para cargar objetos en el bucket de destino.

    • Si el método de cifrado se establece en KMS y se especifica un ID de CMK, también se requieren los permisos ListKeys, ListAliases, ListAliasesByKeyId, DescribeKey, GenerateDataKey y Decrypt. A continuación se muestra un ejemplo de directiva de RAM para este escenario:

      {
        "Version": "1",
        "Statement": [
          {
            "Effect": "Allow",
            "Action": [
              "kms:List*",
              "kms:DescribeKey",
              "kms:GenerateDataKey",
              "kms:Decrypt"
            ],
            "Resource": [
              "acs:kms:*:141661496593****:*"// This policy lets you call all KMS keys under the Alibaba Cloud account ID. To allow the use of only a specific CMK, enter the corresponding CMK ID.
            ]
          }
        ]
      }
  • Descargar un objeto de un bucket cifrado

    • Permisos para acceder a los objetos del bucket de destino.

    • Si el método de cifrado se establece en KMS y se especifica un ID de CMK, también se requiere el permiso Decrypt. A continuación se muestra un ejemplo de directiva de RAM para este escenario:

      {
        "Version": "1",
        "Statement": [
          {
            "Effect": "Allow",
            "Action": [
              "kms:Decrypt"
            ],
            "Resource": [
              "acs:kms:*:141661496593****:*"// This policy grants permissions to decrypt data using all KMS keys under the Alibaba Cloud account ID. To grant permissions to decrypt data using a specific KMS key, enter the corresponding CMK ID.
            ]
          }
        ]
      }

Procedimientos

Importante
  • Si adquiere el servicio complementario de rotación de claves para KMS, el cifrado del lado del servidor es compatible con key rotation para las claves de KMS. Una vez habilitada la rotación de claves, la nueva clave se utiliza únicamente para cifrar los objetos que se carguen a partir de ese momento. Las claves de cifrado de los objetos existentes no cambian.

  • Si actualiza la clave de cifrado de KMS en OSS, la nueva clave cifra solo los objetos que se carguen después de la actualización. Los objetos cargados antes conservan el cifrado con la clave anterior. Por lo tanto, no elimine la clave antigua tras la actualización; de lo contrario, no podrá acceder a los objetos existentes.

Uso de la consola de OSS

Método 1: Habilitar el cifrado del lado del servidor para un bucket

Habilitar el cifrado del lado del servidor al crear un bucket

  1. Inicie sesión en la consola de OSS.

  2. Haga clic en Buckets y luego en Create Bucket.

  3. En el panel Create Bucket, configure los siguientes parámetros.

    A continuación se muestran los parámetros que configuran el cifrado del lado del servidor para una región:

    Parámetro

    Descripción

    Encryption Method

    Seleccione un método de cifrado para los objetos. Valores válidos:

    • None: El cifrado del lado del servidor está deshabilitado.

    • SSE-OSS: Utiliza claves administradas por OSS para el cifrado. OSS emplea una clave distinta para cifrar cada objeto. Como protección adicional, usa una clave maestra para cifrar la propia clave de cifrado de datos.

    • SSE-KMS: Emplea la CMK predeterminada administrada por KMS o una CMK específica para cifrar y descifrar.

      Antes de usar SSE-KMS, debe activar KMS. Para obtener más información, consulte Purchase a dedicated KMS instance.

    Encryption Algorithm

    Solo es compatible con el algoritmo de cifrado AES256.

    CMK

    Esta opción se configura únicamente cuando selecciona KMS como método de cifrado del lado del servidor.

    Seleccione una clave de cifrado. La clave tiene el formato <alias>(CMK ID). <alias> es el alias de la CMK y CMK ID es su identificador. Valores válidos:

    • alias/acs/oss(CMK ID): Si elige esta opción, OSS utiliza la clave de servicio predeterminada para cifrar los datos del bucket y los descifra automáticamente cuando descarga objetos de él.

    • alias/<cmkname>(CMK ID): Con esta opción, OSS emplea la clave de servicio especificada para cifrar los datos del bucket y registra el identificador de la CMK en los metadatos del objeto cifrado. Cuando un usuario con permisos de descifrado descarga el objeto, este se descifra automáticamente. <cmkname> es un alias opcional de la CMK que definió al crear la clave.

      Antes de usar un identificador de CMK específico, debe crear una clave estándar o externa en la misma región que el bucket desde la consola de KMS. Para obtener más información, consulte Create a CMK.

    Para obtener más información sobre los demás parámetros, consulte Create a bucket.

  4. Haga clic en OK.

Habilitar el cifrado del lado del servidor para un bucket existente

  1. Inicie sesión en la consola de OSS.

  2. En el panel de navegación izquierdo, haga clic en Buckets. En la página Buckets, busque el bucket deseado y haga clic en él.

  3. En el panel de navegación izquierdo, seleccione Content Security > Server-side Encryption.

  4. En la página Server-side Encryption, haga clic en Configure y configure los parámetros.

    Parámetro

    Descripción

    Encryption Method

    Seleccione un método de cifrado para los objetos. Valores válidos:

    • None: El cifrado del lado del servidor está deshabilitado.

    • SSE-OSS: Utiliza claves administradas por OSS para el cifrado. OSS emplea una clave distinta para cifrar cada objeto. Como protección adicional, usa una clave maestra para cifrar la propia clave de cifrado de datos.

    • SSE-KMS: Emplea la CMK predeterminada administrada por KMS o una CMK específica para cifrar y descifrar.

      Antes de usar SSE-KMS, debe activar KMS. Para obtener más información, consulte Purchase a dedicated KMS instance.

    Encryption Algorithm

    Solo se admite el algoritmo de cifrado AES256.

    CMK

    Este parámetro es obligatorio únicamente cuando establece Encryption Method en SSE-KMS.

    Seleccione una clave de cifrado. La clave tiene el formato <alias>(CMK ID). <alias> es el alias de la CMK y CMK ID es su identificador. Valores válidos:

    • Default Service Key: Si elige esta opción, OSS genera una clave de servicio predeterminada para cifrar los datos del bucket y los descifra automáticamente cuando descarga objetos de él. La clave de servicio predeterminada creada por OSS tiene el formato alias/acs/oss (CMK ID). Puede consultar esta clave de servicio en la consola de KMS.

      Nota

      Antes de ver esta clave de servicio en la consola de KMS, debe cargar como mínimo un objeto en el bucket de destino. Esto garantiza que se cree la clave de cifrado correspondiente y se asocie a su servicio de OSS.

    • alias/<cmkname>(CMK ID): Con esta opción, OSS emplea la clave de servicio especificada para cifrar los datos del bucket y registra el identificador de la CMK en los metadatos del objeto cifrado. Cuando un usuario con permisos de descifrado descarga el objeto, este se descifra automáticamente. <cmkname> es un alias opcional de la CMK que definió al crear la clave.

      Antes de usar un identificador de CMK específico, debe crear una clave estándar o externa en la misma región que el bucket desde la consola de KMS. Para obtener más información, consulte Create a CMK.

  5. Haga clic en Save.

Método 2: Establecer el cifrado del lado del servidor al cargar un objeto

Para obtener más información, consulte Simple upload.

Uso de los SDK de Alibaba Cloud

Método 1: Habilitar el cifrado del lado del servidor para un bucket

Los SDK le permiten habilitar el cifrado del lado del servidor en buckets existentes. No es posible habilitarlo durante la creación de un bucket mediante un SDK. A continuación se muestran ejemplos de código para habilitar el cifrado del lado del servidor en un bucket existente con los SDK más comunes. Para conocer cómo hacerlo con otros SDK, consulte Introduction to Alibaba Cloud SDKs.

import com.aliyun.oss.*;
import com.aliyun.oss.common.auth.*;
import com.aliyun.oss.common.comm.SignVersion;
import com.aliyun.oss.model.*;

public class Demo {
    public static void main(String[] args) throws Throwable {
        // Specify the endpoint of the region. In this example, the endpoint of the China (Hangzhou) region is used. Specify your actual endpoint. 
        String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
        // 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. 
        EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
        // Specify the name of the bucket. Example: examplebucket. 
        String bucketName = "examplebucket";
        // 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. 
        String region = "cn-hangzhou";

        // Create an OSSClient instance.
        // Call the shutdown method to release resources when the OSSClient is no longer in use. 
        ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
        clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);        
        OSS ossClient = OSSClientBuilder.create()
        .endpoint(endpoint)
        .credentialsProvider(credentialsProvider)
        .clientConfiguration(clientBuilderConfiguration)
        .region(region)               
        .build();

        try {
            // Set the encryption algorithm to SM4 for the bucket. If AES-256 is used, replace SSEAlgorithm.SM4 with SSEAlgorithm.AES256. 
            ServerSideEncryptionByDefault applyServerSideEncryptionByDefault = new ServerSideEncryptionByDefault(SSEAlgorithm.SM4);
            ServerSideEncryptionConfiguration sseConfig = new ServerSideEncryptionConfiguration();
            sseConfig.setApplyServerSideEncryptionByDefault(applyServerSideEncryptionByDefault);
            SetBucketEncryptionRequest request = new SetBucketEncryptionRequest(bucketName, sseConfig);
            ossClient.setBucketEncryption(request);
        } catch (OSSException oe) {
            System.out.println("Caught an OSSException, which means your request made it to OSS, "
                    + "but was rejected with an error response for some reason.");
            System.out.println("Error Message:" + oe.getErrorMessage());
            System.out.println("Error Code:" + oe.getErrorCode());
            System.out.println("Request ID:" + oe.getRequestId());
            System.out.println("Host ID:" + oe.getHostId());
        } catch (ClientException ce) {
            System.out.println("Caught an ClientException, which means the client encountered "
                    + "a serious internal problem while trying to communicate with OSS, "
                    + "such as not being able to access the network.");
            System.out.println("Error Message:" + ce.getMessage());
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }
}
<?php

// Import the autoloader file to load dependencies.
require_once __DIR__ . '/../vendor/autoload.php';

use AlibabaCloud\Oss\V2 as Oss;

// Define command line argument descriptions.
$optsdesc = [
    "region" => ['help' => 'The region in which the bucket is located', 'required' => True], // Required. The region where the bucket is located.
    "endpoint" => ['help' => 'The domain names that other services can use to access OSS', 'required' => False], // Optional. The domain name that other services can use to access OSS.
    "bucket" => ['help' => 'The name of the bucket', 'required' => True], // Required. The name of the bucket.
];

// Generate a long options list to parse command line arguments.
$longopts = \array_map(function ($key) {
    return "$key:"; // A colon (:) after each parameter indicates that a value is required.
}, array_keys($optsdesc));

// Parse the command line arguments.
$options = getopt("", $longopts); 

// Check if required arguments are missing.
foreach ($optsdesc as $key => $value) {
    if ($value['required'] === True && empty($options[$key])) {
        $help = $value['help'];
        echo "Error: the following arguments are required: --$key, $help"; // Prompt the user that a required argument is missing.
        exit(1); 
    }
}

// Get the command line argument values.
$region = $options["region"]; // The region where the bucket is located.
$bucket = $options["bucket"]; // The bucket name.

// Load credentials (AccessKeyId and AccessKeySecret) from environment variables.
$credentialsProvider = new Oss\Credentials\EnvironmentVariableCredentialsProvider();

// Use the default configurations of the SDK.
$cfg = Oss\Config::loadDefault();

// Set the credential provider.
$cfg->setCredentialsProvider($credentialsProvider);

// Set the region.
$cfg->setRegion($region);

// If an endpoint is provided, set the endpoint.
if (isset($options["endpoint"])) {
    $cfg->setEndpoint($options["endpoint"]);
}

// Create an OSS client instance.
$client = new Oss\Client($cfg);

// Create a request object to set the bucket encryption configuration. Use the KMS encryption algorithm and specify SM4 as the data encryption method.
$request = new Oss\Models\PutBucketEncryptionRequest(
    bucket: $bucket, 
    serverSideEncryptionRule: new Oss\Models\ServerSideEncryptionRule(
        applyServerSideEncryptionByDefault: new Oss\Models\ApplyServerSideEncryptionByDefault(
            sseAlgorithm: 'KMS', // Use the KMS encryption algorithm.
            kmsDataEncryption: 'SM4' // The data encryption method is SM4.
    ))
);

// Call the putBucketEncryption method to set the encryption configuration for the bucket.
$result = $client->putBucketEncryption($request);

// Print the response.
printf(
    'status code:' . $result->statusCode . PHP_EOL . // The HTTP response status code.
    'request id:' . $result->requestId // The unique identifier of the request.
);
const OSS = require("ali-oss");

const client = new OSS({
  // Set region to the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set region to oss-cn-hangzhou.
  region: 'yourregion',
  // Obtain access credentials from environment variables. Before you run this code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set.
  accessKeyId: process.env.OSS_ACCESS_KEY_ID,
  accessKeySecret: process.env.OSS_ACCESS_KEY_SECRET,
  authorizationV4: true,
  // Set bucket to the name of your bucket.
  bucket: 'yourbucketname'
});

async function putBucketEncryption() {
  try {
    // Configure the encryption method for the bucket.    

    const result = await client.putBucketEncryption("bucket-name", {
      SSEAlgorithm: "AES256", // This example shows how to set AES256 encryption. If you use KMS encryption, you must add the KMSMasterKeyID property.
      // KMSMasterKeyID: "yourKMSMasterKeyId". Set the KMS key ID. You can set this parameter if the encryption method is KMS. If the value of SSEAlgorithm is KMS and you use a specified key for encryption, you must enter the key ID. Otherwise, this parameter must be empty.
    });
    console.log(result);
  } catch (e) {
    console.log(e);
  }
}

putBucketEncryption();
using Aliyun.OSS;
using Aliyun.OSS.Common;
// 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. 
var endpoint = "yourEndpoint";
// 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. 
var accessKeyId = Environment.GetEnvironmentVariable("OSS_ACCESS_KEY_ID");
var accessKeySecret = Environment.GetEnvironmentVariable("OSS_ACCESS_KEY_SECRET");
// Specify the name of the bucket. Example: examplebucket. 
var bucketName = "examplebucket";
// 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.
const string region = "cn-hangzhou";
            
// Create a ClientConfiguration instance and modify parameters as required.
var conf = new ClientConfiguration();
            
// Use the signature algorithm V4.
 conf.SignatureVersion = SignatureVersion.V4;
            
// Create an OSSClient instance.
var client = new OssClient(endpoint, accessKeyId, accessKeySecret, conf);
client.SetRegion(region);
try
{
    // Configure server-side encryption for the bucket. 
    var request = new SetBucketEncryptionRequest(bucketName, "KMS", null);
    client.SetBucketEncryption(request);
    Console.WriteLine("Set bucket:{0} Encryption succeeded ", bucketName);
}
catch (OssException ex)
{
    Console.WriteLine("Failed with error code: {0}; Error info: {1}. \nRequestID:{2}\tHostID:{3}",
        ex.ErrorCode, ex.Message, ex.RequestId, ex.HostId);
}
catch (Exception ex)
{
    Console.WriteLine("Failed with error info: {0}", ex.Message);
}
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")
}
#include <alibabacloud/oss/OssClient.h>
using namespace AlibabaCloud::OSS;

int main(void)
{
    /* Initialize the OSS account information. */
            
    /* Set yourEndpoint to the endpoint of the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. */
    std::string Endpoint = "yourEndpoint";
    /* Set yourRegion to the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the region to cn-hangzhou. */
    std::string Region = "yourRegion";
    /* Set the bucket name. Example: examplebucket. */
    std::string BucketName = "examplebucket";

    /* Initialize network and other resources. */
    InitializeSdk();

    ClientConfiguration conf;
    conf.signatureVersion = SignatureVersionType::V4;
    /* Obtain access credentials from environment variables. Before you run this sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set. */
    auto credentialsProvider = std::make_shared<EnvironmentVariableCredentialsProvider>();
    OssClient client(Endpoint, credentialsProvider, conf);
    client.SetRegion(Region);

    SetBucketEncryptionRequest setrequest(BucketName);
    setrequest.setSSEAlgorithm(SSEAlgorithm::KMS);
    /* Set server-side encryption using KMS. */
    auto outcome = client.SetBucketEncryption(setrequest);

    if (!outcome.isSuccess()) {
        /* Handle exceptions. */
        std::cout << "SetBucketEncryption fail" <<
        ",code:" << outcome.error().Code() <<
        ",message:" << outcome.error().Message() <<
        ",requestId:" << outcome.error().RequestId() << std::endl;
        return -1;
    }

    /* Release network and other resources. */
    ShutdownSdk();
    return 0;
}

Método 2: Establecer el cifrado del lado del servidor al cargar un objeto

A continuación se muestran ejemplos de código para establecer el cifrado del lado del servidor al cargar un objeto con los SDK más comunes. Para conocer cómo hacerlo con otros SDK, consulte Introduction to Alibaba Cloud SDKs.

Java

import com.aliyun.oss.*;
import com.aliyun.oss.common.auth.*;
import com.aliyun.oss.common.comm.SignVersion;
import com.aliyun.oss.internal.OSSHeaders;
import com.aliyun.oss.model.PutObjectRequest;
import com.aliyun.oss.model.PutObjectResult;
import com.aliyun.oss.model.ObjectMetadata;
import java.io.File;

public class Put {
    public static void main(String[] args) throws Exception {
        // Take the China (Hangzhou) region as an example. Specify the actual region.
        String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
        // Specify the region that corresponds to the endpoint. Example: cn-hangzhou.
        String region = "cn-hangzhou";
        // 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.
        EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
        // Specify the bucket name. Example: examplebucket.
        String bucketName = "examplebucket";
        // Specify the full path of the object. The full path cannot contain the bucket name. Example: exampledir/exampleobject.txt.
        String objectName = "exampledir/exampleobject.txt";
        // Specify the full path of the local file. Example: D:\\localpath\\examplefile.txt.
        // If you do not specify the full path of the local file, the file is uploaded from the local path that corresponds to the project.
        String filePath= "D:\\localpath\\examplefile.txt";
        
        // Create an OSSClient instance.
        // When the OSSClient instance is no longer used, call the shutdown method to release resources.
        ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
        // Explicitly declare the use of the V4 signature algorithm.
        clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);
        OSS ossClient = OSSClientBuilder.create()
                .endpoint(endpoint)
                .credentialsProvider(credentialsProvider)
                .clientConfiguration(clientBuilderConfiguration)
                .region(region)
                .build();
                
        try {
            // Create an ObjectMetadata instance and set the server-side encryption method to AES256.
            ObjectMetadata metadata = new ObjectMetadata();
            metadata.setHeader(OSSHeaders.OSS_SERVER_SIDE_ENCRYPTION, "AES256");

            // Create a PutObjectRequest instance.
            PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, objectName, new File(filePath));
            putObjectRequest.setMetadata(metadata); 

            // Upload the file.
            PutObjectResult result = ossClient.putObject(putObjectRequest);
        } catch (OSSException oe) {
            System.out.println("Caught an OSSException, which means your request made it to OSS, "
                    + "but was rejected with an error response for some reason.");
            System.out.println("Error Message:" + oe.getErrorMessage());
            System.out.println("Error Code:" + oe.getErrorCode());
            System.out.println("Request ID:" + oe.getRequestId());
            System.out.println("Host ID:" + oe.getHostId());
        } catch (ClientException ce) {
            System.out.println("Caught an ClientException, which means the client encountered "
                    + "a serious internal problem while trying to communicate with OSS, "
                    + "such as not being able to access the network.");
            System.out.println("Error Message:" + ce.getMessage());
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }
}

PHP

<?php
if (is_file(__DIR__ . '/../autoload.php')) {
    require_once __DIR__ . '/../autoload.php';
}
if (is_file(__DIR__ . '/../vendor/autoload.php')) {
    require_once __DIR__ . '/../vendor/autoload.php';
}

use OSS\Credentials\EnvironmentVariableCredentialsProvider;
use OSS\OssClient;
use OSS\Core\OssException;

// 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 = new EnvironmentVariableCredentialsProvider();
// Set yourEndpoint to the endpoint of the region in which the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com.
$endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
// Specify the bucket name. Example: examplebucket.
$bucket= "examplebucket";
// Specify the full path of the object. The full path cannot contain the bucket name. Example: exampledir/exampleobject.txt.
$object = "exampledir/exampleobject.txt";
// Specify the full path of the local file. Example: D:\\localpath\\examplefile.txt. If you do not specify the full path of the local file, the file is uploaded from the local path that corresponds to the project.
$filePath = "D:\\localpath\\examplefile.txt";

try{
    $config = array(
        "provider" => $provider,
        "endpoint" => $endpoint,
    );
    $ossClient = new OssClient($config);

    $options[OssClient::OSS_HEADERS] = array(
         // Set the server-side encryption method to AES256.
        "x-oss-server-side-encryption"=>"AES256",
    );
    // Call the uploadFile method to upload the file and pass the UploadOptions object.
    $ossClient->uploadFile($bucket, $object, $filePath, $options);
} catch(OssException $e) {
    printf(__FUNCTION__ . ": FAILED\n");
    printf($e->getMessage() . "\n");
    return;
}
print(__FUNCTION__ . "OK" . "\n");

Node.js

const OSS = require("ali-oss");
const path = require("path");

const client = new OSS({
  // Set yourregion to the region in which the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the region to oss-cn-hangzhou.
  region: "oss-cn-hangzhou",
  // 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.
  accessKeyId: process.env.OSS_ACCESS_KEY_ID,
  accessKeySecret: process.env.OSS_ACCESS_KEY_SECRET,
  // Specify the bucket name.
  bucket: "examplebucket",
});

const headers = {
  // Set the server-side encryption method to AES256.
  "x-oss-server-side-encryption": "AES256",
};

async function put() {
  try {
    const result = await client.put(
      // Specify the full path of the object. The full path cannot contain the bucket name. Example: exampledir/exampleobject.txt.
      "exampledir/exampleobject.txt",
      // Specify the full path of the local file. Example: D:\\localpath\\examplefile.txt. If you do not specify the full path of the local file, the file is uploaded from the local path that corresponds to the project.
      path.normalize("D:\\examplefile.jpg"),
      { headers }
    );
    console.log(result);
  } catch (e) {
    console.log(e);
  }
}

put();

Python

# -*- coding: utf-8 -*-
import oss2
import os
from oss2.credentials import EnvironmentVariableCredentialsProvider

# 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.
auth = oss2.ProviderAuth(EnvironmentVariableCredentialsProvider())

# Set yourEndpoint to the endpoint of the region in which the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com.
endpoint = 'https://oss-cn-hangzhou.aliyuncs.com'

# Specify the bucket name.
bucket_name = 'examplebucket0703'
bucket = oss2.Bucket(auth, endpoint, bucket_name)

# The file must be opened in binary mode.
# Specify the full path of the local file. If you do not specify the full path of the local file, the file is uploaded from the local path that corresponds to the project.
local_file_path = 'D:\\examplefile.jpg'
with open(local_file_path, 'rb') as fileobj:
    # The seek method specifies that the read and write operations start from the 1,000th byte. When you upload a file, the upload starts from the 1,000th byte and continues until the end of the file.
    fileobj.seek(1000, os.SEEK_SET)
    # The tell method returns the current position.
    current = fileobj.tell()

    # Set the server-side encryption method to AES256.
    headers = {
        'x-oss-server-side-encryption': 'AES256',
    }

    # Specify the full path of the object. The full path cannot contain the bucket name.
    object_key = 'exampledir/object1.jpg'
    bucket.put_object(object_key, fileobj, headers=headers)

Go

package main

import (
	"fmt"
	"github.com/aliyun/aliyun-oss-go-sdk/oss"
	"os"
)

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 {
		fmt.Println("Error:", err)
		os.Exit(-1)
	}

	// Create an OSSClient instance.
	// Set yourEndpoint to the endpoint of the bucket. For example, if the bucket is in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. Specify the actual region.
	client, err := oss.New("https://oss-cn-hangzhou.aliyuncs.com", "", "", oss.SetCredentialsProvider(&provider))
	if err != nil {
		fmt.Println("Error:", err)
		os.Exit(-1)
	}

	// Specify the bucket name. Example: examplebucket.
	bucket, err := client.Bucket("examplebucket")
	if err != nil {
		fmt.Println("Error:", err)
		os.Exit(-1)
	}
  // Specify the full path of the object. The full path cannot contain the bucket name. Example: exampledir/exampleobject.txt.
  // Specify the full path of the local file. Example: D:\\localpath\\examplefile.txt. If you do not specify the full path of the local file, the file is uploaded from the local path that corresponds to the project.
  // Set the server-side encryption method to AES256.
	err = bucket.PutObjectFromFile("D:\\localpath\\examplefile.txt", "D:\\examplefile.jpg", oss.ServerSideEncryption("AES256"))
	if err != nil {
		fmt.Println("Error:", err)
		os.Exit(-1)
	}
}

Uso de la herramienta de línea de comandos ossutil

Método 1: Habilitar el cifrado del lado del servidor para un bucket

La herramienta de línea de comandos ossutil permite habilitar el cifrado del lado del servidor para un bucket. Para instalar ossutil, consulte Install ossutil.

El siguiente ejemplo muestra cómo establecer el método de cifrado del lado del servidor en AES256 para un bucket existente llamado examplebucket.

ossutil api put-bucket-encryption --bucket examplebucket --server-side-encryption-rule "{\"ApplyServerSideEncryptionByDefault\":{\"SSEAlgorithm\":\"AES256\"}}"

Para obtener más información sobre este comando, consulte put-bucket-encryption.

Método 2: Establecer el cifrado del lado del servidor al cargar un objeto

ossutil le permite especificar el método de cifrado del lado del servidor de un objeto durante su carga. Para instalar ossutil, consulte Install ossutil. El siguiente ejemplo muestra cómo establecer el método de cifrado del lado del servidor en AES256 al cargar un objeto.

ossutil cp examplefile.txt oss://examplebucket --metadata=x-oss-server-side-encryption:AES256

Para obtener más información sobre este comando, consulte cp (upload objects).

Uso de claves administradas por KMS para cifrar y descifrar

Puede utilizar una clave maestra de cliente (CMK) administrada por KMS para generar una clave de cifrado de datos y proteger su información. El cifrado de sobre añade una capa de seguridad adicional que evita el acceso no autorizado a los datos. KMS le permite concentrarse en funciones de negocio como el cifrado, el descifrado y la verificación de firmas electrónicas, sin necesidad de invertir grandes esfuerzos en garantizar la confidencialidad, integridad y disponibilidad de sus claves.

La siguiente figura muestra la lógica del cifrado SSE-KMS.

image

Al usar SSE-KMS, puede trabajar con los siguientes tipos de claves:

  • Usar la clave predeterminada de KMS administrada por OSS

    OSS emplea la CMK predeterminada de KMS para generar claves distintas que cifran diferentes objetos, y los descifra automáticamente cuando se descargan. La primera vez que utiliza esta función, OSS crea una CMK administrada por OSS en KMS.

    Métodos de configuración:

    • Configurar el método de cifrado de un bucket

      Establezca el método de cifrado del bucket como KMS , pero no indique ningún identificador de CMK. De este modo, todos los objetos que se carguen en el bucket se cifrarán de forma predeterminada.

    • Configurar el método de cifrado de un objeto de destino

      Cuando cargue un objeto o modifique sus metadatos, incluya el parámetro x-oss-server-side-encryption en la solicitud y establézcalo en KMS. OSS usará entonces la CMK predeterminada de KMS y el algoritmo AES256 para cifrar el objeto. Para obtener más información, consulte PutObject.

  • Usar Bring-Your-Own-Key (BYOK)

    Después de generar una CMK en la consola de KMS con material BYOK, OSS puede usar esa CMK específica para generar claves distintas que cifren diferentes objetos. El identificador de la CMK se almacena en los metadatos del objeto cifrado. Este se descifra automáticamente solo cuando lo descarga un usuario con permisos de descifrado.

    El material BYOK puede provenir de dos fuentes:

    • Material BYOK proporcionado por Alibaba Cloud: Al crear una clave en la consola de KMS, seleccione KMS como origen del material de la clave.

    • Su propio material BYOK: Al crear una clave en la consola de KMS, seleccione External como origen del material de la clave e importe el material externo según sea necesario. Para obtener más información sobre cómo importar material de clave externo, consulte Import key material.

    Métodos de configuración:

    • Configurar el método de cifrado de un bucket

      Establezca el método de cifrado del bucket como KMS e indique un identificador de CMK. Así, todos los objetos que se carguen en el bucket se cifrarán de forma predeterminada.

    • Configurar el método de cifrado del objeto de destino

      Cuando cargue un objeto o modifique sus metadatos, establezca el parámetro x-oss-server-side-encryption en KMS y el parámetro x-oss-server-side-encryption-key-id con el identificador de la CMK especificada. OSS usará dicha CMK de KMS y el algoritmo AES256 para cifrar el objeto. Para obtener más información, consulte PutObject.

Uso de claves administradas por OSS para el cifrado y descifrado

OSS genera y administra las claves de cifrado de datos. Además, las protege con medidas de seguridad multifactor de alta resistencia. Los datos se cifran mediante los algoritmos estándar de la industria Advanced Encryption Standard (AES) 256 .

Métodos de configuración:

  • Configure el método de cifrado de un bucket

    Establezca SSE-OSS como método de cifrado del bucket y especifique AES256 como algoritmo de cifrado. De este modo, todos los objetos que se carguen en este bucket se cifrarán de forma predeterminada.

  • Configure el método de cifrado de un objeto de destino

    Cuando cargue un objeto o modifique sus metadatos, incluya el parámetro x-oss-server-side-encryption en la solicitud y establezca su valor en AES256. A continuación, OSS utiliza una clave administrada por OSS para cifrar el objeto. Para obtener más información, consulte PutObject.

Operaciones de API relacionadas

Las operaciones anteriores se implementan a partir de operaciones de API. Si su aplicación tiene requisitos de personalización avanzados, envíe directamente solicitudes de API REST. Para ello, debe escribir manualmente el código que calcula las firmas. Para obtener más información, consulte PutBucketEncryption.

Preguntas frecuentes

Después de configurar un método de cifrado para un bucket, ¿OSS cifra los objetos existentes?

OSS cifra únicamente los objetos que se cargan después de habilitar la configuración de cifrado del lado del servidor. Los objetos existentes no se cifran. Para cifrarlos, sobrescríbalos mediante la operación CopyObject.