S3 Http: Download and Verify a Full-Object SHA-256 Checksum
See more S3 - HTTP Examples
Uses Chilkat.Http with Amazon S3 general purpose buckets and Signature Version 4. These examples do not cover directory buckets/S3 Express, access-point ARNs, Outposts, or other specialized endpoints. They target the commercial AWS partition; other partitions need their documented endpoint suffix.
Load private qa_data/aws/s3.json containing nonempty string fields access_key and secret_key, plus session_token for temporary credentials. Prefer short-lived role credentials. These samples do not discover AWS profiles or refresh credentials. Set the bucket's actual region and replace sample bucket names and object keys. TLS certificate verification is explicitly enabled. Keep detailed HTTP diagnostics private because they can contain credentials or presigned URLs.
Uses explicit signed Http requests to preserve query parameters, conditional headers, and full responses. The included SigV4 block signs the exact path, sorted encoded query and headers used by this example; it is not a general-purpose HTTP signing library. Keep the clock accurate and do not change signed data after signing. Code requires Chilkat 11.6.0 or later; locally tested with 11.8.0.
For objects uploaded with a FULL_OBJECT SHA-256 checksum, reads HEAD checksum metadata, pins a returned version ID and ETag, downloads using If-Match, and checks returned metadata, actual byte count and the locally computed base64 SHA-256 before renaming. Empty objects are supported. Create qa_output first; existing output paths are not overwritten.
COMPOSITE or absent SHA-256 checksums stop explicitly. Use the companion single-PUT checksum upload to create a suitable object. Requires s3:GetObject/s3:GetObjectVersion and applicable KMS permissions. No multipart ETag-as-MD5 assumption.
Chilkat Unicode C++ Downloads
#include <CkStringBuilderW.h>
#include <CkJsonObjectW.h>
#include <CkHttpW.h>
#include <CkHttpResponseW.h>
#include <CkCrypt2W.h>
#include <CkDateTimeW.h>
#include <CkXmlW.h>
#include <CkFileAccessW.h>
#include <CkMimeW.h>
void ChilkatSample(void)
{
bool success = false;
CkStringBuilderW stringCompare;
// This example requires the Chilkat API to have been previously unlocked.
// See Global Unlock Sample for sample code.
// Load private credentials; never put access keys or session tokens in source.
CkJsonObjectW credentials;
credentials.put_Strict(true);
success = credentials.LoadFile(L"qa_data/aws/s3.json");
if (success != true) {
wprintf(L"Could not load private S3 credentials.\n");
return;
}
stringCompare.SetString(credentials.stringOf(L"access_key"));
bool stringMatch1 = stringCompare.ContentsEqual(L"",true);
if ((credentials.JsonTypeOf(L"access_key") != 1) || (stringMatch1 == true)) {
wprintf(L"Missing or invalid access_key.\n");
return;
}
stringCompare.SetString(credentials.stringOf(L"secret_key"));
bool stringMatch2 = stringCompare.ContentsEqual(L"",true);
if ((credentials.JsonTypeOf(L"secret_key") != 1) || (stringMatch2 == true)) {
wprintf(L"Missing or invalid secret_key.\n");
return;
}
CkHttpW http;
http.put_AwsAccessKey(credentials.stringOf(L"access_key"));
http.put_AwsSecretKey(credentials.stringOf(L"secret_key"));
if (credentials.HasMember(L"session_token") == true) {
stringCompare.SetString(credentials.stringOf(L"session_token"));
bool stringMatch3 = stringCompare.ContentsEqual(L"",true);
if ((credentials.JsonTypeOf(L"session_token") != 1) || (stringMatch3 == true)) {
wprintf(L"session_token must be a nonempty string when supplied.\n");
return;
}
http.put_AwsSessionToken(credentials.stringOf(L"session_token"));
}
// Current Chilkat uses SigV4 by default. Do not select deprecated SigV2.
// Set the actual bucket region, not the caller's location.
const wchar_t *region = L"us-west-2";
http.put_AwsRegion(region);
CkStringBuilderW endpoint;
endpoint.Append(L"s3.");
endpoint.Append(region);
endpoint.Append(L".amazonaws.com");
http.put_AwsEndpoint(endpoint.getAsString());
http.put_RequireSslCertVerify(true);
http.put_FollowRedirects(false);
// A region redirect is not success. Correct the endpoint and signing region.
const wchar_t *bucketName = L"your-bucket-name";
const wchar_t *objectKey = L"examples/archive.bin";
CkHttpResponseW response;
CkCrypt2W signer;
signer.put_Charset(L"utf-8");
signer.put_HashAlgorithm(L"sha256");
signer.put_EncodingMode(L"hexlower");
signer.put_MacAlgorithm(L"hmac");
CkDateTimeW now;
CkStringBuilderW timestamp;
CkStringBuilderW canonical;
CkStringBuilderW canonicalHeaders;
CkStringBuilderW signedHeaders;
CkStringBuilderW scope;
CkStringBuilderW stringToSign;
CkStringBuilderW signingKey;
CkStringBuilderW authorization;
CkStringBuilderW url;
CkStringBuilderW query;
CkStringBuilderW number;
CkStringBuilderW host;
CkStringBuilderW uri;
CkXmlW xml;
const wchar_t *amzDate = 0;
const wchar_t *dateStamp = 0;
const wchar_t *payloadHash = 0;
const wchar_t *canonicalHash = 0;
const wchar_t *derivedKey = 0;
const wchar_t *signature = 0;
int replaceCount;
host.Append(bucketName);
host.Append(L".");
host.Append(endpoint.getAsString());
// Encode the original key exactly once, preserving S3 path separators.
uri.SetString(http.urlEncode(objectKey));
replaceCount = uri.ReplaceNoCase(L"%2f",L"/");
if ((uri.StartsWith(L"/",true) == true) || (uri.Contains(L"/../",true) == true) || (uri.Contains(L"/./",true) == true)) {
wprintf(L"Use a key without a leading slash or dot path segments for these examples.\n");
return;
}
uri.Prepend(L"/");
const wchar_t *versionId = L"";
const wchar_t *etag = 0;
const wchar_t *expectedSize = 0;
const wchar_t *expectedChecksum = 0;
const wchar_t *checksumType = 0;
const wchar_t *returnedVersion = 0;
CkFileAccessW files;
const wchar_t *finalPath = L"qa_output/s3-download.bin";
const wchar_t *partialPath = L"qa_output/s3-download.bin.part";
if ((files.FileExists(finalPath) == true) || (files.FileExists(partialPath) == true)) {
wprintf(L"Choose unused output paths.\n");
return;
}
query.Clear();
stringCompare.SetString(versionId);
bool stringMatch4 = stringCompare.ContentsEqual(L"",true);
if (stringMatch4 != true) {
if (query.get_Length() > 0) {
query.Append(L"&");
}
query.Append(L"versionId=");
query.Append(http.urlEncode(versionId));
}
http.ClearHeaders();
success = now.SetFromCurrentSystemTime();
if (success != true) {
wprintf(L"Could not read system time.\n");
return;
}
timestamp.SetString(now.getAsTimestamp(false));
replaceCount = timestamp.Replace(L"-",L"");
replaceCount = timestamp.Replace(L":",L"");
amzDate = timestamp.getAsString();
dateStamp = timestamp.getRange(0,8,false);
payloadHash = signer.hashStringENC(L"");
if (signer.get_LastMethodSuccess() != true) {
wprintf(L"Could not hash payload.\n");
return;
}
canonicalHeaders.Clear();
signedHeaders.Clear();
if (signedHeaders.get_Length() > 0) {
signedHeaders.Append(L";");
}
signedHeaders.Append(L"host");
canonicalHeaders.Append(L"host:");
canonicalHeaders.Append(host.getAsString());
canonicalHeaders.Append(L"\n");
http.SetRequestHeader(L"host",host.getAsString());
if (signedHeaders.get_Length() > 0) {
signedHeaders.Append(L";");
}
signedHeaders.Append(L"x-amz-checksum-mode");
canonicalHeaders.Append(L"x-amz-checksum-mode:");
canonicalHeaders.Append(L"ENABLED");
canonicalHeaders.Append(L"\n");
http.SetRequestHeader(L"x-amz-checksum-mode",L"ENABLED");
if (signedHeaders.get_Length() > 0) {
signedHeaders.Append(L";");
}
signedHeaders.Append(L"x-amz-content-sha256");
canonicalHeaders.Append(L"x-amz-content-sha256:");
canonicalHeaders.Append(payloadHash);
canonicalHeaders.Append(L"\n");
http.SetRequestHeader(L"x-amz-content-sha256",payloadHash);
if (signedHeaders.get_Length() > 0) {
signedHeaders.Append(L";");
}
signedHeaders.Append(L"x-amz-date");
canonicalHeaders.Append(L"x-amz-date:");
canonicalHeaders.Append(amzDate);
canonicalHeaders.Append(L"\n");
http.SetRequestHeader(L"x-amz-date",amzDate);
if (credentials.HasMember(L"session_token") == true) {
if (signedHeaders.get_Length() > 0) {
signedHeaders.Append(L";");
}
signedHeaders.Append(L"x-amz-security-token");
canonicalHeaders.Append(L"x-amz-security-token:");
canonicalHeaders.Append(credentials.stringOf(L"session_token"));
canonicalHeaders.Append(L"\n");
http.SetRequestHeader(L"x-amz-security-token",credentials.stringOf(L"session_token"));
}
canonical.Clear();
canonical.Append(L"HEAD\n");
canonical.Append(uri.getAsString());
canonical.Append(L"\n");
canonical.Append(query.getAsString());
canonical.Append(L"\n");
canonical.Append(canonicalHeaders.getAsString());
canonical.Append(L"\n");
canonical.Append(signedHeaders.getAsString());
canonical.Append(L"\n");
canonical.Append(payloadHash);
canonicalHash = signer.hashStringENC(canonical.getAsString());
if (signer.get_LastMethodSuccess() != true) {
wprintf(L"Could not hash canonical request.\n");
return;
}
scope.Clear();
scope.Append(dateStamp);
scope.Append(L"/");
scope.Append(region);
scope.Append(L"/s3/aws4_request");
stringToSign.Clear();
stringToSign.Append(L"AWS4-HMAC-SHA256\n");
stringToSign.Append(amzDate);
stringToSign.Append(L"\n");
stringToSign.Append(scope.getAsString());
stringToSign.Append(L"\n");
stringToSign.Append(canonicalHash);
signingKey.SetString(L"AWS4");
signingKey.Append(credentials.stringOf(L"secret_key"));
success = signer.SetMacKeyString(signingKey.getAsString());
if (success != true) {
wprintf(L"Could not set signing key.\n");
return;
}
derivedKey = signer.macStringENC(dateStamp);
if (signer.get_LastMethodSuccess() != true) {
wprintf(L"Could not derive signing key.\n");
return;
}
success = signer.SetMacKeyEncoded(derivedKey,L"hex");
if (success != true) {
wprintf(L"Could not set signing key.\n");
return;
}
derivedKey = signer.macStringENC(region);
if (signer.get_LastMethodSuccess() != true) {
wprintf(L"Could not derive signing key.\n");
return;
}
success = signer.SetMacKeyEncoded(derivedKey,L"hex");
if (success != true) {
wprintf(L"Could not set signing key.\n");
return;
}
derivedKey = signer.macStringENC(L"s3");
if (signer.get_LastMethodSuccess() != true) {
wprintf(L"Could not derive signing key.\n");
return;
}
success = signer.SetMacKeyEncoded(derivedKey,L"hex");
if (success != true) {
wprintf(L"Could not set signing key.\n");
return;
}
derivedKey = signer.macStringENC(L"aws4_request");
if (signer.get_LastMethodSuccess() != true) {
wprintf(L"Could not derive signing key.\n");
return;
}
success = signer.SetMacKeyEncoded(derivedKey,L"hex");
if (success != true) {
wprintf(L"Could not set signing key.\n");
return;
}
signature = signer.macStringENC(stringToSign.getAsString());
if (signer.get_LastMethodSuccess() != true) {
wprintf(L"Could not sign request.\n");
return;
}
authorization.Clear();
authorization.Append(L"AWS4-HMAC-SHA256 Credential=");
authorization.Append(credentials.stringOf(L"access_key"));
authorization.Append(L"/");
authorization.Append(scope.getAsString());
authorization.Append(L", SignedHeaders=");
authorization.Append(signedHeaders.getAsString());
authorization.Append(L", Signature=");
authorization.Append(signature);
http.SetRequestHeader(L"Authorization",authorization.getAsString());
url.SetString(L"https://");
url.Append(host.getAsString());
url.Append(uri.getAsString());
if (query.get_Length() > 0) {
url.Append(L"?");
url.Append(query.getAsString());
}
success = http.HttpNoBody(L"HEAD",url.getAsString(),response);
if ((success != true) || (response.get_StatusCode() != 200)) {
wprintf(L"Request failed or returned unexpected HTTP status: %d\n",response.get_StatusCode());
// Preserve progress. Inspect full diagnostics privately; do not log secrets.
return;
}
etag = response.getHeaderField(L"ETag");
stringCompare.SetString(etag);
bool stringMatch5 = stringCompare.ContentsEqual(L"",true);
if ((response.get_LastMethodSuccess() != true) || (stringMatch5 == true)) {
wprintf(L"Missing required response header ETag.\n");
return;
}
expectedSize = response.getHeaderField(L"Content-Length");
stringCompare.SetString(expectedSize);
bool stringMatch6 = stringCompare.ContentsEqual(L"",true);
if ((response.get_LastMethodSuccess() != true) || (stringMatch6 == true)) {
wprintf(L"Missing required response header Content-Length.\n");
return;
}
returnedVersion = response.getHeaderField(L"x-amz-version-id");
if (response.get_LastMethodSuccess() != true) {
returnedVersion = L"";
}
stringCompare.SetString(versionId);
bool stringMatch7 = stringCompare.ContentsEqual(L"",true);
if (stringMatch7 == true) {
versionId = returnedVersion;
}
else {
stringCompare.SetString(returnedVersion);
bool stringMatch8 = stringCompare.ContentsEqual(versionId,true);
if (stringMatch8 != true) {
wprintf(L"Unexpected object version.\n");
return;
}
}
expectedChecksum = response.getHeaderField(L"x-amz-checksum-sha256");
stringCompare.SetString(expectedChecksum);
bool stringMatch9 = stringCompare.ContentsEqual(L"",true);
if ((response.get_LastMethodSuccess() != true) || (stringMatch9 == true)) {
wprintf(L"Missing required response header x-amz-checksum-sha256.\n");
return;
}
checksumType = response.getHeaderField(L"x-amz-checksum-type");
stringCompare.SetString(checksumType);
bool stringMatch10 = stringCompare.ContentsEqual(L"",true);
if ((response.get_LastMethodSuccess() != true) || (stringMatch10 == true)) {
wprintf(L"Missing required response header x-amz-checksum-type.\n");
return;
}
stringCompare.SetString(checksumType);
bool stringMatch11 = stringCompare.ContentsEqual(L"FULL_OBJECT",true);
if (stringMatch11 != true) {
wprintf(L"This example requires a FULL_OBJECT SHA-256 checksum; COMPOSITE needs separate verification.\n");
return;
}
query.Clear();
stringCompare.SetString(versionId);
bool stringMatch12 = stringCompare.ContentsEqual(L"",true);
if (stringMatch12 != true) {
if (query.get_Length() > 0) {
query.Append(L"&");
}
query.Append(L"versionId=");
query.Append(http.urlEncode(versionId));
}
http.ClearHeaders();
success = now.SetFromCurrentSystemTime();
if (success != true) {
wprintf(L"Could not read system time.\n");
return;
}
timestamp.SetString(now.getAsTimestamp(false));
replaceCount = timestamp.Replace(L"-",L"");
replaceCount = timestamp.Replace(L":",L"");
amzDate = timestamp.getAsString();
dateStamp = timestamp.getRange(0,8,false);
payloadHash = signer.hashStringENC(L"");
if (signer.get_LastMethodSuccess() != true) {
wprintf(L"Could not hash payload.\n");
return;
}
canonicalHeaders.Clear();
signedHeaders.Clear();
if (signedHeaders.get_Length() > 0) {
signedHeaders.Append(L";");
}
signedHeaders.Append(L"host");
canonicalHeaders.Append(L"host:");
canonicalHeaders.Append(host.getAsString());
canonicalHeaders.Append(L"\n");
http.SetRequestHeader(L"host",host.getAsString());
if (signedHeaders.get_Length() > 0) {
signedHeaders.Append(L";");
}
signedHeaders.Append(L"if-match");
canonicalHeaders.Append(L"if-match:");
canonicalHeaders.Append(etag);
canonicalHeaders.Append(L"\n");
http.SetRequestHeader(L"if-match",etag);
if (signedHeaders.get_Length() > 0) {
signedHeaders.Append(L";");
}
signedHeaders.Append(L"x-amz-checksum-mode");
canonicalHeaders.Append(L"x-amz-checksum-mode:");
canonicalHeaders.Append(L"ENABLED");
canonicalHeaders.Append(L"\n");
http.SetRequestHeader(L"x-amz-checksum-mode",L"ENABLED");
if (signedHeaders.get_Length() > 0) {
signedHeaders.Append(L";");
}
signedHeaders.Append(L"x-amz-content-sha256");
canonicalHeaders.Append(L"x-amz-content-sha256:");
canonicalHeaders.Append(payloadHash);
canonicalHeaders.Append(L"\n");
http.SetRequestHeader(L"x-amz-content-sha256",payloadHash);
if (signedHeaders.get_Length() > 0) {
signedHeaders.Append(L";");
}
signedHeaders.Append(L"x-amz-date");
canonicalHeaders.Append(L"x-amz-date:");
canonicalHeaders.Append(amzDate);
canonicalHeaders.Append(L"\n");
http.SetRequestHeader(L"x-amz-date",amzDate);
if (credentials.HasMember(L"session_token") == true) {
if (signedHeaders.get_Length() > 0) {
signedHeaders.Append(L";");
}
signedHeaders.Append(L"x-amz-security-token");
canonicalHeaders.Append(L"x-amz-security-token:");
canonicalHeaders.Append(credentials.stringOf(L"session_token"));
canonicalHeaders.Append(L"\n");
http.SetRequestHeader(L"x-amz-security-token",credentials.stringOf(L"session_token"));
}
canonical.Clear();
canonical.Append(L"GET\n");
canonical.Append(uri.getAsString());
canonical.Append(L"\n");
canonical.Append(query.getAsString());
canonical.Append(L"\n");
canonical.Append(canonicalHeaders.getAsString());
canonical.Append(L"\n");
canonical.Append(signedHeaders.getAsString());
canonical.Append(L"\n");
canonical.Append(payloadHash);
canonicalHash = signer.hashStringENC(canonical.getAsString());
if (signer.get_LastMethodSuccess() != true) {
wprintf(L"Could not hash canonical request.\n");
return;
}
scope.Clear();
scope.Append(dateStamp);
scope.Append(L"/");
scope.Append(region);
scope.Append(L"/s3/aws4_request");
stringToSign.Clear();
stringToSign.Append(L"AWS4-HMAC-SHA256\n");
stringToSign.Append(amzDate);
stringToSign.Append(L"\n");
stringToSign.Append(scope.getAsString());
stringToSign.Append(L"\n");
stringToSign.Append(canonicalHash);
signingKey.SetString(L"AWS4");
signingKey.Append(credentials.stringOf(L"secret_key"));
success = signer.SetMacKeyString(signingKey.getAsString());
if (success != true) {
wprintf(L"Could not set signing key.\n");
return;
}
derivedKey = signer.macStringENC(dateStamp);
if (signer.get_LastMethodSuccess() != true) {
wprintf(L"Could not derive signing key.\n");
return;
}
success = signer.SetMacKeyEncoded(derivedKey,L"hex");
if (success != true) {
wprintf(L"Could not set signing key.\n");
return;
}
derivedKey = signer.macStringENC(region);
if (signer.get_LastMethodSuccess() != true) {
wprintf(L"Could not derive signing key.\n");
return;
}
success = signer.SetMacKeyEncoded(derivedKey,L"hex");
if (success != true) {
wprintf(L"Could not set signing key.\n");
return;
}
derivedKey = signer.macStringENC(L"s3");
if (signer.get_LastMethodSuccess() != true) {
wprintf(L"Could not derive signing key.\n");
return;
}
success = signer.SetMacKeyEncoded(derivedKey,L"hex");
if (success != true) {
wprintf(L"Could not set signing key.\n");
return;
}
derivedKey = signer.macStringENC(L"aws4_request");
if (signer.get_LastMethodSuccess() != true) {
wprintf(L"Could not derive signing key.\n");
return;
}
success = signer.SetMacKeyEncoded(derivedKey,L"hex");
if (success != true) {
wprintf(L"Could not set signing key.\n");
return;
}
signature = signer.macStringENC(stringToSign.getAsString());
if (signer.get_LastMethodSuccess() != true) {
wprintf(L"Could not sign request.\n");
return;
}
authorization.Clear();
authorization.Append(L"AWS4-HMAC-SHA256 Credential=");
authorization.Append(credentials.stringOf(L"access_key"));
authorization.Append(L"/");
authorization.Append(scope.getAsString());
authorization.Append(L", SignedHeaders=");
authorization.Append(signedHeaders.getAsString());
authorization.Append(L", Signature=");
authorization.Append(signature);
http.SetRequestHeader(L"Authorization",authorization.getAsString());
url.SetString(L"https://");
url.Append(host.getAsString());
url.Append(uri.getAsString());
if (query.get_Length() > 0) {
url.Append(L"?");
url.Append(query.getAsString());
}
success = http.Download(url.getAsString(),partialPath);
if ((success != true) || (http.get_LastStatus() != 200)) {
wprintf(L"Request failed or returned unexpected HTTP status: %d\n",http.get_LastStatus());
// Preserve progress. Inspect full diagnostics privately; do not log secrets.
return;
}
CkMimeW received;
success = received.LoadMime(http.lastResponseHeader());
if (success != true) {
wprintf(L"Could not parse download headers.\n");
return;
}
const wchar_t *receivedSize = 0;
const wchar_t *receivedHash = 0;
const wchar_t *receivedType = 0;
receivedSize = received.getHeaderField(L"Content-Length");
stringCompare.SetString(receivedSize);
bool stringMatch13 = stringCompare.ContentsEqual(L"",true);
if ((received.get_LastMethodSuccess() != true) || (stringMatch13 == true)) {
wprintf(L"Missing download header Content-Length.\n");
return;
}
receivedHash = received.getHeaderField(L"x-amz-checksum-sha256");
stringCompare.SetString(receivedHash);
bool stringMatch14 = stringCompare.ContentsEqual(L"",true);
if ((received.get_LastMethodSuccess() != true) || (stringMatch14 == true)) {
wprintf(L"Missing download header x-amz-checksum-sha256.\n");
return;
}
receivedType = received.getHeaderField(L"x-amz-checksum-type");
stringCompare.SetString(receivedType);
bool stringMatch15 = stringCompare.ContentsEqual(L"",true);
if ((received.get_LastMethodSuccess() != true) || (stringMatch15 == true)) {
wprintf(L"Missing download header x-amz-checksum-type.\n");
return;
}
stringCompare.SetString(receivedSize);
bool stringMatch16 = stringCompare.ContentsEqual(expectedSize,true);
stringCompare.SetString(receivedHash);
bool stringMatch17 = stringCompare.ContentsEqual(expectedChecksum,true);
stringCompare.SetString(receivedType);
bool stringMatch18 = stringCompare.ContentsEqual(L"FULL_OBJECT",true);
if ((stringMatch16 != true) || (stringMatch17 != true) || (stringMatch18 != true)) {
wprintf(L"Download metadata changed; preserve the temporary file.\n");
return;
}
const wchar_t *actualSize = files.fileSizeStr(partialPath);
stringCompare.SetString(actualSize);
bool stringMatch19 = stringCompare.ContentsEqual(expectedSize,true);
if ((files.get_LastMethodSuccess() != true) || (stringMatch19 != true)) {
wprintf(L"Downloaded size mismatch.\n");
return;
}
CkCrypt2W digest;
digest.put_HashAlgorithm(L"sha256");
digest.put_EncodingMode(L"base64");
const wchar_t *actualChecksum = digest.hashFileENC(partialPath);
stringCompare.SetString(actualChecksum);
bool stringMatch20 = stringCompare.ContentsEqual(expectedChecksum,true);
if ((digest.get_LastMethodSuccess() != true) || (stringMatch20 != true)) {
wprintf(L"Downloaded checksum mismatch.\n");
return;
}
success = files.FileRename(partialPath,finalPath);
if (success != true) {
wprintf(L"Verified download remains at the temporary path.\n");
return;
}
wprintf(L"Full-object SHA-256 download verified.\n");
}