Todos os produtos
Search
Central de documentação

Object Storage Service:Criptografia no lado do servidor (Python SDK V2)

Última atualização: Jul 03, 2026

O OSS criptografa os dados no lado do servidor durante o upload e os descriptografa automaticamente no baixe. O cabeçalho de resposta HTTP indica a aplicação da criptografia no lado do servidor.

Observações

  • Antes de configure a criptografia no lado do servidor, certifique-se de compreender esse recurso. Para mais informações, consulte Criptografia no lado do servidor.

  • O código de exemplo neste tópico usa o ID da região China (Hangzhou) cn-hangzhou e um endpoint público. Para acessar o OSS a partir de outros serviços da Alibaba Cloud na mesma região, use um endpoint interno. Para mais informações sobre regiões e endpoints compatíveis, consulte Regiões e endpoints.

  • Neste tópico, as credenciais de acesso são obtidas de variáveis de ambiente. Para mais detalhes, consulte Configurar credenciais de acesso.

  • Para configure a criptografia do bucket, você precisa da permissão oss:PutBucketEncryption. Para obter a configuração de criptografia do bucket, você precisa da permissão oss:GetBucketEncryption. Para exclua a configuração de criptografia do bucket, você precisa da permissão oss:DeleteBucketEncryption. Para mais informações, consulte Conceder permissões personalizadas a um usuário RAM.

Código de exemplo

Configure bucket encryption

O código abaixo defina o método de criptografia padrão para um bucket. Após essa configuração, os objetos enviados sem um método de criptografia específico serão criptografados com este método padrão.

import argparse
import alibabacloud_oss_v2 as oss

# Create a command-line argument parser to receive user-entered parameters.
parser = argparse.ArgumentParser(description="put bucket encryption sample")

# Add the --region command-line argument, which specifies the region where the bucket is located. This argument is required.
parser.add_argument('--region', help='The region in which the bucket is located.', required=True)

# Add the --bucket command-line argument, which specifies the name of the bucket. This argument is required.
parser.add_argument('--bucket', help='The name of the bucket.', required=True)

# Add the --endpoint command-line argument, which specifies the domain names that other services can use to access OSS. This argument is optional.
parser.add_argument('--endpoint', help='The domain names that other services can use to access OSS')

# Add the --sse_algorithm command-line argument, which specifies the default server-side encryption method. The default value is 'KMS'.
# Valid values: KMS (encryption using KMS), AES256 (encryption using AES-256), and SM4 (encryption using the Chinese cryptographic algorithm SM4).
parser.add_argument('--sse_algorithm', help='The default server-side encryption method. Valid values: KMS, AES256, and SM4.', default='KMS')

# Add the --kms_master_key_id command-line argument, which specifies the ID of the master key when SSEAlgorithm is set to KMS and a specified CMK is used for encryption.
# If you do not use a specified CMK, leave this parameter empty.
parser.add_argument('--kms_master_key_id', help='The CMK ID that is specified when SSEAlgorithm is set to KMS and a specified CMK is used for encryption. In other cases, leave this parameter empty.', default='')

# Add the --kms_data_encryption command-line argument, which specifies the algorithm that is used to encrypt objects.
# The default value is 'SM4'. This parameter is valid only when SSEAlgorithm is set to KMS.
parser.add_argument('--kms_data_encryption', help='The algorithm that is used to encrypt objects. If this parameter is not specified, objects are encrypted using AES256. This parameter is valid only when SSEAlgorithm is set to KMS. Valid value: SM4', default='SM4')

def main():
    # Parse command-line arguments.
    args = parser.parse_args()

    # Load credentials (AccessKeyId and AccessKeySecret) from environment variables.
    credentials_provider = oss.credentials.EnvironmentVariableCredentialsProvider()

    # Load the default configurations of the SDK.
    cfg = oss.config.load_default()

    # Set the credential provider.
    cfg.credentials_provider = credentials_provider

    # Set the region where the bucket is located.
    cfg.region = args.region

    # If a custom endpoint is provided, set it in the configuration.
    if args.endpoint is not None:
        cfg.endpoint = args.endpoint

    # Initialize the OSS client using the configuration object.
    client = oss.Client(cfg)

    # Call the put_bucket_encryption method to set the encryption configuration for the bucket.
    result = client.put_bucket_encryption(
        oss.PutBucketEncryptionRequest(
            bucket=args.bucket,  # Specify the name of the destination bucket.
            server_side_encryption_rule=oss.ServerSideEncryptionRule(
                apply_server_side_encryption_by_default=oss.ApplyServerSideEncryptionByDefault(
                    kms_master_key_id=args.kms_master_key_id,  # The master key ID. This parameter is valid only when SSEAlgorithm is set to KMS.
                    kms_data_encryption=args.kms_data_encryption,  # The object encryption algorithm. This parameter is valid only when SSEAlgorithm is set to KMS.
                    sse_algorithm=args.sse_algorithm,  # The server-side encryption algorithm, such as KMS, AES256, or SM4.
                ),
            ),
        )
    )

    # Print the status code and request ID of the operation result.
    print(f'status code: {result.status_code}, '  # The HTTP status code, which indicates whether the request is successful.
          f'request id: {result.request_id}')     # The request ID, which is used to track request logs and for debugging.

if __name__ == "__main__":
    # The program entry point. Call the main function to execute the logic.
    main()

Get bucket encryption configuration

O código a seguir obtém a configuração de criptografia do bucket.

import argparse
import alibabacloud_oss_v2 as oss

# Create a command-line argument parser to receive user-entered parameters.
parser = argparse.ArgumentParser(description="get bucket encryption sample")

# Add the --region command-line argument, which specifies the region where the bucket is located. This argument is required.
parser.add_argument('--region', help='The region in which the bucket is located.', required=True)

# Add the --bucket command-line argument, which specifies the name of the bucket. This argument is required.
parser.add_argument('--bucket', help='The name of the bucket.', required=True)

# Add the --endpoint command-line argument, which specifies the domain names that other services can use to access OSS. This argument is optional.
parser.add_argument('--endpoint', help='The domain names that other services can use to access OSS')

def main():
    # Parse command-line arguments.
    args = parser.parse_args()

    # Load credentials (AccessKeyId and AccessKeySecret) from environment variables.
    credentials_provider = oss.credentials.EnvironmentVariableCredentialsProvider()

    # Load the default configurations of the SDK.
    cfg = oss.config.load_default()

    # Set the credential provider.
    cfg.credentials_provider = credentials_provider

    # Set the region where the bucket is located.
    cfg.region = args.region

    # If a custom endpoint is provided, set it in the configuration.
    if args.endpoint is not None:
        cfg.endpoint = args.endpoint

    # Initialize the OSS client using the configuration object.
    client = oss.Client(cfg)

    # Call the get_bucket_encryption method to obtain the encryption configuration of the bucket.
    result = client.get_bucket_encryption(
        oss.GetBucketEncryptionRequest(
            bucket=args.bucket,  # Specify the name of the destination bucket.
        )
    )

    # Print the status code and request ID of the operation result.
    print(f'status code: {result.status_code}, '
          f'request id: {result.request_id}, '
    )

if __name__ == "__main__":
    # The program entry point. Call the main function to execute the logic.
    main()

Delete bucket encryption configuration

O código a seguir exclua a configuração de criptografia do bucket.

import argparse
import alibabacloud_oss_v2 as oss

# Create a command-line argument parser to receive user-entered parameters.
parser = argparse.ArgumentParser(description="delete bucket encryption sample")

# Add the --region command-line argument, which specifies the region where the bucket is located. This argument is required.
parser.add_argument('--region', help='The region in which the bucket is located.', required=True)

# Add the --bucket command-line argument, which specifies the name of the bucket. This argument is required.
parser.add_argument('--bucket', help='The name of the bucket.', required=True)

# Add the --endpoint command-line argument, which specifies the domain names that other services can use to access OSS. This argument is optional.
parser.add_argument('--endpoint', help='The domain names that other services can use to access OSS')

def main():
    # Parse command-line arguments.
    args = parser.parse_args()

    # Load credentials (AccessKeyId and AccessKeySecret) from environment variables.
    credentials_provider = oss.credentials.EnvironmentVariableCredentialsProvider()

    # Load the default configurations of the SDK.
    cfg = oss.config.load_default()

    # Set the credential provider.
    cfg.credentials_provider = credentials_provider

    # Set the region where the bucket is located.
    cfg.region = args.region

    # If a custom endpoint is provided, set it in the configuration.
    if args.endpoint is not None:
        cfg.endpoint = args.endpoint

    # Initialize the OSS client using the configuration object.
    client = oss.Client(cfg)

    # Call the delete_bucket_encryption method to delete the encryption configuration of the bucket.
    result = client.delete_bucket_encryption(
        oss.DeleteBucketEncryptionRequest(
            bucket=args.bucket,  # Specify the name of the destination bucket.
        )
    )

    # Print the status code and request ID of the operation result.
    print(f'status code: {result.status_code}, '  # The HTTP status code, which indicates whether the request is successful.
          f'request id: {result.request_id}')     # The request ID, which is used to track requests.

if __name__ == "__main__":
    # The program entry point. Call the main function to execute the logic.
    main()

Referências

  • Para configure a criptografia no lado do servidor via api, consulte PutBucketEncryption.

  • Para obter a configuração de criptografia no lado do servidor via api, consulte GetBucketEncryption.

  • Para exclua a configuração de criptografia no lado do servidor via api, consulte DeleteBucketEncryption.