Todos os produtos
Search
Central de documentação

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

Última atualização: Sep 22, 2026

O Object Storage Service (OSS) pode criptografar os dados enviados diretamente no servidor, recurso conhecido como criptografia no lado do servidor. Ao fazer upload de dados para o OSS, o serviço criptografa o conteúdo e o armazena de forma persistente em formato criptografado. Durante o download, o OSS descriptografa os dados e retorna o conteúdo original. Além disso, um cabeçalho é adicionado à resposta para indicar que a criptografia ocorreu no servidor.

Observações

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

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

  • As credenciais de acesso neste exemplo são obtidas por meio de variáveis de ambiente. Para saber como configurar essas credenciais, consulte Configure access credentials using OSS SDK for Python 1.0.

  • Este tópico demonstra a criação de uma instância OSSClient com um endpoint do OSS. Para outras configurações, como uso de domínio personalizado ou autenticação via Security Token Service (STS), consulte Initialization.

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

Configurar a criptografia no lado do servidor para um bucket

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

# -*- coding: utf-8 -*-
import oss2
from oss2.credentials import EnvironmentVariableCredentialsProvider
from oss2.models import ServerSideEncryptionRule
# Obtain access credentials from the environment variables. Before you run the sample code, make sure that you have configured environment variables OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET. 
auth = oss2.ProviderAuthV4(EnvironmentVariableCredentialsProvider())

# 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. 
endpoint = "https://oss-cn-hangzhou.aliyuncs.com"
# Specify the ID of the region that maps to the endpoint. Example: cn-hangzhou. This parameter is required if you use the signature algorithm V4.
region = "cn-hangzhou"

# Specify the name of the bucket.
bucket = oss2.Bucket(auth, endpoint, "examplebucket", region=region)

# Create encryption configurations for the bucket. In this example, AES-256 encryption is used. 
rule = ServerSideEncryptionRule()
rule.sse_algorithm = oss2.SERVER_SIDE_ENCRYPTION_AES256
# Specify the CMK ID. The CMK ID can be specified only if you use the OSS-KMS encryption method. If you want to use a specified CMK for encryption, enter the CMK ID. If you want to use the default CMK managed by KMS for encryption, leave this parameter empty. If you use AES-256 encryption, you must leave this parameter empty. 
rule.kms_master_keyid = ""

# Apply the encryption configurations to the bucket. 
result = bucket.put_bucket_encryption(rule)

# Display the returned HTTP status code. 
print('http response code:', result.status)

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

O exemplo abaixo ilustra como obter as configurações atuais de criptografia no lado do servidor de um bucket:

# -*- coding: utf-8 -*-
import oss2
from oss2.credentials import EnvironmentVariableCredentialsProvider
# Obtain access credentials from the environment variables. Before you run the sample code, make sure that you have configured environment variables OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET. 
auth = oss2.ProviderAuthV4(EnvironmentVariableCredentialsProvider())

# 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. 
endpoint = "https://oss-cn-hangzhou.aliyuncs.com"
# Specify the ID of the region that maps to the endpoint. Example: cn-hangzhou. This parameter is required if you use the signature algorithm V4.
region = "cn-hangzhou"

# Specify the name of the bucket.
bucket = oss2.Bucket(auth, endpoint, "examplebucket", region=region)

# Query the server-side encryption configurations of the bucket. 
result = bucket.get_bucket_encryption()
# Display the obtained server-side encryption configurations. 
print('sse_algorithm:', result.sse_algorithm)
print('kms_master_keyid:', result.kms_master_keyid) # If the encryption method is AES256, set kms_master_keyid to None.

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

Utilize o código a seguir para remover as configurações de criptografia no lado do servidor de um bucket:

# -*- coding: utf-8 -*-
import oss2
from oss2.credentials import EnvironmentVariableCredentialsProvider
# Obtain access credentials from the environment variables. Before you run the sample code, make sure that you have configured environment variables OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET. 
auth = oss2.ProviderAuthV4(EnvironmentVariableCredentialsProvider())

# 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. 
endpoint = "https://oss-cn-hangzhou.aliyuncs.com"
# Specify the ID of the region that maps to the endpoint. Example: cn-hangzhou. This parameter is required if you use the signature algorithm V4.
region = "cn-hangzhou"

# Specify the name of the bucket.
bucket = oss2.Bucket(auth, endpoint, "examplebucket", region=region)

# Delete the server-side encryption configurations of the bucket. 
result = bucket.delete_bucket_encryption()
# Display the returned HTTP status code. 
print('http status:', result.status)

Referências

  • Acesse o código completo de exemplo sobre criptografia no lado do servidor no GitHub.

  • Para detalhes sobre a operação de API destinada a configurar a criptografia no lado do servidor, consulte PutBucketEncryption.

  • Saiba mais sobre a operação de API para consulta das configurações de criptografia no lado do servidor em GetBucketEncryption.

  • Informações adicionais sobre a operação de API para exclusão das configurações de criptografia no lado do servidor estão disponíveis em DeleteBucketEncryption.