Todos os produtos
Search
Central de documentação

Object Storage Service:Criptografia no lado do cliente (Python SDK V1)

Última atualização: Jul 03, 2026

Com a criptografia no lado do cliente ativada, os objetos são criptografados localmente antes do envio ao Object Storage Service (OSS). Somente o proprietário da chave mestra do cliente (CMK) consegue descriptografar esses objetos. Esse recurso aumenta a segurança dos dados durante a transmissão e o armazenamento.

Aviso legal

  • Ao usar a criptografia no lado do cliente, garanta a integridade e a validade da CMK. Se a CMK for usada incorretamente ou perdida devido a manutenção inadequada, você será responsável por todas as perdas e consequências decorrentes de falhas na descriptografia.

  • Ao copiar ou migrar dados criptografados, garanta a integridade e a validade dos metadados do objeto. Se os metadados criptografados estiverem incorretos ou forem perdidos por manutenção inadequada, você responderá por quaisquer perdas e consequências causadas por falhas na descriptografia dos dados.

Cenários

  • Dados altamente sensíveis: Para informações de identificação pessoal (PII), registros de transações financeiras, dados de saúde e outros conteúdos críticos, recomenda-se criptografar as informações antes que saiam do ambiente local. Isso assegura a proteção eficaz dos dados originais mesmo em caso de interceptação durante a transmissão.

  • Requisitos de conformidade: Normas e regulamentações específicas, como a Health Insurance Portability and Accountability Act (HIPAA) e o General Data Protection Regulation (GDPR), exigem gestão rigorosa de criptografia para dados armazenados em plataformas de terceiros. A criptografia no lado do cliente ajuda a atender a essas exigências, pois as CMKs são gerenciadas pelos usuários, sem transitar pela rede ou ficar expostas aos provedores de serviços em nuvem.

  • Controle total da criptografia: Empresas ou desenvolvedores que desejam gerenciar integralmente o processo de criptografia, incluindo a escolha de algoritmos e o gerenciamento e rodízio de CMKs, podem usar esse recurso. Dessa forma, garante-se que apenas usuários autorizados consigam descriptografar e acessar os dados.

  • Segurança na migração de dados entre regiões: Manter os dados criptografados antes e depois da migração entre regiões reforça a segurança durante o tráfego pela internet.

Observações

  • Este tópico utiliza o endpoint público da região China (Hangzhou). Para 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 Regiões e endpoints.

  • As credenciais de acesso neste exemplo são obtidas de variáveis de ambiente. Para saber como configurar credenciais de acesso, consulte Configurar credenciais de acesso (Python SDK V1).

  • Esta documentação demonstra a criação de uma instância OSSClient com um endpoint do OSS. Para configurações alternativas, como uso de domínio personalizado ou autenticação com credenciais do Security Token Service (STS), consulte Inicialização.

Informações básicas

Na criptografia no lado do cliente, gera-se uma chave de dados aleatória para cada objeto, aplicando criptografia simétrica ao conteúdo. O cliente usa uma CMK para criptografar essa chave aleatória. A chave de dados criptografada é enviada como parte dos metadados do objeto e armazenada no servidor do OSS. Ao baixar um objeto criptografado, o cliente utiliza a CMK para descriptografar a chave de dados aleatória e, em seguida, usa essa chave para descriptografar o objeto. Para garantir a segurança, a CMK é usada exclusivamente no cliente, não sendo transmitida pela rede nem armazenada no servidor.

Métodos de criptografia

Atualmente, a chave mestra pode ser utilizada de duas formas:

  • CMKs gerenciadas pelo KMS

    Para usar uma CMK gerenciada pelo Key Management Service (KMS) na criptografia no lado do cliente, forneça o ID da CMK ao OSS SDK for Python.

  • CMKs baseadas em RSA gerenciadas por você

    Ao optar por uma CMK gerenciada por você mesmo, envie a chave pública e a chave privada da sua CMK como parâmetros para o OSS SDK for Python.

Esses métodos de criptografia previnem vazamentos e protegem seus dados no cliente. Mesmo que ocorra um vazamento, terceiros não conseguirão descriptografar as informações.

Para mais informações, consulte Criptografia no lado do cliente no Guia do Desenvolvedor do OSS.

Criptografia no lado do cliente V2 (recomendada)

Importante
  • A criptografia no lado do cliente suporta upload multipart para objetos maiores que 5 GB. Ao realizar esse tipo de upload, especifique o tamanho total do objeto e o tamanho da parte. Exceto pela última parte, todas devem ter o mesmo tamanho, que deve ser múltiplo de 16 bytes.

  • Objetos criptografados localmente possuem metadados protegidos por criptografia, impedindo modificações via operações como CopyObject.

  • Metadados de objeto relacionados à criptografia no lado do cliente

    Parâmetro

    Descrição

    Obrigatório

    x-oss-meta-client-side-encryption-key

    Chave de dados criptografada. Trata-se de uma string criptografada com uma CMK baseada em RSA ou gerenciada pelo KMS e codificada em Base64.

    Sim

    x-oss-meta-client-side-encryption-start

    Vetor de inicialização gerado aleatoriamente para criptografia dos dados. É uma string criptografada com uma CMK baseada em RSA ou gerenciada pelo KMS e codificada em Base64.

    Sim

    x-oss-meta-client-side-encryption-cek-alg

    Algoritmo utilizado para criptografar os dados.

    Sim

    x-oss-meta-client-side-encryption-wrap-alg

    Algoritmo usado para criptografar a chave de dados.

    Sim

    x-oss-meta-client-side-encryption-matdesc

    Descrição da chave de criptografia de conteúdo (CEK) no formato JSON.

    Não

    x-oss-meta-client-side-encryption-unencrypted-content-length

    Tamanho dos dados antes da criptografia. Este parâmetro não é gerado se content-length não for especificado.

    Não

    x-oss-meta-client-side-encryption-unencrypted-content-md5

    Hash MD5 dos dados antes da criptografia. Este parâmetro não é gerado se content-md5 não for especificado.

    Não

    x-oss-meta-client-side-encryption-data-size

    Tamanho total do objeto a ser enviado via upload multipart.

    Condicional (obrigatório para upload multipart)

    x-oss-meta-client-side-encryption-part-size

    Tamanho da parte definido no upload multipart.

    Condicional (obrigatório para upload multipart)

  • Criar um bucket para criptografia no lado do cliente

    Antes de criptografar e enviar um objeto, ou baixar e descriptografar um objeto no cliente, inicialize uma instância de bucket. As operações de upload e download são executadas por meio dessa instância. Na criptografia no lado do cliente, a classe CryptoBucket herda as operações da classe Bucket. Configure os parâmetros para inicializar uma instância CryptoBucket da mesma forma que faria para uma instância Bucket.

    • Inicializar uma instância CryptoBucket para criptografia de objetos usando uma CMK baseada em RSA gerenciada por você

      Importante

      Se utilizar uma CMK baseada em RSA, você deverá gerenciá-la pessoalmente. A perda ou corrupção dos dados da CMK pode resultar em falhas de descriptografia. Recomendamos o uso de CMKs gerenciadas pelo KMS. Caso precise usar uma CMK baseada em RSA, faça backup dos dados da chave.

      O código abaixo exemplifica como inicializar uma instância CryptoBucket para criptografia de objetos utilizando uma CMK baseada em RSA gerenciada por você:

      # -*- coding: utf-8 -*-
      import os
      import oss2
      from oss2.credentials import EnvironmentVariableCredentialsProvider
      from oss2.crypto import RsaProvider
      
      # 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.ProviderAuthV4(EnvironmentVariableCredentialsProvider())
      
      # If you want to only decrypt objects, specify only the private key. 
      # key_pair = {'private_key': 'yourPrivateKey'}
      # If you want to only encrypt objects, specify only the public key. 
      # key_pair = {'public_key': 'yourPublicKey'}
      # If you want to encrypt and decrypt objects, you must specify both the public key and the private key. 
      key_pair = {'private_key': 'yourPrivateKey', 'public_key': 'yourPublicKey'}
      
      # 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 region in which the bucket is located. Example: cn-hangzhou This parameter is required if you use the V4 signature algorithm.
      region = "cn-hangzhou"
      
      # Specify the name of the bucket. 
      bucket = oss2.CryptoBucket(auth, endpoint, 'yourBucketName',
                                 crypto_provider=RsaProvider(key_pair), region=region)
      
    • Inicializar uma instância CryptoBucket para criptografia de objetos usando uma CMK gerenciada pelo KMS

      O exemplo a seguir mostra como inicializar uma instância CryptoBucket para criptografia de objetos com uma CMK gerenciada pelo KMS:

      # -*- coding: utf-8 -*-
      import os
      import oss2
      from oss2.crypto import AliKMSProvider
      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.ProviderAuthV4(EnvironmentVariableCredentialsProvider())
      kms_provider = AliKMSProvider(auth, 'yourRegion', 'yourCMKID')
      
      # 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 region in which the bucket is located. Example: cn-hangzhou This parameter is required if you use the V4 signature algorithm.
      region = "cn-hangzhou"
      
      # Specify the name of the bucket. 
      bucket = oss2.CryptoBucket(auth, endpoint, 'yourBucketName', crypto_provider=kms_provider, region=region)
      
    • Usar e gerenciar múltiplas CMKs

      É possível utilizar diferentes CMKs para criptografar objetos enviados a um bucket ou descriptografar objetos baixados do mesmo bucket. Defina descrições distintas para as CMKs e adicione-as, junto com suas descrições, às informações de criptografia do bucket. Durante a descriptografia, o OSS SDK for Python identifica automaticamente a CMK correta com base na descrição. O código abaixo ilustra como fornecer múltiplas CMKs:

      # -*- coding: utf-8 -*-
      import os
      import oss2
      from oss2.crypto import RsaProvider
      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.ProviderAuthV4(EnvironmentVariableCredentialsProvider())
      
      # Create an RSA-based key pair. 
      key_pair_1 = {'private_key': 'yourPrivateKey_1', 'public_key': 'yourPublicKey_1'}
      mat_desc_1 = {'key1': 'value1'}
      
      # Create another RSA-based key pair. 
      key_pair_2 = {'private_key': 'yourPrivateKey_2', 'public_key': 'yourPublicKey_2'}
      mat_desc_2 = {'key2': 'value2'}
      
      provider = RsaProvider(key_pair=key_pair_2, mat_desc=mat_desc_2)
      # Add the description of key_pair_1 to the provider. 
      encryption_materials = oss2.EncryptionMaterials(mat_desc_1, key_pair=key_pair_1)
      provider.add_encryption_materials(encryption_materials)
      
      # 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 region in which the bucket is located. Example: cn-hangzhou This parameter is required if you use the V4 signature algorithm.
      region = "cn-hangzhou"
      
      # Use the provider to initialize a CryptoBucket instance. Then, you can download the object data that is encrypted using a CMK whose description is mat_desc_1. 
      crypto_bucket = oss2.CryptoBucket(auth, endpoint, 'yourBucketName', crypto_provider=provider, region=region)
      
  • Uploads e downloads padrão de arquivos

    O código a seguir demonstra uploads e downloads padrão de arquivos utilizando uma chave mestra do KMS:

    # -*- coding: utf-8 -*-
    import os
    import oss2
    from oss2.credentials import EnvironmentVariableCredentialsProvider
    from oss2.crypto import RsaProvider
    from oss2.crypto import AliKMSProvider
    
    # Obtain access credentials from environment variables. Before you run this sample code, make sure the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set.
    auth = oss2.ProviderAuthV4(EnvironmentVariableCredentialsProvider())
    
    kms_provider = AliKMSProvider(auth, 'yourRegion', 'yourCMKID')
    # Enter the endpoint of the region where the bucket is located. For example, for China (Hangzhou), set the endpoint to https://oss-cn-hangzhou.aliyuncs.com.
    endpoint = "https://oss-cn-hangzhou.aliyuncs.com"
    # Enter the region information corresponding to the endpoint, for example, cn-hangzhou. Note that this parameter is required for V4 signatures.
    region = "cn-hangzhou"
    bucket = oss2.CryptoBucket(auth, endpoint, 'yourBucketName', crypto_provider=kms_provider, region=region)
    
    key = 'motto.txt'
    content = b'a' * 1024 * 1024
    filename = 'download.txt'
    
    # Upload the file.
    bucket.put_object(key, content, headers={'content-length': str(1024 * 1024)})
    
    # Download the OSS file to local memory.
    result = bucket.get_object(key)
    
    # Verify that the content of the downloaded file is the same as the content of the uploaded file.
    content_got = b''
    for chunk in result:
        content_got += chunk
    assert content_got == content
    
    # Download the OSS file to a local file.
    result = bucket.get_object_to_file(key, filename)
    
    # Verify that the content of the downloaded file is the same as the content of the uploaded file.
    with open(filename, 'rb') as fileobj:
        assert fileobj.read() == content
  • Upload Multipart

    Nota
    • Se uma tarefa de upload multipart for interrompida e o processo encerrado, o contexto da tarefa poderá ser perdido. Nesse caso, será necessário reenviar o objeto inteiro desde o início.

    • Para objetos grandes, prefira usar a operação de upload retomável do OSS. Isso permite armazenar o contexto da tarefa de upload multipart no cliente local, preservando-o mesmo se houver interrupção.

    O exemplo abaixo mostra como usar uma CMK gerenciada pelo KMS para criptografar um objeto em um upload multipart:

    # -*- coding: utf-8 -*-
    import os
    import oss2
    from oss2.credentials import EnvironmentVariableCredentialsProvider
    from oss2.crypto import RsaProvider
    from oss2.cryptoimportAliKMSProvider
    
    # 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.ProviderAuthV4(EnvironmentVariableCredentialsProvider())
    
    kms_provider = AliKMSProvider(auth, 'yourRegion', 'yourCMKID')
    # 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 region in which the bucket is located. Example: cn-hangzhou This parameter is required if you use the V4 signature algorithm.
    region = "cn-hangzhou"
    bucket = oss2.CryptoBucket(auth, endpoint, 'yourBucketName', crypto_provider = kms_provider, region=region)
    
    """
    Perform client-side encryption in multipart upload
    """
    # Initiate a multipart upload task. 
    part_a = b'a' * 1024 * 100
    part_b = b'b' * 1024 * 100
    part_c = b'c' * 1024 * 100
    multi_content = [part_a, part_b, part_c]
    
    parts = []
    data_size = 100 * 1024 * 3
    part_size = 100 * 1024
    multi_key = "test_crypto_multipart"
    
    # Initialize the context of the multipart upload task when you use client-side encryption. 
    context = models.MultipartUploadCryptoContext(data_size, part_size)
    res = bucket.init_multipart_upload(multi_key, upload_context=context)
    upload_id = res.upload_id
    
    # In this example, the parts are uploaded in sequence. Multipart upload supports multiple parallel threads to accelerate the upload. 
    for i in range(3):
        # The context values cannot be modified. If the values in context are modified, data upload fails. 
        result = bucket.upload_part(multi_key, upload_id, i + 1, multi_content[i], upload_context=context)
        parts.append(oss2.models.PartInfo(i + 1, result.etag, size=part_size, part_crc=result.crc))
    
    # Complete the multipart upload task. 
    result = bucket.complete_multipart_upload(multi_key, upload_id, parts)
    
    # Check data consistency between the content of the downloaded object and that of the object before upload. 
    result = bucket.get_object(multi_key)
    content_got = b''
    for chunk in result:
        content_got += chunk
    assert content_got[0:102400] == part_a
    assert content_got[102400:204800] == part_b
    assert content_got[204800:307200] == part_c
  • Uploads retomáveis

    O código a seguir exemplifica o uso de uma CMK baseada em RSA gerenciada por você para criptografar um objeto em um upload retomável:

    # -*- coding: utf-8 -*-
    import os
    import oss2
    from oss2.credentials import EnvironmentVariableCredentialsProvider
    from  oss2.crypto import RsaProvider
    
    key = 'motto.txt'
    content = b'a' * 1024 * 1024 * 100
    file_name_put = 'upload.txt'
    
    # Write the data included in content to the file. 
    with open(file_name_put, 'wb') as fileobj:
        fileobj.write(content)
    
    # 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.ProviderAuthV4(EnvironmentVariableCredentialsProvider())
    
    # Initialize a CryptoBucket instance and use the RSA-based CMK to perform client-side encryption. This encryption method supports only uploads and downloads of entire objects. 
    # If you use OSS SDK for Python 2.9.0 or later, we recommend that you do not use LocalRsaProvider to initialize the CryptoBucket instance. 
    # bucket = oss2.CryptoBucket(auth,'yourEndpoint', 'yourBucketName', crypto_provider=LocalRsaProvider())
    
    # If you want to only decrypt objects, specify only the private key. 
    # key_pair = {'private_key': 'yourPrivateKey'}
    # If you want to only encrypt objects, specify only the public key. 
    # key_pair = {'public_key': 'yourPublicKey'}
    # If you want to encrypt and decrypt objects, you must specify both the public key and the private key. 
    key_pair = {'private_key': 'yourPrivateKey', 'public_key': 'yourPublicKey'}
    
    # 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 region in which the bucket is located. Example: cn-hangzhou This parameter is required if you use the V4 signature algorithm.
    region = "cn-hangzhou"
    
    # Initialize a CryptoBucket instance. If you set upload_contexts_flag to True, you do not need to configure parameters for the multipart upload context when you call the upload_part operation. 
    bucket = oss2.CryptoBucket(auth, endpoint, 'yourBucketName',
                               crypto_provider=RsaProvider(key_pair), region=region)
    
    # In this example, the value of multipart_threshold is set to 10 * 1024 * 1024. The default multipart upload threshold is 10 MB. Specify a value based on your scenario. 
    # multipart_threshold specifies the object size threshold for using multipart upload. If the object size exceeds the threshold, multipart upload is used. If the object size is smaller than the threshold, we recommend that you call put_object to upload the object. 
    # part_size specifies the part size in multipart upload. The default part size is 10 MB. 
    # num_threads specifies the number of parallel upload threads. Default value: 1. 
    oss2.resumable_upload(bucket, key, file_name_put, multipart_threshold=10 * 1024 * 1024, part_size=1024 * 1024, num_threads=3)
  • Download retomável

    Veja abaixo como usar uma CMK gerenciada pelo KMS para descriptografar um objeto durante um download retomável:

    # -*- coding: utf-8 -*-
    import os
    import oss2
    from oss2.crypto import RsaProvider
    from oss2.cryptoimportAliKMSProvider
    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.ProviderAuthV4(EnvironmentVariableCredentialsProvider())
    
    key = 'motto.txt'
    content = b'a' * 1024 * 1024 * 100
    file_name_get = 'download.txt'
    
    kms_provider = AliKMSProvider(auth, 'yourRegion', 'yourCMKID')
    
    endpoint = "https://oss-cn-hangzhou.aliyuncs.com"
    # Specify the region in which the bucket is located. Example: cn-hangzhou This parameter is required if you use the V4 signature algorithm.
    region = "cn-hangzhou"
    bucket = oss2.CryptoBucket(auth, endpoint, 'yourBucketName', crypto_provider=kms_provider, region=region)
    
    # Download an object using resumable download. 
    oss2.resumable_download(bucket, key, file_name_get, multiget_threshold=10 * 1024 * 1024, part_size=1024 * 1024, num_threads=3)
    
    # Check data consistency between the content of the downloaded object and that of the object before upload. 
    with open(file_name_get, 'rb') as fileobj:
        assert fileobj.read() == content
    

Criptografia no lado do cliente V1 (não recomendada)

Nota
  • A versão V1 da criptografia no lado do cliente suporta apenas o upload de objetos menores que 5 GB via PutObject. Operações de upload multipart, upload retomável e download retomável não são suportadas.

  • Após enviar um objeto usando as operações da classe CryptoBucket, não é possível modificar seus metadados com operações como CopyObject. Alterações nos metadados podem causar falhas na descriptografia.

  • Somente o OSS SDK for Python oferece suporte à criptografia no lado do cliente V1. SDKs do OSS para outras linguagens de programação não conseguem descriptografar dados enviados com essa versão.

  • O OSS SDK for Python V2.11.0 e versões posteriores suportam a criptografia no lado do cliente V2, que oferece mais recursos que a V1. Recomendamos atualizar o OSS SDK for Python para a versão mais recente.

  • Metadados de objeto relacionados à criptografia no lado do cliente

    Parâmetro

    Descrição

    Obrigatório

    x-oss-meta-oss-crypto-key

    Chave de dados criptografada. É uma string criptografada com uma CMK baseada em RSA e codificada em Base64.

    Sim

    x-oss-meta-oss-crypto-start

    Valor inicial gerado aleatoriamente para criptografia dos dados. Trata-se de uma string criptografada com uma CMK baseada em RSA e codificada em Base64.

    Sim

    x-oss-meta-oss-cek-alg

    Algoritmo utilizado para criptografar os dados.

    Sim

    x-oss-meta-oss-wrap-alg

    Algoritmo usado para criptografar a chave de dados.

    Sim

    x-oss-meta-oss-matdesc

    Descrição da chave de criptografia de conteúdo (CEK) no formato JSON. Este parâmetro não tem efeito.

    Não

    x-oss-meta-unencrypted-content-length

    Tamanho dos dados antes da criptografia. Este parâmetro não é gerado se content-length não for especificado.

    Não

    x-oss-meta-unencrypted-content-md5

    Hash MD5 dos dados antes da criptografia. Este parâmetro não é gerado se content-md5 não for especificado.

    Não

  • Upload e download de arquivos usando RSA

    O exemplo de código abaixo demonstra como usar RSA para enviar e baixar arquivos:

    # -*- coding: utf-8 -*-
    import os
    import oss2
    from oss2.credentials import EnvironmentVariableCredentialsProvider
    from oss2.crypto import LocalRsaProvider
    
    # 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.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 region in which the bucket is located. Example: cn-hangzhou This parameter is required if you use the V4 signature algorithm.
    region = "cn-hangzhou"
    # Initialize a CryptoBucket instance and use the RSA-based CMK to perform client-side encryption. This encryption method supports only uploads and downloads of entire objects. 
    bucket = oss2.CryptoBucket(auth, endpoint, 'yourBucketName', crypto_provider=LocalRsaProvider(), region=region)
    
    key = 'motto.txt'
    content = b'a' * 1024 * 1024
    filename = 'download.txt'
    
    # Upload the object. 
    bucket.put_object(key, content, headers={'content-length': str(1024 * 1024)})
    
    # Download the object from OSS to the local memory. 
    result = bucket.get_object(key)
    
    # Check data consistency between the content of the downloaded object and that of the object before upload. 
    content_got = b''
    for chunk in result:
        content_got += chunk
    assert content_got == content
    
    # Download the object from OSS to a local path. 
    result = bucket.get_object_to_file(key, filename)
    
    # Check data consistency between the content of the downloaded object and that of the object before upload. 
    with open(filename, 'rb') as fileobj:
        assert fileobj.read() == content

Referências

Para acessar o código de exemplo completo sobre criptografia no lado do cliente, visite o GitHub.