Le SDK OSS pour Java utilise la vérification MD5 et CRC-64 afin de garantir l'intégrité des données lors du chargement, du téléchargement et de la copie d'objets.
Notes
Cette rubrique utilise le point de terminaison public de la région Chine (Hangzhou). Si vous souhaitez accéder à OSS depuis d'autres services Alibaba Cloud situés dans la même région, utilisez un point de terminaison interne. Pour plus d'informations sur les régions et les points de terminaison OSS, consultez Régions et points de terminaison.
Dans cette rubrique, les identifiants d'accès sont récupérés à partir des variables d'environnement. Pour savoir comment configurer les identifiants d'accès, consultez Configurer les identifiants d'accès à l'aide du SDK OSS pour Python 1.0.
Cette rubrique illustre la création d'une instance
OSSClientavec un endpoint OSS. Pour d'autres configurations, telles que l'utilisation d'un domaine personnalisé ou l'authentification via des identifiants du Security Token Service (STS), consultez Initialisation.
Validation MD5
Lorsque vous incluez l'en-tête Content-MD5 dans une requête de chargement, OSS compare le hachage MD5 des données reçues à la valeur fournie. En cas de non-correspondance, OSS renvoie une erreur InvalidDigest et vous devez recharger l'objet.
Configurez la vérification MD5 lors d'une opération PutObject :
# -*- coding: utf-8 -*-
import oss2
from oss2.credentials import EnvironmentVariableCredentialsProvider
# 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.
auth = oss2.ProviderAuthV4(EnvironmentVariableCredentialsProvider())
# Specify the Endpoint for 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.
endpoint = "https://oss-cn-hangzhou.aliyuncs.com"
# Specify the region that corresponds to the Endpoint, for example, cn-hangzhou. Note that this parameter is required for v4 signatures.
region = "cn-hangzhou"
# Replace examplebucket with the name of your bucket.
bucket = oss2.Bucket(auth, endpoint, "examplebucket", region=region)
# Specify the full path of the object. The full path cannot include the bucket name. For example, exampledir/exampleobject.txt.
object_name = 'exampledir/exampleobject.txt'
# Specify the local path of the file to upload. The value of this variable is transferred to OSS as the content to upload. The file can be of any type, such as text, image, video, or audio.
with open('/Users/test/Desktop/demo.txt', 'rb') as file:
content = file.read()
# Calculate the MD5 hash of the content to be uploaded.
content_md5 = oss2.utils.content_md5(content)
print('content_md5', content_md5)
# Include the 'Content-MD5' header in the upload request. The server verifies the MD5 hash of the uploaded content to ensure its integrity and correctness.
headers = dict()
headers['Content-MD5'] = content_md5
bucket.put_object(object_name, content, headers=headers)
La validation MD5 est prise en charge pour les opérations put_object, append_object, post_object et upload_part.
Validation CRC-64
Lorsque vous utilisez le contrôle de redondance cyclique (CRC) pour la validation des données, tenez compte des points suivants :
La validation CRC-64 est prise en charge pour les opérations
put_object,get_object,append_objectetupload_part. La validation CRC est activée par défaut pour les chargements de fichiers. Si la valeur CRC calculée par le client ne correspond pas à la valeur CRC renvoyée par le serveur, une exceptionInconsistentErrorest levée.Les téléchargements partiels (range downloads) ne prennent pas en charge la validation CRC-64.
La validation CRC-64 consomme des ressources CPU et peut affecter les vitesses de chargement et de téléchargement.
-
Validation CRC-64 pour les téléchargements
Le code suivant montre comment valider l'intégrité des données via CRC-64 lors du téléchargement d'un fichier :
# -*- coding: utf-8 -*- import oss2 from oss2.credentials import EnvironmentVariableCredentialsProvider # 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. auth = oss2.ProviderAuthV4(EnvironmentVariableCredentialsProvider()) # Specify the Endpoint for 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. endpoint = "https://oss-cn-hangzhou.aliyuncs.com" # Specify the region that corresponds to the Endpoint, for example, cn-hangzhou. Note that this parameter is required for v4 signatures. region = "cn-hangzhou" # Replace examplebucket with the name of your bucket. bucket = oss2.Bucket(auth, endpoint, "examplebucket", region=region) # Specify the full path of the object. The full path cannot include the bucket name. object_name = 'yourObjectName' # Check whether CRC validation is enabled by default. print('bucket.enable-crc:', bucket.enable_crc) # The return value of bucket.get_object is a file-like object and is also iterable. object_stream = bucket.get_object(object_name) print(object_stream.read()) # Because the get_object operation returns a stream, you must call read() before you can calculate the CRC checksum of the returned object data. Therefore, perform CRC validation after you call this operation. if object_stream.client_crc != object_stream.server_crc: print("The CRC checksum between client and server is inconsistent!") -
Validation CRC-64 pour les chargements par ajout
Pour les chargements par ajout, si vous spécifiez le paramètre
init_crc, la validation CRC-64 est activée par défaut.# -*- coding: utf-8 -*- import oss2 from oss2.credentials import EnvironmentVariableCredentialsProvider # 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. auth = oss2.ProviderAuthV4(EnvironmentVariableCredentialsProvider()) # Specify the Endpoint for 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. endpoint = "https://oss-cn-hangzhou.aliyuncs.com" # Specify the region that corresponds to the Endpoint, for example, cn-hangzhou. Note that this parameter is required for v4 signatures. region = "cn-hangzhou" # Replace examplebucket with the name of your bucket. bucket = oss2.Bucket(auth, endpoint, "examplebucket", region=region) object_name = "yourAppendObjectName" first_content = "yourFirstContent" second_content = "yourSecondContent" # First append upload. # If init_crc is specified, the SDK performs CRC validation on the returned result by default. result = bucket.append_object(object_name, 0, first_content, init_crc=0) # Second append upload. # Set init_crc to the CRC value of the uploaded data. result = bucket.append_object(object_name, result.next_position, second_content, init_crc=result.crc)
Références
Pour obtenir le code complet illustrant la validation des données, consultez l'exemple GitHub.