Sample code for 30+ languages & platforms
C# Requires Chilkat v11.6.0+

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.

AWS reference

Chilkat C# Downloads

C#
bool success = false;

Chilkat.StringBuilder stringCompare = new 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.
Chilkat.JsonObject credentials = new Chilkat.JsonObject();
credentials.Strict = true;
success = credentials.LoadFile("qa_data/aws/s3.json");
if (success != true) {
    Debug.WriteLine("Could not load private S3 credentials.");
    return;
}

stringCompare.SetString(credentials.StringOf("access_key"));
bool stringMatch1 = stringCompare.ContentsEqual("",true);
if ((credentials.JsonTypeOf("access_key") != 1) || (stringMatch1 == true)) {
    Debug.WriteLine("Missing or invalid access_key.");
    return;
}

stringCompare.SetString(credentials.StringOf("secret_key"));
bool stringMatch2 = stringCompare.ContentsEqual("",true);
if ((credentials.JsonTypeOf("secret_key") != 1) || (stringMatch2 == true)) {
    Debug.WriteLine("Missing or invalid secret_key.");
    return;
}

Chilkat.Http http = new Chilkat.Http();
http.AwsAccessKey = credentials.StringOf("access_key");
http.AwsSecretKey = credentials.StringOf("secret_key");
if (credentials.HasMember("session_token") == true) {
    stringCompare.SetString(credentials.StringOf("session_token"));
    bool stringMatch3 = stringCompare.ContentsEqual("",true);
    if ((credentials.JsonTypeOf("session_token") != 1) || (stringMatch3 == true)) {
        Debug.WriteLine("session_token must be a nonempty string when supplied.");
        return;
    }

    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.
string region = "us-west-2";
http.AwsRegion = region;
Chilkat.StringBuilder endpoint = new Chilkat.StringBuilder();
endpoint.Append("s3.");
endpoint.Append(region);
endpoint.Append(".amazonaws.com");
http.AwsEndpoint = endpoint.GetAsString();
http.RequireSslCertVerify = true;
http.FollowRedirects = false;
//  A region redirect is not success. Correct the endpoint and signing region.
string bucketName = "your-bucket-name";
string objectKey = "examples/archive.bin";
Chilkat.HttpResponse response = new Chilkat.HttpResponse();
Chilkat.Crypt2 signer = new Chilkat.Crypt2();
signer.Charset = "utf-8";
signer.HashAlgorithm = "sha256";
signer.EncodingMode = "hexlower";
signer.MacAlgorithm = "hmac";
Chilkat.CkDateTime now = new Chilkat.CkDateTime();
Chilkat.StringBuilder timestamp = new Chilkat.StringBuilder();
Chilkat.StringBuilder canonical = new Chilkat.StringBuilder();
Chilkat.StringBuilder canonicalHeaders = new Chilkat.StringBuilder();
Chilkat.StringBuilder signedHeaders = new Chilkat.StringBuilder();
Chilkat.StringBuilder scope = new Chilkat.StringBuilder();
Chilkat.StringBuilder stringToSign = new Chilkat.StringBuilder();
Chilkat.StringBuilder signingKey = new Chilkat.StringBuilder();
Chilkat.StringBuilder authorization = new Chilkat.StringBuilder();
Chilkat.StringBuilder url = new Chilkat.StringBuilder();
Chilkat.StringBuilder query = new Chilkat.StringBuilder();
Chilkat.StringBuilder number = new Chilkat.StringBuilder();
Chilkat.StringBuilder host = new Chilkat.StringBuilder();
Chilkat.StringBuilder uri = new Chilkat.StringBuilder();
Chilkat.Xml xml = new Chilkat.Xml();
string amzDate;
string dateStamp;
string payloadHash;
string canonicalHash;
string derivedKey;
string signature;
int replaceCount;
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("/",true) == true) || (uri.Contains("/../",true) == true) || (uri.Contains("/./",true) == true)) {
    Debug.WriteLine("Use a key without a leading slash or dot path segments for these examples.");
    return;
}

uri.Prepend("/");
string versionId = "";
string etag;
string expectedSize;
string expectedChecksum;
string checksumType;
string returnedVersion;
Chilkat.FileAccess files = new Chilkat.FileAccess();
string finalPath = "qa_output/s3-download.bin";
string partialPath = "qa_output/s3-download.bin.part";
if ((files.FileExists(finalPath) == true) || (files.FileExists(partialPath) == true)) {
    Debug.WriteLine("Choose unused output paths.");
    return;
}

query.Clear();
stringCompare.SetString(versionId);
bool stringMatch4 = stringCompare.ContentsEqual("",true);
if (stringMatch4 != true) {
    if (query.Length > 0) {
        query.Append("&");
    }

    query.Append("versionId=");
    query.Append(http.UrlEncode(versionId));
}

http.ClearHeaders();
success = now.SetFromCurrentSystemTime();
if (success != true) {
    Debug.WriteLine("Could not read system time.");
    return;
}

timestamp.SetString(now.GetAsTimestamp(false));
replaceCount = timestamp.Replace("-","");
replaceCount = timestamp.Replace(":","");
amzDate = timestamp.GetAsString();
dateStamp = timestamp.GetRange(0,8,false);
payloadHash = signer.HashStringENC("");
if (signer.LastMethodSuccess != true) {
    Debug.WriteLine("Could not hash payload.");
    return;
}

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") == true) {
    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 != true) {
    Debug.WriteLine("Could not hash canonical request.");
    return;
}

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 != true) {
    Debug.WriteLine("Could not set signing key.");
    return;
}

derivedKey = signer.MacStringENC(dateStamp);
if (signer.LastMethodSuccess != true) {
    Debug.WriteLine("Could not derive signing key.");
    return;
}

success = signer.SetMacKeyEncoded(derivedKey,"hex");
if (success != true) {
    Debug.WriteLine("Could not set signing key.");
    return;
}

derivedKey = signer.MacStringENC(region);
if (signer.LastMethodSuccess != true) {
    Debug.WriteLine("Could not derive signing key.");
    return;
}

success = signer.SetMacKeyEncoded(derivedKey,"hex");
if (success != true) {
    Debug.WriteLine("Could not set signing key.");
    return;
}

derivedKey = signer.MacStringENC("s3");
if (signer.LastMethodSuccess != true) {
    Debug.WriteLine("Could not derive signing key.");
    return;
}

success = signer.SetMacKeyEncoded(derivedKey,"hex");
if (success != true) {
    Debug.WriteLine("Could not set signing key.");
    return;
}

derivedKey = signer.MacStringENC("aws4_request");
if (signer.LastMethodSuccess != true) {
    Debug.WriteLine("Could not derive signing key.");
    return;
}

success = signer.SetMacKeyEncoded(derivedKey,"hex");
if (success != true) {
    Debug.WriteLine("Could not set signing key.");
    return;
}

signature = signer.MacStringENC(stringToSign.GetAsString());
if (signer.LastMethodSuccess != true) {
    Debug.WriteLine("Could not sign request.");
    return;
}

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 != true) || (response.StatusCode != 200)) {
    Debug.WriteLine("Request failed or returned unexpected HTTP status: " + Convert.ToString(response.StatusCode));
    //  Preserve progress. Inspect full diagnostics privately; do not log secrets.
    return;
}

etag = response.GetHeaderField("ETag");
stringCompare.SetString(etag);
bool stringMatch5 = stringCompare.ContentsEqual("",true);
if ((response.LastMethodSuccess != true) || (stringMatch5 == true)) {
    Debug.WriteLine("Missing required response header ETag.");
    return;
}

expectedSize = response.GetHeaderField("Content-Length");
stringCompare.SetString(expectedSize);
bool stringMatch6 = stringCompare.ContentsEqual("",true);
if ((response.LastMethodSuccess != true) || (stringMatch6 == true)) {
    Debug.WriteLine("Missing required response header Content-Length.");
    return;
}

returnedVersion = response.GetHeaderField("x-amz-version-id");
if (response.LastMethodSuccess != true) {
    returnedVersion = "";
}

stringCompare.SetString(versionId);
bool stringMatch7 = stringCompare.ContentsEqual("",true);
if (stringMatch7 == true) {
    versionId = returnedVersion;
}
else {
    stringCompare.SetString(returnedVersion);
    bool stringMatch8 = stringCompare.ContentsEqual(versionId,true);
    if (stringMatch8 != true) {
        Debug.WriteLine("Unexpected object version.");
        return;
    }

}

expectedChecksum = response.GetHeaderField("x-amz-checksum-sha256");
stringCompare.SetString(expectedChecksum);
bool stringMatch9 = stringCompare.ContentsEqual("",true);
if ((response.LastMethodSuccess != true) || (stringMatch9 == true)) {
    Debug.WriteLine("Missing required response header x-amz-checksum-sha256.");
    return;
}

checksumType = response.GetHeaderField("x-amz-checksum-type");
stringCompare.SetString(checksumType);
bool stringMatch10 = stringCompare.ContentsEqual("",true);
if ((response.LastMethodSuccess != true) || (stringMatch10 == true)) {
    Debug.WriteLine("Missing required response header x-amz-checksum-type.");
    return;
}

stringCompare.SetString(checksumType);
bool stringMatch11 = stringCompare.ContentsEqual("FULL_OBJECT",true);
if (stringMatch11 != true) {
    Debug.WriteLine("This example requires a FULL_OBJECT SHA-256 checksum; COMPOSITE needs separate verification.");
    return;
}

query.Clear();
stringCompare.SetString(versionId);
bool stringMatch12 = stringCompare.ContentsEqual("",true);
if (stringMatch12 != true) {
    if (query.Length > 0) {
        query.Append("&");
    }

    query.Append("versionId=");
    query.Append(http.UrlEncode(versionId));
}

http.ClearHeaders();
success = now.SetFromCurrentSystemTime();
if (success != true) {
    Debug.WriteLine("Could not read system time.");
    return;
}

timestamp.SetString(now.GetAsTimestamp(false));
replaceCount = timestamp.Replace("-","");
replaceCount = timestamp.Replace(":","");
amzDate = timestamp.GetAsString();
dateStamp = timestamp.GetRange(0,8,false);
payloadHash = signer.HashStringENC("");
if (signer.LastMethodSuccess != true) {
    Debug.WriteLine("Could not hash payload.");
    return;
}

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") == true) {
    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 != true) {
    Debug.WriteLine("Could not hash canonical request.");
    return;
}

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 != true) {
    Debug.WriteLine("Could not set signing key.");
    return;
}

derivedKey = signer.MacStringENC(dateStamp);
if (signer.LastMethodSuccess != true) {
    Debug.WriteLine("Could not derive signing key.");
    return;
}

success = signer.SetMacKeyEncoded(derivedKey,"hex");
if (success != true) {
    Debug.WriteLine("Could not set signing key.");
    return;
}

derivedKey = signer.MacStringENC(region);
if (signer.LastMethodSuccess != true) {
    Debug.WriteLine("Could not derive signing key.");
    return;
}

success = signer.SetMacKeyEncoded(derivedKey,"hex");
if (success != true) {
    Debug.WriteLine("Could not set signing key.");
    return;
}

derivedKey = signer.MacStringENC("s3");
if (signer.LastMethodSuccess != true) {
    Debug.WriteLine("Could not derive signing key.");
    return;
}

success = signer.SetMacKeyEncoded(derivedKey,"hex");
if (success != true) {
    Debug.WriteLine("Could not set signing key.");
    return;
}

derivedKey = signer.MacStringENC("aws4_request");
if (signer.LastMethodSuccess != true) {
    Debug.WriteLine("Could not derive signing key.");
    return;
}

success = signer.SetMacKeyEncoded(derivedKey,"hex");
if (success != true) {
    Debug.WriteLine("Could not set signing key.");
    return;
}

signature = signer.MacStringENC(stringToSign.GetAsString());
if (signer.LastMethodSuccess != true) {
    Debug.WriteLine("Could not sign request.");
    return;
}

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 != true) || (http.LastStatus != 200)) {
    Debug.WriteLine("Request failed or returned unexpected HTTP status: " + Convert.ToString(http.LastStatus));
    //  Preserve progress. Inspect full diagnostics privately; do not log secrets.
    return;
}

Chilkat.Mime received = new Chilkat.Mime();
success = received.LoadMime(http.LastResponseHeader);
if (success != true) {
    Debug.WriteLine("Could not parse download headers.");
    return;
}

string receivedSize;
string receivedHash;
string receivedType;
receivedSize = received.GetHeaderField("Content-Length");
stringCompare.SetString(receivedSize);
bool stringMatch13 = stringCompare.ContentsEqual("",true);
if ((received.LastMethodSuccess != true) || (stringMatch13 == true)) {
    Debug.WriteLine("Missing download header Content-Length.");
    return;
}

receivedHash = received.GetHeaderField("x-amz-checksum-sha256");
stringCompare.SetString(receivedHash);
bool stringMatch14 = stringCompare.ContentsEqual("",true);
if ((received.LastMethodSuccess != true) || (stringMatch14 == true)) {
    Debug.WriteLine("Missing download header x-amz-checksum-sha256.");
    return;
}

receivedType = received.GetHeaderField("x-amz-checksum-type");
stringCompare.SetString(receivedType);
bool stringMatch15 = stringCompare.ContentsEqual("",true);
if ((received.LastMethodSuccess != true) || (stringMatch15 == true)) {
    Debug.WriteLine("Missing download header x-amz-checksum-type.");
    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("FULL_OBJECT",true);
if ((stringMatch16 != true) || (stringMatch17 != true) || (stringMatch18 != true)) {
    Debug.WriteLine("Download metadata changed; preserve the temporary file.");
    return;
}

string actualSize = files.FileSizeStr(partialPath);
stringCompare.SetString(actualSize);
bool stringMatch19 = stringCompare.ContentsEqual(expectedSize,true);
if ((files.LastMethodSuccess != true) || (stringMatch19 != true)) {
    Debug.WriteLine("Downloaded size mismatch.");
    return;
}

Chilkat.Crypt2 digest = new Chilkat.Crypt2();
digest.HashAlgorithm = "sha256";
digest.EncodingMode = "base64";
string actualChecksum = digest.HashFileENC(partialPath);
stringCompare.SetString(actualChecksum);
bool stringMatch20 = stringCompare.ContentsEqual(expectedChecksum,true);
if ((digest.LastMethodSuccess != true) || (stringMatch20 != true)) {
    Debug.WriteLine("Downloaded checksum mismatch.");
    return;
}

success = files.FileRename(partialPath,finalPath);
if (success != true) {
    Debug.WriteLine("Verified download remains at the temporary path.");
    return;
}

Debug.WriteLine("Full-object SHA-256 download verified.");