Todos los productos
Search
Centro de documentos

Object Storage Service:Client-side encryption (Python SDK V1)

Última actualización: Sep 05, 2026

Si se habilita el cifrado del lado del cliente, los objetos se cifran localmente antes de cargarse en Object Storage Service (OSS). Solo el propietario de la clave maestra del cliente (CMK) puede descifrar los objetos. El cifrado del lado del cliente mejora la seguridad de los datos durante su transmisión y almacenamiento.

Aviso legal

  • Al utilizar el cifrado del lado del cliente, debe garantizar la integridad y validez de la CMK. Si la CMK se utiliza incorrectamente o se pierde debido a un mantenimiento inadecuado, usted será responsable de todas las pérdidas y consecuencias derivadas de fallos en el descifrado.

  • Al copiar o migrar datos cifrados, es responsabilidad suya mantener la integridad y validez de los metadatos del objeto. Si los metadatos cifrados son incorrectos o se pierden por un mantenimiento inadecuado, usted asumirá todas las pérdidas y consecuencias causadas por fallos en el descifrado de datos.

Escenarios

  • Datos altamente sensibles: Para información de identificación personal (PII), registros de transacciones financieras, datos de salud y otros datos altamente sensibles, los usuarios pueden optar por cifrar la información antes de que salga del entorno local. Esto asegura que los datos originales estén protegidos eficazmente incluso si se interceptan durante la transmisión.

  • Requisitos de cumplimiento: Ciertas industrias y regulaciones, como la Ley de Portabilidad y Responsabilidad de Seguros Médicos (HIPAA) y el Reglamento General de Protección de Datos (GDPR), exigen una gestión estricta del cifrado para los datos almacenados en plataformas de terceros. El cifrado del lado del cliente ayuda a cumplir estos requisitos, ya que las CMK son gestionadas por los usuarios y no se transmiten por la red ni se exponen a los proveedores de servicios en la nube.

  • Control total del cifrado: Una empresa o desarrollador puede desear tener control absoluto sobre el proceso de cifrado, lo que incluye seleccionar algoritmos de cifrado, así como gestionar y rotar las CMK. En este caso, el uso del cifrado del lado del cliente garantiza que solo los usuarios autorizados puedan descifrar y acceder a los datos.

  • Seguridad en la migración de datos entre regiones: El cifrado del lado del cliente ayuda a mantener los datos en estado cifrado tanto antes como después de una migración entre regiones. Esto refuerza la seguridad de la transmisión de datos a través de Internet.

Notas

  • En este tema se utiliza el endpoint público de la región China (Hangzhou). Si desea acceder a OSS desde otros servicios de Alibaba Cloud en la misma región que OSS, utilice un endpoint interno. Para obtener más información sobre las regiones y endpoints de OSS, consulte Regions and endpoints.

  • En este tema, las credenciales de acceso se obtienen de variables de entorno. Para obtener más información sobre cómo configurar las credenciales de acceso, consulte Configure access credentials using OSS SDK for Python 1.0.

  • Este tema muestra cómo crear una instancia de OSSClient con un endpoint de OSS. Para configuraciones alternativas, como el uso de un dominio personalizado o la autenticación con credenciales de Security Token Service (STS), consulte Initialization.

Contexto

En el cifrado del lado del cliente, se genera una clave de datos aleatoria para cada objeto con el fin de realizar un cifrado simétrico sobre dicho objeto. El cliente utiliza una CMK para cifrar la clave de datos aleatoria. La clave de datos cifrada se carga como parte de los metadatos del objeto y se almacena en el servidor de OSS. Cuando se descarga un objeto cifrado, el cliente usa la CMK para descifrar la clave de datos aleatoria y posteriormente utiliza esa clave descifrada para descifrar el objeto. Para garantizar la seguridad de los datos, la CMK se utiliza únicamente en el cliente y no se transmite por la red ni se almacena en el servidor.

Métodos de cifrado

Actualmente, una clave maestra se utiliza de las siguientes dos maneras:

  • CMK gestionadas por KMS

    Cuando utiliza una CMK gestionada en Key Management Service (KMS) para el cifrado del lado del cliente, debe proporcionar el ID de la CMK al OSS SDK for Python.

  • CMK basadas en RSA gestionadas por usted mismo

    Cuando utiliza una CMK gestionada por usted mismo para el cifrado del lado del cliente, debe enviar la clave pública y la clave privada de su CMK al OSS SDK for Python como parámetros.

Puede utilizar los métodos de cifrado anteriores para prevenir fugas de datos y proteger su información en el cliente. Incluso si sus datos se filtran, nadie más podrá descifrarlos.

Para obtener más información, consulte Client-side encryption en la Guía para desarrolladores de OSS.

Cifrado del lado del cliente V2 (recomendado)

Importante
  • El cifrado del lado del cliente admite la carga multiparte para objetos cuyo tamaño supera los 5 GB. Al utilizar la carga multiparte para cargar un objeto, debe especificar el tamaño total del objeto y el tamaño de cada parte. El tamaño de cada parte, excepto la última, debe ser idéntico y múltiplo de 16 bytes.

  • Si carga un objeto cifrado en un cliente local, los metadatos del objeto se cifran y protegen, por lo que no pueden modificarse mediante llamadas a operaciones como CopyObject.

  • Metadatos del objeto relacionados con el cifrado del lado del cliente

    Parámetro

    Descripción

    Obligatorio

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

    La clave de datos cifrada. Es una cadena cifrada mediante una CMK basada en RSA o una CMK gestionada por KMS, y codificada en Base64.

    Sí

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

    El vector de inicialización generado aleatoriamente para el cifrado de datos. Es una cadena cifrada mediante una CMK basada en RSA o una CMK gestionada por KMS, y codificada en Base64.

    Sí

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

    El algoritmo utilizado para cifrar los datos.

    Sí

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

    El algoritmo utilizado para cifrar la clave de datos.

    Sí

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

    La descripción de la clave de cifrado de contenido (CEK) en formato JSON.

    No

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

    La longitud de los datos antes del cifrado. Si no se especifica content-length, este parámetro no se genera.

    No

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

    El hash MD5 de los datos antes del cifrado. Si no se especifica content-md5, este parámetro no se genera.

    No

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

    El tamaño total del objeto que desea cargar mediante carga multiparte.

    Condicional (obligatorio para carga multiparte)

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

    El tamaño de parte especificado en la carga multiparte.

    Condicional (obligatorio para carga multiparte)

  • Crear un bucket para el cifrado del lado del cliente

    Antes de cifrar y cargar un objeto, o descargar y descifrar un objeto en el cliente, debe inicializar una instancia de bucket. Puede llamar a las operaciones del bucket para cargar o descargar objetos. En el cifrado del lado del cliente, la clase CryptoBucket hereda las operaciones de la clase Bucket. Puede configurar parámetros para inicializar una instancia de CryptoBucket de la misma manera que inicializa una instancia de Bucket.

    • Inicializar una instancia de CryptoBucket para el cifrado de objetos mediante una CMK basada en RSA gestionada por usted mismo

      Importante

      Si utiliza una CMK basada en RSA, debe gestionarla usted mismo. La pérdida de la CMK o el daño a sus datos pueden provocar fallos en el descifrado. Se recomienda utilizar CMK gestionadas por KMS. Si decide usar una CMK basada en RSA para realizar el cifrado, le recomendamos hacer una copia de seguridad de los datos de su CMK.

      El siguiente código de ejemplo muestra cómo inicializar una instancia de CryptoBucket para el cifrado de objetos mediante una CMK basada en RSA gestionada por usted mismo:

      # -*- 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 una instancia de CryptoBucket para el cifrado de objetos mediante una CMK gestionada por KMS

      El siguiente código de ejemplo muestra cómo inicializar una instancia de CryptoBucket para el cifrado de objetos mediante una CMK gestionada por 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)
      
    • Uso y gestión de múltiples CMK

      Es posible utilizar diferentes CMK para cifrar objetos cargados en un bucket o descifrar objetos descargados del mismo bucket. Puede especificar distintas descripciones para las CMK y agregar tanto las claves como las descripciones a la información relacionada con el cifrado del bucket. Al descifrar los datos, el OSS SDK for Python asocia automáticamente una CMK según su descripción. El siguiente código de ejemplo muestra cómo proporcionar múltiples CMK:

      # -*- 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)
      
  • Cargas y descargas estándar de archivos

    El siguiente código de ejemplo demuestra cargas y descargas estándar de archivos utilizando una clave maestra de 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
  • Carga multiparte

    Nota
    • Si una tarea de carga multiparte se interrumpe y el proceso finaliza, es posible que se pierda el contexto de dicha tarea. Si esto ocurre y desea volver a cargar el objeto, deberá cargarlo nuevamente en su totalidad.

    • Se recomienda llamar a la operación de carga reanudable en OSS para cargar objetos grandes. De esta forma, puede almacenar el contexto de una tarea de carga multiparte en el cliente local para conservarlo incluso si la tarea se interrumpe.

    El siguiente código de ejemplo muestra cómo utilizar una CMK gestionada por KMS para cifrar un objeto que desea cargar mediante carga multiparte:

    # -*- 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
  • Cargas reanudables

    El siguiente código de ejemplo muestra cómo utilizar una CMK basada en RSA gestionada por usted mismo para cifrar un objeto que desea cargar mediante carga reanudable:

    # -*- 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)
  • Descarga reanudable

    El siguiente código de ejemplo muestra cómo utilizar una CMK gestionada por KMS para descifrar un objeto que desea descargar mediante descarga reanudable:

    # -*- 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
    

Cifrado del lado del cliente V1 (no recomendado)

Nota
  • El cifrado del lado del cliente V1 solo admite la carga de objetos menores a 5 GB mediante la llamada a PutObject. No se admiten las operaciones de carga multiparte, carga reanudable ni descarga reanudable.

  • Después de cargar un objeto llamando a las operaciones de la clase CryptoBucket, no se pueden invocar operaciones como CopyObject para modificar los metadatos del objeto. Si los metadatos se modifican, podría fallar el descifrado de los datos.

  • Solo el OSS SDK for Python admite el cifrado del lado del cliente V1. Los SDK de OSS para otros lenguajes de programación no pueden descifrar datos cargados con esta versión.

  • El OSS SDK for Python V2.11.0 y versiones posteriores admiten el cifrado del lado del cliente V2. Esta versión ofrece más funciones que la V1. Se recomienda actualizar el OSS SDK for Python a la versión más reciente.

  • Metadatos del objeto relacionados con el cifrado del lado del cliente

    Parámetro

    Descripción

    Obligatorio

    x-oss-meta-oss-crypto-key

    La clave de datos cifrada. Es una cadena cifrada mediante una CMK basada en RSA y codificada en Base64.

    Sí

    x-oss-meta-oss-crypto-start

    El valor inicial generado aleatoriamente para el cifrado de datos. Es una cadena cifrada mediante una CMK basada en RSA y codificada en Base64.

    Sí

    x-oss-meta-oss-cek-alg

    El algoritmo utilizado para cifrar los datos.

    Sí

    x-oss-meta-oss-wrap-alg

    El algoritmo utilizado para cifrar la clave de datos.

    Sí

    x-oss-meta-oss-matdesc

    La descripción de la clave de cifrado de contenido (CEK) en formato JSON. Este parámetro no surte efecto.

    No

    x-oss-meta-unencrypted-content-length

    La longitud de los datos antes del cifrado. Si no se especifica content-length, este parámetro no se genera.

    No

    x-oss-meta-unencrypted-content-md5

    El hash MD5 de los datos antes del cifrado. Si no se especifica content-md5, este parámetro no se genera.

    No

  • Carga y descarga de archivos mediante RSA

    El siguiente código de ejemplo demuestra cómo utilizar RSA para cargar y descargar archivos:

    # -*- 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

Referencias

Para consultar el código de ejemplo completo sobre el cifrado del lado del cliente, visite GitHub.