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 PHP ActiveX Downloads
<?php
$success = 0;
$stringCompare = new COM("Chilkat.StringBuilder");
// 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.
$credentials = new COM("Chilkat.JsonObject");
$credentials->Strict = 1;
$success = $credentials->LoadFile('qa_data/aws/s3.json');
if ($success != 1) {
print 'Could not load private S3 credentials.' . "\n";
exit;
}
$stringCompare->SetString($credentials->stringOf('access_key'));
$stringMatch1 = $stringCompare->ContentsEqual('',1);
if (($credentials->JsonTypeOf('access_key') != 1) or ($stringMatch1 == 1)) {
print 'Missing or invalid access_key.' . "\n";
exit;
}
$stringCompare->SetString($credentials->stringOf('secret_key'));
$stringMatch2 = $stringCompare->ContentsEqual('',1);
if (($credentials->JsonTypeOf('secret_key') != 1) or ($stringMatch2 == 1)) {
print 'Missing or invalid secret_key.' . "\n";
exit;
}
$http = new COM("Chilkat.Http");
$http->AwsAccessKey = $credentials->stringOf('access_key');
$http->AwsSecretKey = $credentials->stringOf('secret_key');
if ($credentials->HasMember('session_token') == 1) {
$stringCompare->SetString($credentials->stringOf('session_token'));
$stringMatch3 = $stringCompare->ContentsEqual('',1);
if (($credentials->JsonTypeOf('session_token') != 1) or ($stringMatch3 == 1)) {
print 'session_token must be a nonempty string when supplied.' . "\n";
exit;
}
$http->AwsSessionToken = $credentials->stringOf('session_token');
}
// Current Chilkat uses SigV4 by default. Do not select deprecated SigV2.
// Set the actual bucket region, not the caller's location.
$region = 'us-west-2';
$http->AwsRegion = $region;
$endpoint = new COM("Chilkat.StringBuilder");
$endpoint->Append('s3.');
$endpoint->Append($region);
$endpoint->Append('.amazonaws.com');
$http->AwsEndpoint = $endpoint->getAsString();
$http->RequireSslCertVerify = 1;
$http->FollowRedirects = 0;
// A region redirect is not success. Correct the endpoint and signing region.
$bucketName = 'your-bucket-name';
$objectKey = 'examples/archive.bin';
$response = new COM("Chilkat.HttpResponse");
$signer = new COM("Chilkat.Crypt2");
$signer->Charset = 'utf-8';
$signer->HashAlgorithm = 'sha256';
$signer->EncodingMode = 'hexlower';
$signer->MacAlgorithm = 'hmac';
$now = new COM("Chilkat.CkDateTime");
$timestamp = new COM("Chilkat.StringBuilder");
$canonical = new COM("Chilkat.StringBuilder");
$canonicalHeaders = new COM("Chilkat.StringBuilder");
$signedHeaders = new COM("Chilkat.StringBuilder");
$scope = new COM("Chilkat.StringBuilder");
$stringToSign = new COM("Chilkat.StringBuilder");
$signingKey = new COM("Chilkat.StringBuilder");
$authorization = new COM("Chilkat.StringBuilder");
$url = new COM("Chilkat.StringBuilder");
$query = new COM("Chilkat.StringBuilder");
$number = new COM("Chilkat.StringBuilder");
$host = new COM("Chilkat.StringBuilder");
$uri = new COM("Chilkat.StringBuilder");
$xml = new COM("Chilkat.Xml");
$host->Append($bucketName);
$host->Append('.');
$host->Append($endpoint->getAsString());
// Encode the original key exactly once, preserving S3 path separators.
$uri->SetString($http->urlEncode($objectKey));
$replaceCount = $uri->ReplaceNoCase('%2f','/');
if (($uri->StartsWith('/',1) == 1) or ($uri->Contains('/../',1) == 1) or ($uri->Contains('/./',1) == 1)) {
print 'Use a key without a leading slash or dot path segments for these examples.' . "\n";
exit;
}
$uri->Prepend('/');
$versionId = '';
$files = new COM("Chilkat.FileAccess");
$finalPath = 'qa_output/s3-download.bin';
$partialPath = 'qa_output/s3-download.bin.part';
if (($files->FileExists($finalPath) == 1) or ($files->FileExists($partialPath) == 1)) {
print 'Choose unused output paths.' . "\n";
exit;
}
$query->Clear();
$stringCompare->SetString($versionId);
$stringMatch4 = $stringCompare->ContentsEqual('',1);
if ($stringMatch4 != 1) {
if ($query->Length > 0) {
$query->Append('&');
}
$query->Append('versionId=');
$query->Append($http->urlEncode($versionId));
}
$http->ClearHeaders();
$success = $now->SetFromCurrentSystemTime();
if ($success != 1) {
print 'Could not read system time.' . "\n";
exit;
}
$timestamp->SetString($now->getAsTimestamp(0));
$replaceCount = $timestamp->Replace('-','');
$replaceCount = $timestamp->Replace(':','');
$amzDate = $timestamp->getAsString();
$dateStamp = $timestamp->getRange(0,8,0);
$payloadHash = $signer->hashStringENC('');
if ($signer->LastMethodSuccess != 1) {
print 'Could not hash payload.' . "\n";
exit;
}
$canonicalHeaders->Clear();
$signedHeaders->Clear();
if ($signedHeaders->Length > 0) {
$signedHeaders->Append(';');
}
$signedHeaders->Append('host');
$canonicalHeaders->Append('host:');
$canonicalHeaders->Append($host->getAsString());
$canonicalHeaders->Append('\n');
$http->SetRequestHeader('host',$host->getAsString());
if ($signedHeaders->Length > 0) {
$signedHeaders->Append(';');
}
$signedHeaders->Append('x-amz-checksum-mode');
$canonicalHeaders->Append('x-amz-checksum-mode:');
$canonicalHeaders->Append('ENABLED');
$canonicalHeaders->Append('\n');
$http->SetRequestHeader('x-amz-checksum-mode','ENABLED');
if ($signedHeaders->Length > 0) {
$signedHeaders->Append(';');
}
$signedHeaders->Append('x-amz-content-sha256');
$canonicalHeaders->Append('x-amz-content-sha256:');
$canonicalHeaders->Append($payloadHash);
$canonicalHeaders->Append('\n');
$http->SetRequestHeader('x-amz-content-sha256',$payloadHash);
if ($signedHeaders->Length > 0) {
$signedHeaders->Append(';');
}
$signedHeaders->Append('x-amz-date');
$canonicalHeaders->Append('x-amz-date:');
$canonicalHeaders->Append($amzDate);
$canonicalHeaders->Append('\n');
$http->SetRequestHeader('x-amz-date',$amzDate);
if ($credentials->HasMember('session_token') == 1) {
if ($signedHeaders->Length > 0) {
$signedHeaders->Append(';');
}
$signedHeaders->Append('x-amz-security-token');
$canonicalHeaders->Append('x-amz-security-token:');
$canonicalHeaders->Append($credentials->stringOf('session_token'));
$canonicalHeaders->Append('\n');
$http->SetRequestHeader('x-amz-security-token',$credentials->stringOf('session_token'));
}
$canonical->Clear();
$canonical->Append('HEAD\n');
$canonical->Append($uri->getAsString());
$canonical->Append('\n');
$canonical->Append($query->getAsString());
$canonical->Append('\n');
$canonical->Append($canonicalHeaders->getAsString());
$canonical->Append('\n');
$canonical->Append($signedHeaders->getAsString());
$canonical->Append('\n');
$canonical->Append($payloadHash);
$canonicalHash = $signer->hashStringENC($canonical->getAsString());
if ($signer->LastMethodSuccess != 1) {
print 'Could not hash canonical request.' . "\n";
exit;
}
$scope->Clear();
$scope->Append($dateStamp);
$scope->Append('/');
$scope->Append($region);
$scope->Append('/s3/aws4_request');
$stringToSign->Clear();
$stringToSign->Append('AWS4-HMAC-SHA256\n');
$stringToSign->Append($amzDate);
$stringToSign->Append('\n');
$stringToSign->Append($scope->getAsString());
$stringToSign->Append('\n');
$stringToSign->Append($canonicalHash);
$signingKey->SetString('AWS4');
$signingKey->Append($credentials->stringOf('secret_key'));
$success = $signer->SetMacKeyString($signingKey->getAsString());
if ($success != 1) {
print 'Could not set signing key.' . "\n";
exit;
}
$derivedKey = $signer->macStringENC($dateStamp);
if ($signer->LastMethodSuccess != 1) {
print 'Could not derive signing key.' . "\n";
exit;
}
$success = $signer->SetMacKeyEncoded($derivedKey,'hex');
if ($success != 1) {
print 'Could not set signing key.' . "\n";
exit;
}
$derivedKey = $signer->macStringENC($region);
if ($signer->LastMethodSuccess != 1) {
print 'Could not derive signing key.' . "\n";
exit;
}
$success = $signer->SetMacKeyEncoded($derivedKey,'hex');
if ($success != 1) {
print 'Could not set signing key.' . "\n";
exit;
}
$derivedKey = $signer->macStringENC('s3');
if ($signer->LastMethodSuccess != 1) {
print 'Could not derive signing key.' . "\n";
exit;
}
$success = $signer->SetMacKeyEncoded($derivedKey,'hex');
if ($success != 1) {
print 'Could not set signing key.' . "\n";
exit;
}
$derivedKey = $signer->macStringENC('aws4_request');
if ($signer->LastMethodSuccess != 1) {
print 'Could not derive signing key.' . "\n";
exit;
}
$success = $signer->SetMacKeyEncoded($derivedKey,'hex');
if ($success != 1) {
print 'Could not set signing key.' . "\n";
exit;
}
$signature = $signer->macStringENC($stringToSign->getAsString());
if ($signer->LastMethodSuccess != 1) {
print 'Could not sign request.' . "\n";
exit;
}
$authorization->Clear();
$authorization->Append('AWS4-HMAC-SHA256 Credential=');
$authorization->Append($credentials->stringOf('access_key'));
$authorization->Append('/');
$authorization->Append($scope->getAsString());
$authorization->Append(', SignedHeaders=');
$authorization->Append($signedHeaders->getAsString());
$authorization->Append(', Signature=');
$authorization->Append($signature);
$http->SetRequestHeader('Authorization',$authorization->getAsString());
$url->SetString('https://');
$url->Append($host->getAsString());
$url->Append($uri->getAsString());
if ($query->Length > 0) {
$url->Append('?');
$url->Append($query->getAsString());
}
$success = $http->HttpNoBody('HEAD',$url->getAsString(),$response);
if (($success != 1) or ($response->StatusCode != 200)) {
print 'Request failed or returned unexpected HTTP status: ' . $response->StatusCode . "\n";
// Preserve progress. Inspect full diagnostics privately; do not log secrets.
exit;
}
$etag = $response->getHeaderField('ETag');
$stringCompare->SetString($etag);
$stringMatch5 = $stringCompare->ContentsEqual('',1);
if (($response->LastMethodSuccess != 1) or ($stringMatch5 == 1)) {
print 'Missing required response header ETag.' . "\n";
exit;
}
$expectedSize = $response->getHeaderField('Content-Length');
$stringCompare->SetString($expectedSize);
$stringMatch6 = $stringCompare->ContentsEqual('',1);
if (($response->LastMethodSuccess != 1) or ($stringMatch6 == 1)) {
print 'Missing required response header Content-Length.' . "\n";
exit;
}
$returnedVersion = $response->getHeaderField('x-amz-version-id');
if ($response->LastMethodSuccess != 1) {
$returnedVersion = '';
}
$stringCompare->SetString($versionId);
$stringMatch7 = $stringCompare->ContentsEqual('',1);
if ($stringMatch7 == 1) {
$versionId = $returnedVersion;
}
else {
$stringCompare->SetString($returnedVersion);
$stringMatch8 = $stringCompare->ContentsEqual($versionId,1);
if ($stringMatch8 != 1) {
print 'Unexpected object version.' . "\n";
exit;
}
}
$expectedChecksum = $response->getHeaderField('x-amz-checksum-sha256');
$stringCompare->SetString($expectedChecksum);
$stringMatch9 = $stringCompare->ContentsEqual('',1);
if (($response->LastMethodSuccess != 1) or ($stringMatch9 == 1)) {
print 'Missing required response header x-amz-checksum-sha256.' . "\n";
exit;
}
$checksumType = $response->getHeaderField('x-amz-checksum-type');
$stringCompare->SetString($checksumType);
$stringMatch10 = $stringCompare->ContentsEqual('',1);
if (($response->LastMethodSuccess != 1) or ($stringMatch10 == 1)) {
print 'Missing required response header x-amz-checksum-type.' . "\n";
exit;
}
$stringCompare->SetString($checksumType);
$stringMatch11 = $stringCompare->ContentsEqual('FULL_OBJECT',1);
if ($stringMatch11 != 1) {
print 'This example requires a FULL_OBJECT SHA-256 checksum; COMPOSITE needs separate verification.' . "\n";
exit;
}
$query->Clear();
$stringCompare->SetString($versionId);
$stringMatch12 = $stringCompare->ContentsEqual('',1);
if ($stringMatch12 != 1) {
if ($query->Length > 0) {
$query->Append('&');
}
$query->Append('versionId=');
$query->Append($http->urlEncode($versionId));
}
$http->ClearHeaders();
$success = $now->SetFromCurrentSystemTime();
if ($success != 1) {
print 'Could not read system time.' . "\n";
exit;
}
$timestamp->SetString($now->getAsTimestamp(0));
$replaceCount = $timestamp->Replace('-','');
$replaceCount = $timestamp->Replace(':','');
$amzDate = $timestamp->getAsString();
$dateStamp = $timestamp->getRange(0,8,0);
$payloadHash = $signer->hashStringENC('');
if ($signer->LastMethodSuccess != 1) {
print 'Could not hash payload.' . "\n";
exit;
}
$canonicalHeaders->Clear();
$signedHeaders->Clear();
if ($signedHeaders->Length > 0) {
$signedHeaders->Append(';');
}
$signedHeaders->Append('host');
$canonicalHeaders->Append('host:');
$canonicalHeaders->Append($host->getAsString());
$canonicalHeaders->Append('\n');
$http->SetRequestHeader('host',$host->getAsString());
if ($signedHeaders->Length > 0) {
$signedHeaders->Append(';');
}
$signedHeaders->Append('if-match');
$canonicalHeaders->Append('if-match:');
$canonicalHeaders->Append($etag);
$canonicalHeaders->Append('\n');
$http->SetRequestHeader('if-match',$etag);
if ($signedHeaders->Length > 0) {
$signedHeaders->Append(';');
}
$signedHeaders->Append('x-amz-checksum-mode');
$canonicalHeaders->Append('x-amz-checksum-mode:');
$canonicalHeaders->Append('ENABLED');
$canonicalHeaders->Append('\n');
$http->SetRequestHeader('x-amz-checksum-mode','ENABLED');
if ($signedHeaders->Length > 0) {
$signedHeaders->Append(';');
}
$signedHeaders->Append('x-amz-content-sha256');
$canonicalHeaders->Append('x-amz-content-sha256:');
$canonicalHeaders->Append($payloadHash);
$canonicalHeaders->Append('\n');
$http->SetRequestHeader('x-amz-content-sha256',$payloadHash);
if ($signedHeaders->Length > 0) {
$signedHeaders->Append(';');
}
$signedHeaders->Append('x-amz-date');
$canonicalHeaders->Append('x-amz-date:');
$canonicalHeaders->Append($amzDate);
$canonicalHeaders->Append('\n');
$http->SetRequestHeader('x-amz-date',$amzDate);
if ($credentials->HasMember('session_token') == 1) {
if ($signedHeaders->Length > 0) {
$signedHeaders->Append(';');
}
$signedHeaders->Append('x-amz-security-token');
$canonicalHeaders->Append('x-amz-security-token:');
$canonicalHeaders->Append($credentials->stringOf('session_token'));
$canonicalHeaders->Append('\n');
$http->SetRequestHeader('x-amz-security-token',$credentials->stringOf('session_token'));
}
$canonical->Clear();
$canonical->Append('GET\n');
$canonical->Append($uri->getAsString());
$canonical->Append('\n');
$canonical->Append($query->getAsString());
$canonical->Append('\n');
$canonical->Append($canonicalHeaders->getAsString());
$canonical->Append('\n');
$canonical->Append($signedHeaders->getAsString());
$canonical->Append('\n');
$canonical->Append($payloadHash);
$canonicalHash = $signer->hashStringENC($canonical->getAsString());
if ($signer->LastMethodSuccess != 1) {
print 'Could not hash canonical request.' . "\n";
exit;
}
$scope->Clear();
$scope->Append($dateStamp);
$scope->Append('/');
$scope->Append($region);
$scope->Append('/s3/aws4_request');
$stringToSign->Clear();
$stringToSign->Append('AWS4-HMAC-SHA256\n');
$stringToSign->Append($amzDate);
$stringToSign->Append('\n');
$stringToSign->Append($scope->getAsString());
$stringToSign->Append('\n');
$stringToSign->Append($canonicalHash);
$signingKey->SetString('AWS4');
$signingKey->Append($credentials->stringOf('secret_key'));
$success = $signer->SetMacKeyString($signingKey->getAsString());
if ($success != 1) {
print 'Could not set signing key.' . "\n";
exit;
}
$derivedKey = $signer->macStringENC($dateStamp);
if ($signer->LastMethodSuccess != 1) {
print 'Could not derive signing key.' . "\n";
exit;
}
$success = $signer->SetMacKeyEncoded($derivedKey,'hex');
if ($success != 1) {
print 'Could not set signing key.' . "\n";
exit;
}
$derivedKey = $signer->macStringENC($region);
if ($signer->LastMethodSuccess != 1) {
print 'Could not derive signing key.' . "\n";
exit;
}
$success = $signer->SetMacKeyEncoded($derivedKey,'hex');
if ($success != 1) {
print 'Could not set signing key.' . "\n";
exit;
}
$derivedKey = $signer->macStringENC('s3');
if ($signer->LastMethodSuccess != 1) {
print 'Could not derive signing key.' . "\n";
exit;
}
$success = $signer->SetMacKeyEncoded($derivedKey,'hex');
if ($success != 1) {
print 'Could not set signing key.' . "\n";
exit;
}
$derivedKey = $signer->macStringENC('aws4_request');
if ($signer->LastMethodSuccess != 1) {
print 'Could not derive signing key.' . "\n";
exit;
}
$success = $signer->SetMacKeyEncoded($derivedKey,'hex');
if ($success != 1) {
print 'Could not set signing key.' . "\n";
exit;
}
$signature = $signer->macStringENC($stringToSign->getAsString());
if ($signer->LastMethodSuccess != 1) {
print 'Could not sign request.' . "\n";
exit;
}
$authorization->Clear();
$authorization->Append('AWS4-HMAC-SHA256 Credential=');
$authorization->Append($credentials->stringOf('access_key'));
$authorization->Append('/');
$authorization->Append($scope->getAsString());
$authorization->Append(', SignedHeaders=');
$authorization->Append($signedHeaders->getAsString());
$authorization->Append(', Signature=');
$authorization->Append($signature);
$http->SetRequestHeader('Authorization',$authorization->getAsString());
$url->SetString('https://');
$url->Append($host->getAsString());
$url->Append($uri->getAsString());
if ($query->Length > 0) {
$url->Append('?');
$url->Append($query->getAsString());
}
$success = $http->Download($url->getAsString(),$partialPath);
if (($success != 1) or ($http->LastStatus != 200)) {
print 'Request failed or returned unexpected HTTP status: ' . $http->LastStatus . "\n";
// Preserve progress. Inspect full diagnostics privately; do not log secrets.
exit;
}
$received = new COM("Chilkat.Mime");
$success = $received->LoadMime($http->LastResponseHeader);
if ($success != 1) {
print 'Could not parse download headers.' . "\n";
exit;
}
$receivedSize = $received->getHeaderField('Content-Length');
$stringCompare->SetString($receivedSize);
$stringMatch13 = $stringCompare->ContentsEqual('',1);
if (($received->LastMethodSuccess != 1) or ($stringMatch13 == 1)) {
print 'Missing download header Content-Length.' . "\n";
exit;
}
$receivedHash = $received->getHeaderField('x-amz-checksum-sha256');
$stringCompare->SetString($receivedHash);
$stringMatch14 = $stringCompare->ContentsEqual('',1);
if (($received->LastMethodSuccess != 1) or ($stringMatch14 == 1)) {
print 'Missing download header x-amz-checksum-sha256.' . "\n";
exit;
}
$receivedType = $received->getHeaderField('x-amz-checksum-type');
$stringCompare->SetString($receivedType);
$stringMatch15 = $stringCompare->ContentsEqual('',1);
if (($received->LastMethodSuccess != 1) or ($stringMatch15 == 1)) {
print 'Missing download header x-amz-checksum-type.' . "\n";
exit;
}
$stringCompare->SetString($receivedSize);
$stringMatch16 = $stringCompare->ContentsEqual($expectedSize,1);
$stringCompare->SetString($receivedHash);
$stringMatch17 = $stringCompare->ContentsEqual($expectedChecksum,1);
$stringCompare->SetString($receivedType);
$stringMatch18 = $stringCompare->ContentsEqual('FULL_OBJECT',1);
if (($stringMatch16 != 1) or ($stringMatch17 != 1) or ($stringMatch18 != 1)) {
print 'Download metadata changed; preserve the temporary file.' . "\n";
exit;
}
$actualSize = $files->fileSizeStr($partialPath);
$stringCompare->SetString($actualSize);
$stringMatch19 = $stringCompare->ContentsEqual($expectedSize,1);
if (($files->LastMethodSuccess != 1) or ($stringMatch19 != 1)) {
print 'Downloaded size mismatch.' . "\n";
exit;
}
$digest = new COM("Chilkat.Crypt2");
$digest->HashAlgorithm = 'sha256';
$digest->EncodingMode = 'base64';
$actualChecksum = $digest->hashFileENC($partialPath);
$stringCompare->SetString($actualChecksum);
$stringMatch20 = $stringCompare->ContentsEqual($expectedChecksum,1);
if (($digest->LastMethodSuccess != 1) or ($stringMatch20 != 1)) {
print 'Downloaded checksum mismatch.' . "\n";
exit;
}
$success = $files->FileRename($partialPath,$finalPath);
if ($success != 1) {
print 'Verified download remains at the temporary path.' . "\n";
exit;
}
print 'Full-object SHA-256 download verified.' . "\n";
?>