Add sample for transactional checksum (#2384)

This commit is contained in:
JinmingHu 2021-06-03 09:36:14 +08:00 committed by GitHub
parent bae5f553a2
commit 06cc8980f4
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 55 additions and 0 deletions

View File

@ -115,6 +115,7 @@ if(BUILD_STORAGE_SAMPLES)
sample/blob_getting_started.cpp
sample/blob_list_operation.cpp
sample/blob_sas.cpp
sample/transactional_checksum.cpp
)
target_link_libraries(azure-storage-sample PRIVATE azure-storage-blobs)

View File

@ -0,0 +1,54 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// SPDX-License-Identifier: MIT
#include <iostream>
#include <azure/storage/blobs.hpp>
#include "samples_common.hpp"
SAMPLE(TransactionalChecksum, TransactionalChecksum)
void TransactionalChecksum()
{
using namespace Azure::Storage::Blobs;
std::string containerName = "sample-container";
std::string blobName = "sample-blob";
auto containerClient
= BlobContainerClient::CreateFromConnectionString(GetConnectionString(), containerName);
containerClient.CreateIfNotExists();
BlockBlobClient blobClient = containerClient.GetBlockBlobClient(blobName);
// Upload 1MiB of data and verify with MD5
std::vector<uint8_t> buffer;
buffer.resize(1 * 1024 * 1024);
UploadBlockBlobOptions uploadOptions;
uploadOptions.TransactionalContentHash = Azure::Storage::ContentHash();
uploadOptions.TransactionalContentHash.Value().Algorithm = Azure::Storage::HashAlgorithm::Md5;
Azure::Core::Cryptography::Md5Hash md5Hash;
md5Hash.Append(buffer.data(), buffer.size());
uploadOptions.TransactionalContentHash.Value().Value = md5Hash.Final();
Azure::Core::IO::MemoryBodyStream bodyStream(buffer);
blobClient.Upload(bodyStream, uploadOptions);
// Download the data and verify with CRC64
DownloadBlobOptions downloadOptions;
downloadOptions.Range = Azure::Core::Http::HttpRange(); // Have to specify a range, and the range
// cannot be larger than 4MiB
downloadOptions.Range.Value().Offset = 0;
downloadOptions.Range.Value().Length = buffer.size();
downloadOptions.RangeHashAlgorithm = Azure::Storage::HashAlgorithm::Crc64;
auto downloadResponse = blobClient.Download(downloadOptions);
buffer = downloadResponse.Value.BodyStream->ReadToEnd();
Azure::Storage::Crc64Hash crc64Hash;
crc64Hash.Append(buffer.data(), buffer.size());
if (crc64Hash.Final() != downloadResponse.Value.TransactionalContentHash.Value().Value)
{
std::cout << "CRC-64 mismatch" << std::endl;
}
else
{
std::cout << "CRC-64 match" << std::endl;
}
}