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

S3 Http: Download Only If the ETag Still Matches

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.

Uses an exact quoted ETag as an If-Match validator, handles 412 without promoting output, and verifies returned ETag and byte count before renaming. ETag is a validator, not necessarily MD5. This is not checksum verification; use the dedicated checksum example for integrity validation. Requires s3:GetObject and applicable KMS permissions. For immutable identity across overwrites, select a version ID.

AWS reference

Chilkat C++ Downloads

C++
#include <CkStringBuilder.h>
#include <CkJsonObject.h>
#include <CkHttp.h>
#include <CkHttpResponse.h>
#include <CkCrypt2.h>
#include <CkDateTime.h>
#include <CkXml.h>
#include <CkFileAccess.h>
#include <CkMime.h>

void ChilkatSample(void)
    {
    bool success = false;

    CkStringBuilder 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.
    CkJsonObject credentials;
    credentials.put_Strict(true);
    success = credentials.LoadFile("qa_data/aws/s3.json");
    if (success != true) {
        std::cout << "Could not load private S3 credentials." << "\r\n";
        return;
    }

    stringCompare.SetString(credentials.stringOf("access_key"));
    bool stringMatch1 = stringCompare.ContentsEqual("",true);
    if ((credentials.JsonTypeOf("access_key") != 1) || (stringMatch1 == true)) {
        std::cout << "Missing or invalid access_key." << "\r\n";
        return;
    }

    stringCompare.SetString(credentials.stringOf("secret_key"));
    bool stringMatch2 = stringCompare.ContentsEqual("",true);
    if ((credentials.JsonTypeOf("secret_key") != 1) || (stringMatch2 == true)) {
        std::cout << "Missing or invalid secret_key." << "\r\n";
        return;
    }

    CkHttp http;
    http.put_AwsAccessKey(credentials.stringOf("access_key"));
    http.put_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)) {
            std::cout << "session_token must be a nonempty string when supplied." << "\r\n";
            return;
        }

        http.put_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.
    const char *region = "us-west-2";
    http.put_AwsRegion(region);
    CkStringBuilder endpoint;
    endpoint.Append("s3.");
    endpoint.Append(region);
    endpoint.Append(".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 char *bucketName = "your-bucket-name";
    const char *objectKey = "examples/archive.bin";
    CkHttpResponse response;
    CkCrypt2 signer;
    signer.put_Charset("utf-8");
    signer.put_HashAlgorithm("sha256");
    signer.put_EncodingMode("hexlower");
    signer.put_MacAlgorithm("hmac");
    CkDateTime now;
    CkStringBuilder timestamp;
    CkStringBuilder canonical;
    CkStringBuilder canonicalHeaders;
    CkStringBuilder signedHeaders;
    CkStringBuilder scope;
    CkStringBuilder stringToSign;
    CkStringBuilder signingKey;
    CkStringBuilder authorization;
    CkStringBuilder url;
    CkStringBuilder query;
    CkStringBuilder number;
    CkStringBuilder host;
    CkStringBuilder uri;
    CkXml xml;
    const char *amzDate = 0;
    const char *dateStamp = 0;
    const char *payloadHash = 0;
    const char *canonicalHash = 0;
    const char *derivedKey = 0;
    const char *signature = 0;
    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)) {
        std::cout << "Use a key without a leading slash or dot path segments for these examples." << "\r\n";
        return;
    }

    uri.Prepend("/");
    CkFileAccess files;
    const char *finalPath = "qa_output/s3-download.bin";
    const char *partialPath = "qa_output/s3-download.bin.part";
    if ((files.FileExists(finalPath) == true) || (files.FileExists(partialPath) == true)) {
        std::cout << "Choose unused output paths." << "\r\n";
        return;
    }

    //  Copy the exact quoted ETag from a previous HEAD/GET.
    const char *expectedEtag = "\"YOUR_ETAG\"";
    query.Clear();
    http.ClearHeaders();
    success = now.SetFromCurrentSystemTime();
    if (success != true) {
        std::cout << "Could not read system time." << "\r\n";
        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.get_LastMethodSuccess() != true) {
        std::cout << "Could not hash payload." << "\r\n";
        return;
    }

    canonicalHeaders.Clear();
    signedHeaders.Clear();
    if (signedHeaders.get_Length() > 0) {
        signedHeaders.Append(";");
    }

    signedHeaders.Append("host");
    canonicalHeaders.Append("host:");
    canonicalHeaders.Append(host.getAsString());
    canonicalHeaders.Append("\n");
    http.SetRequestHeader("host",host.getAsString());
    if (signedHeaders.get_Length() > 0) {
        signedHeaders.Append(";");
    }

    signedHeaders.Append("if-match");
    canonicalHeaders.Append("if-match:");
    canonicalHeaders.Append(expectedEtag);
    canonicalHeaders.Append("\n");
    http.SetRequestHeader("if-match",expectedEtag);
    if (signedHeaders.get_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.get_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.get_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.get_LastMethodSuccess() != true) {
        std::cout << "Could not hash canonical request." << "\r\n";
        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) {
        std::cout << "Could not set signing key." << "\r\n";
        return;
    }

    derivedKey = signer.macStringENC(dateStamp);
    if (signer.get_LastMethodSuccess() != true) {
        std::cout << "Could not derive signing key." << "\r\n";
        return;
    }

    success = signer.SetMacKeyEncoded(derivedKey,"hex");
    if (success != true) {
        std::cout << "Could not set signing key." << "\r\n";
        return;
    }

    derivedKey = signer.macStringENC(region);
    if (signer.get_LastMethodSuccess() != true) {
        std::cout << "Could not derive signing key." << "\r\n";
        return;
    }

    success = signer.SetMacKeyEncoded(derivedKey,"hex");
    if (success != true) {
        std::cout << "Could not set signing key." << "\r\n";
        return;
    }

    derivedKey = signer.macStringENC("s3");
    if (signer.get_LastMethodSuccess() != true) {
        std::cout << "Could not derive signing key." << "\r\n";
        return;
    }

    success = signer.SetMacKeyEncoded(derivedKey,"hex");
    if (success != true) {
        std::cout << "Could not set signing key." << "\r\n";
        return;
    }

    derivedKey = signer.macStringENC("aws4_request");
    if (signer.get_LastMethodSuccess() != true) {
        std::cout << "Could not derive signing key." << "\r\n";
        return;
    }

    success = signer.SetMacKeyEncoded(derivedKey,"hex");
    if (success != true) {
        std::cout << "Could not set signing key." << "\r\n";
        return;
    }

    signature = signer.macStringENC(stringToSign.getAsString());
    if (signer.get_LastMethodSuccess() != true) {
        std::cout << "Could not sign request." << "\r\n";
        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.get_Length() > 0) {
        url.Append("?");
        url.Append(query.getAsString());
    }

    success = http.Download(url.getAsString(),partialPath);
    if (http.get_LastStatus() == 412) {
        std::cout << "Object changed; conditional download was not applied." << "\r\n";
        return;
    }

    if ((success != true) || (http.get_LastStatus() != 200)) {
        std::cout << "Request failed or returned unexpected HTTP status: " << http.get_LastStatus() << "\r\n";
        //  Preserve progress. Inspect full diagnostics privately; do not log secrets.
        return;
    }

    CkMime received;
    success = received.LoadMime(http.lastResponseHeader());
    if (success != true) {
        std::cout << "Could not parse download headers." << "\r\n";
        return;
    }

    const char *responseEtag = 0;
    const char *expectedSize = 0;
    responseEtag = received.getHeaderField("ETag");
    stringCompare.SetString(responseEtag);
    bool stringMatch4 = stringCompare.ContentsEqual("",true);
    if ((received.get_LastMethodSuccess() != true) || (stringMatch4 == true)) {
        std::cout << "Missing download header ETag." << "\r\n";
        return;
    }

    expectedSize = received.getHeaderField("Content-Length");
    stringCompare.SetString(expectedSize);
    bool stringMatch5 = stringCompare.ContentsEqual("",true);
    if ((received.get_LastMethodSuccess() != true) || (stringMatch5 == true)) {
        std::cout << "Missing download header Content-Length." << "\r\n";
        return;
    }

    stringCompare.SetString(responseEtag);
    bool stringMatch6 = stringCompare.ContentsEqual(expectedEtag,true);
    if (stringMatch6 != true) {
        std::cout << "Returned ETag differs." << "\r\n";
        return;
    }

    const char *actualSize = files.fileSizeStr(partialPath);
    stringCompare.SetString(actualSize);
    bool stringMatch7 = stringCompare.ContentsEqual(expectedSize,true);
    if ((files.get_LastMethodSuccess() != true) || (stringMatch7 != true)) {
        std::cout << "Downloaded size mismatch." << "\r\n";
        return;
    }

    success = files.FileRename(partialPath,finalPath);
    if (success != true) {
        std::cout << "Downloaded file remains at its temporary path." << "\r\n";
        return;
    }

    std::cout << "Conditional download succeeded." << "\r\n";
    }