Todos os produtos
Search
Central de documentação

Object Storage Service:Server-side encryption

Última atualização: Sep 12, 2026

Ao fazer upload de um objeto para um bucket com criptografia no lado do servidor ativada, o Object Storage Service (OSS) criptografa o objeto antes de armazená-lo. Ao baixar o objeto usando uma solicitação GetObject, o OSS descriptografa automaticamente o objeto e o retorna. O cabeçalho x-oss-server-side-encryption na resposta indica que o objeto foi criptografado no lado do servidor.

Nota

Para obter mais informações sobre o cabeçalho de resposta x-oss-server-side-encryption, consulte GetObject.

Cenários

O OSS oferece proteção de dados em repouso por meio da criptografia no lado do servidor. Esse recurso é ideal para aplicações com altos requisitos de segurança ou conformidade no armazenamento de dados, como o armazenamento de arquivos de amostra para deep learning ou dados de documentos colaborativos online.

Métodos de criptografia

O OSS disponibiliza dois métodos de criptografia no lado do servidor para diferentes cenários. Selecione o método mais adequado às suas necessidades.

Método de criptografia

Descrição

Cenários

Observações

Faturamento

Criptografar e descriptografar dados usando chaves gerenciadas pelo Key Management Service (KMS) (SSE-KMS)

Use a chave mestra do cliente (CMK) padrão gerenciada pelo KMS ou uma CMK específica para criptografar e descriptografar dados. A criptografia e a descriptografia ocorrem sem envio dos dados pela rede ao servidor do KMS.

Indicado para cenários que exigem chaves autogerenciadas, especificadas para fins de segurança e conformidade.

  • A chave usada para criptografar um objeto também é criptografada e armazenada nos metadados do objeto.

  • O método SSE-KMS criptografa apenas os dados do objeto, mas não seus metadados.

  • A chave do KMS criada por padrão no console do OSS é gratuita.

  • Se você usar sua própria chave do KMS, haverá cobrança de taxas no KMS. Para obter mais informações, consulte KMS pricing.

Criptografar e descriptografar dados usando chaves gerenciadas pelo OSS (SSE-OSS)

Use uma chave totalmente gerenciada pelo OSS para criptografar cada objeto. Para maior segurança, o OSS também usa uma chave mestra para criptografar a própria chave de criptografia de dados.

Recomendado quando você precisa apenas de criptografia básica e não deseja gerenciar chaves.

Nenhuma.

Gratuito.

Observações

  • Ao fazer upload, download ou acessar objetos em um bucket com criptografia SSE-KMS ativada, verifique se você tem permissões para usar o ID da CMK especificado e se a solicitação não é anônima. Caso contrário, a solicitação falhará e o erro This request is forbidden by kms será retornado.

  • Objetos espelhados em um bucket usando back-to-origin baseado em espelhamento não são criptografados por padrão.

  • Ativar ou modificar o método de criptografia de um bucket não afeta a configuração de criptografia dos objetos existentes nele.

  • Apenas um método de criptografia no lado do servidor pode ser usado por objeto de cada vez.

  • Mesmo após configurar a criptografia para um bucket, você ainda pode especificar um método diferente para um objeto individual ao fazer upload ou copiá-lo. O método especificado para o objeto prevalece. Para obter mais informações, consulte PutObject.

Permissões

A lista a seguir descreve as permissões necessárias para que um usuário do Resource Access Management (RAM) utilize a criptografia no lado do servidor em diferentes cenários.

Nota

Para obter mais informações sobre como conceder permissões a um usuário RAM, consulte Grant custom permissions to a RAM user.

  • Configure o método de criptografia para um bucket

    • Permissões de gerenciamento no bucket de destino.

    • As permissões PutBucketEncryption e GetBucketEncryption.

    • Se você definir o método de criptografia como SSE-KMS e especificar um ID de CMK, as permissões ListKeys, ListAliases, ListAliasesByKeyId e DescribeKey também serão necessárias. Veja abaixo um exemplo de política do RAM para este cenário:

      {
        "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.
            ]
          }
        ]
      }
  • Fazer upload de um objeto para um bucket criptografado

    • Permissões para fazer upload de objetos no bucket de destino.

    • Caso o método de criptografia esteja definido como KMS e um ID de CMK seja especificado, as permissões ListKeys, ListAliases, ListAliasesByKeyId, DescribeKey, GenerateDataKey e Decrypt também são obrigatórias. Abaixo está um exemplo de política do RAM para esta situação:

      {
        "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.
            ]
          }
        ]
      }
  • Baixe um objeto de um bucket criptografado

    • Permissões para acessar objetos no bucket de destino.

    • Quando o método de criptografia for KMS e houver um ID de CMK especificado, a permissão Decrypt também é necessária. O exemplo a seguir mostra uma política do RAM aplicável a este caso:

      {
        "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.
            ]
          }
        ]
      }

Procedimentos

Importante
  • Se você adquirir o service de valor agregado de rotação de chaves para o KMS, a criptografia no lado do servidor suportará key rotation para chaves do KMS. Após ative a rotação de chaves, a nova chave será usada para criptografar apenas objetos recém-carregados. As chaves de criptografia dos objetos existentes permanecem inalteradas.

  • Ao atualize a chave de criptografia do KMS no OSS, a nova chave criptografa somente os novos uploads. Os objetos carregados antes da atualização continuam criptografados com a chave antiga. Portanto, não exclua a chave antiga após a atualização, pois isso impedirá o acesso aos objetos existentes.

Usar o console do OSS

Método 1: Ative a criptografia no lado do servidor para um bucket

Ative a criptografia no lado do servidor ao crie um bucket

  1. Faça login no console do OSS.

  2. Clique em Buckets e, em seguida, clique em Create Bucket.

  3. No painel Create Bucket, configure os parâmetros a seguir.

    Os parâmetros abaixo servem para configure a criptografia no lado do servidor em uma região:

    Parâmetro

    Descrição

    Encryption Method

    Selecione um método de criptografia para os objetos. Valores válidos:

    • None: A criptografia no lado do servidor está desativada.

    • SSE-OSS: Usa chaves gerenciadas pelo OSS para criptografia. O OSS utiliza uma chave diferente para criptografar cada objeto. Para proteção adicional, o OSS usa uma chave mestra para criptografar a própria chave de criptografia de dados.

    • SSE-KMS: Utiliza a CMK padrão gerenciada pelo KMS ou uma CMK específica para criptografia e descriptografia.

      Antes de usar o SSE-KMS, é necessário ative o KMS. Para mais detalhes, consulte Purchase a dedicated KMS instance.

    Encryption Algorithm

    Suporta apenas o algoritmo de criptografia AES256.

    CMK

    Esta opção precisa ser configurada apenas quando você selecione KMS para criptografia no lado do servidor.

    Selecione uma chave de criptografia. A chave segue o formato <alias>(CMK ID). <alias> é o alias da CMK, e CMK ID é o identificador da CMK. Valores válidos:

    • alias/acs/oss(CMK ID): Ao escolher esta opção, o OSS usa a chave de service padrão para criptografar os dados no bucket e descriptografa automaticamente os dados quando você baixe objetos do bucket.

    • alias/<cmkname>(CMK ID): Nesta opção, o OSS utiliza a chave de service especificada para criptografar os dados no bucket e registra o ID da CMK nos metadados do objeto criptografado. Quando um usuário com permissões de descriptografia baixe o objeto, ele é descriptografado automaticamente. <cmkname> é um alias opcional para a CMK que você defina ao crie a chave.

      Antes de usar um ID de CMK específico, crie uma chave padrão ou externa na mesma região do bucket no console do KMS. Para mais informações, consulte Create a CMK.

    Para obter mais informações sobre outros parâmetros, consulte Create a bucket.

  4. Clique em OK.

Ative a criptografia no lado do servidor para um bucket existente

  1. Faça login no console do OSS.

  2. No painel de navegação à esquerda, clique em Buckets. Na página Buckets, localize e clique no bucket desejado.

  3. No painel de navegação à esquerda, escolha Content Security > Server-side Encryption.

  4. Na página Server-side Encryption, clique em Configure e defina os parâmetros.

    Parâmetro

    Descrição

    Encryption Method

    Escolha um método de criptografia para os objetos. Valores válidos:

    • None: A criptografia no lado do servidor está desativada.

    • SSE-OSS: Utiliza chaves gerenciadas pelo OSS para criptografia. O OSS emprega uma chave distinta para cada objeto. Como proteção extra, o OSS usa uma chave mestra para criptografar a própria chave de criptografia de dados.

    • SSE-KMS: Emprega a CMK padrão gerenciada pelo KMS ou uma CMK específica para criptografia e descriptografia.

      É necessário ative o KMS antes de usar o SSE-KMS. Para mais detalhes, consulte Purchase a dedicated KMS instance.

    Encryption Algorithm

    Somente o algoritmo de criptografia AES256 é suportado.

    CMK

    Este parâmetro é obrigatório apenas quando você defina o Encryption Method como SSE-KMS.

    Escolha uma chave de criptografia. A chave possui o formato <alias>(CMK ID). <alias> representa o alias da CMK, e CMK ID é o identificador da CMK. Valores válidos:

    • Default Service Key: Se selecionada, o OSS gera uma chave de service padrão para criptografar os dados no bucket e descriptografa automaticamente os dados durante o download dos objetos. A chave de service padrão criada pelo OSS segue o formato alias/acs/oss (CMK ID). É possível visualize essa chave no console do KMS.

      Nota

      Para visualize essa chave de service no console do KMS, faça upload de pelo menos um objeto no bucket de destino, garantindo assim que a chave de criptografia correspondente seja criada e associada ao seu service OSS.

    • alias/<cmkname>(CMK ID): Nesta opção, o OSS usa a chave de service especificada para criptografar os dados no bucket e grava o ID da CMK nos metadados do objeto criptografado. O objeto é descriptografado automaticamente quando baixado por um usuário com permissões adequadas. <cmkname> é um alias opcional para a CMK definida durante a criação da chave.

      Antes de utilizar um ID de CMK específico, crie uma chave padrão ou externa na mesma região do bucket através do console do KMS. Para mais informações, consulte Create a CMK.

  5. Clique em Save.

Método 2: Defina a criptografia no lado do servidor ao fazer upload de um objeto

Para obter mais informações, consulte Simple upload.

Usar SDKs da Alibaba Cloud

Método 1: Ative a criptografia no lado do servidor para um bucket

Os SDKs permitem ative a criptografia no lado do servidor para buckets existentes. Não é possível ative a criptografia no lado do servidor durante a criação de um bucket via sdk. Os códigos abaixo mostram exemplos de como ative a criptografia no lado do servidor para um bucket existente usando SDKs comuns. Para saber como fazer isso com outros SDKs, 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: Defina a criptografia no lado do servidor ao fazer upload de um objeto

Os exemplos de código a seguir demonstram como defina a criptografia no lado do servidor durante o upload de um objeto utilizando SDKs comuns. Para instruções sobre outros SDKs, 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)
	}
}

Usar a ferramenta de linha de comando ossutil

Método 1: Ative a criptografia no lado do servidor para um bucket

Utilize a ferramenta de linha de comando ossutil para ative a criptografia no lado do servidor em um bucket. Para instale o ossutil, consulte Install ossutil.

O exemplo a seguir demonstra como defina o método de criptografia no lado do servidor como AES256 para um bucket existente chamado examplebucket.

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

Para mais detalhes sobre este comando, consulte put-bucket-encryption.

Método 2: Defina a criptografia no lado do servidor ao fazer upload de um objeto

O ossutil permite especifique o método de criptografia no lado do servidor para um objeto durante o upload. Para instale o ossutil, consulte Install ossutil. O exemplo abaixo ilustra como defina o método de criptografia no lado do servidor como AES256 ao carregar um objeto.

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

Para mais informações sobre este comando, consulte cp (upload objects).

Usar chaves gerenciadas pelo KMS para criptografia e descriptografia

É possível utilizar uma chave mestra do cliente (CMK) gerenciada pelo KMS para gerar uma chave de criptografia de dados. A criptografia de envelope adiciona uma camada extra de segurança para impedir acessos não autorizados aos dados. Com o KMS, você foca nas funcionalidades do negócio, como criptografia, descriptografia e verificação de assinaturas digitais, sem precisar investir pesadamente na garantia de confidencialidade, integridade e disponibilidade das suas chaves.

A figura a seguir ilustra a lógica da criptografia SSE-KMS.

image

Ao utilizar o SSE-KMS, você pode optar pelos seguintes tipos de chave:

  • Usar a chave padrão do KMS gerenciada pelo OSS

    O OSS utiliza a CMK padrão do KMS para gerar chaves distintas e criptografar diferentes objetos, descriptografando-os automaticamente durante o download. Na primeira utilização deste recurso, o OSS crie uma CMK gerenciada pelo OSS no KMS.

    Métodos de configuração:

    • Configure o método de criptografia para um bucket

      Defina o método de criptografia do bucket como KMS , mas não insira um ID de CMK. Assim, todos os objetos enviados para este bucket serão criptografados por padrão.

    • Configure o método de criptografia para um objeto de destino

      Ao fazer upload de um objeto ou modifique seus metadados, inclua o parâmetro x-oss-server-side-encryption na solicitação e defina seu valor como KMS. O OSS então usará a CMK padrão do KMS e o algoritmo de criptografia AES256 para criptografar o objeto. Para mais informações, consulte PutObject.

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

    Após gerar uma CMK no console do KMS usando material BYOK, o OSS pode usar a CMK do KMS especificada para gerar chaves diferentes e criptografar objetos distintos. O ID da CMK fica armazenado nos metadados do objeto criptografado. A descriptografia automática ocorre apenas quando um usuário com as devidas permissões baixe o objeto.

    O material BYOK pode ter duas origens:

    • Material BYOK fornecido pela Alibaba Cloud: Ao crie uma chave no console do KMS, selecione KMS como source do material da chave.

    • Seu próprio material BYOK: Ao crie uma chave no console do KMS, selecione External como source do material da chave e importe o material externo conforme necessário. Para saber como importar material de chave externa, consulte Import key material.

    Métodos de configuração:

    • Configure o método de criptografia para um bucket

      Defina o método de criptografia do bucket como KMS e insira um ID de CMK. Dessa forma, todos os objetos carregados neste bucket serão criptografados por padrão.

    • Configure o método de criptografia do objeto de destino

      Ao fazer upload de um objeto ou modifique seus metadados, defina o parâmetro x-oss-server-side-encryption como KMS e o parâmetro x-oss-server-side-encryption-key-id com o ID da CMK especificada. O OSS usará a CMK do KMS indicada e o algoritmo de criptografia AES256 para criptografar o objeto. Para mais informações, consulte PutObject.

Usar chaves gerenciadas pelo OSS para criptografia e descriptografia

O OSS gera e gerencia chaves de criptografia de dados, protegendo-as com medidas de segurança multifatoriais de alta resistência. Os dados são criptografados usando os algoritmos padrão da indústria Advanced Encryption Standard (AES) 256 .

Métodos de configuração:

  • Configure o método de criptografia para um bucket

    Defina o método de criptografia do bucket como SSE-OSS e especifique o algoritmo de criptografia como AES256 . Consequentemente, todos os objetos enviados para este bucket serão criptografados por padrão.

  • Configure o método de criptografia para um objeto de destino

    Ao fazer upload de um objeto ou modifique seus metadados, inclua o parâmetro x-oss-server-side-encryption na solicitação e defina seu valor como AES256. O OSS usará então uma chave gerenciada pelo OSS para criptografar o objeto. Para mais informações, consulte PutObject.

Operações de api relacionadas

As operações descritas acima são implementadas com base em operações de api. Se sua aplicação tiver requisitos de personalização elevados, inicie solicitações de api REST diretamente. Para isso, escreva manualmente o código para calcular as assinaturas. Para mais informações, consulte PutBucketEncryption.

Perguntas frequentes

Depois de configure um método de criptografia para um bucket, o OSS criptografa os objetos existentes?

O OSS criptografa apenas os objetos carregados após a ativação da configuração de criptografia no lado do servidor. Objetos já existentes não são criptografados retroativamente. Para criptografar objetos existentes, sobrescreva-os utilizando a operação CopyObject.