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

S3 Http: Resume a Version-Pinned, Checksum-Verified Download

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.

Downloads an object with a stored FULL_OBJECT SHA-256 checksum in 8 MiB chunks. Start with a private empty cache and run one process. The checkpoint binds region, bucket, key, requested/selected version, ETag, size, checksum, chunk size and final path. On resume it reuses the saved version ID, so a newer current version does not silently replace the original target; null/unversioned objects still need the matching ETag and checksum.

Checks HTTP 206, exact Content-Range/Content-Length, ETag, version and actual bytes before committing each range. Rehashes cached chunks before reuse. Interrupted chunks are redownloaded; interrupted assembly is rebuilt. The assembled file must match the entire object's SHA-256 before final rename. Cached chunk hashes alone are not an S3 checksum of each range. HTTP 200, 412, 416, changed metadata, corrupt cache and checksum failures never promote output.

Use the companion SHA-256 upload to create a suitable object. Absent or COMPOSITE SHA-256 checksums stop explicitly. This fixed-size demonstration supports nonempty objects up to 10,000 chunks (78.125 GiB), with portable offsets beyond 2 GiB. Empty objects use the single checksum download. Larger objects need a suitably adjusted chunk size/checkpoint schema.

Requires s3:GetObject/s3:GetObjectVersion and relevant KMS permissions. Create qa_output; keep the same working directory and settings. Cache and final output must share a filesystem. Allow about twice the object size plus a temporary chunk in disk space. Protect manifests/receipts from other writers and retain them after failure. No automatic object replacement, restoration request, or deletion occurs.

AWS reference

Chilkat CkJava Downloads

CkJava
import com.chilkatsoft.*;

public class ChilkatExample {

  static {
    try {
        System.loadLibrary("chilkat");
    } catch (UnsatisfiedLinkError e) {
      System.err.println("Native code library failed to load.\n" + e);
      System.exit(1);
    }
  }

  public static void main(String argv[])
  {
    boolean success = false;

    CkStringBuilder stringCompare = new CkStringBuilder();
    //  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 = new CkJsonObject();
    credentials.put_Strict(true);
    success = credentials.LoadFile("qa_data/aws/s3.json");
    if (success != true) {
        System.out.println("Could not load private S3 credentials.");
        return;
        }

    stringCompare.SetString(credentials.stringOf("access_key"));
    boolean stringMatch1 = stringCompare.ContentsEqual("",true);
    if ((credentials.JsonTypeOf("access_key") != 1) || (stringMatch1 == true)) {
        System.out.println("Missing or invalid access_key.");
        return;
        }

    stringCompare.SetString(credentials.stringOf("secret_key"));
    boolean stringMatch2 = stringCompare.ContentsEqual("",true);
    if ((credentials.JsonTypeOf("secret_key") != 1) || (stringMatch2 == true)) {
        System.out.println("Missing or invalid secret_key.");
        return;
        }

    CkHttp http = new CkHttp();
    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"));
        boolean stringMatch3 = stringCompare.ContentsEqual("",true);
        if ((credentials.JsonTypeOf("session_token") != 1) || (stringMatch3 == true)) {
            System.out.println("session_token must be a nonempty string when supplied.");
            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.
    String region = "us-west-2";
    http.put_AwsRegion(region);
    CkStringBuilder endpoint = new CkStringBuilder();
    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.
    String bucketName = "your-bucket-name";
    String objectKey = "examples/archive.bin";
    CkHttpResponse response = new CkHttpResponse();
    CkCrypt2 signer = new CkCrypt2();
    signer.put_Charset("utf-8");
    signer.put_HashAlgorithm("sha256");
    signer.put_EncodingMode("hexlower");
    signer.put_MacAlgorithm("hmac");
    CkDateTime now = new CkDateTime();
    CkStringBuilder timestamp = new CkStringBuilder();
    CkStringBuilder canonical = new CkStringBuilder();
    CkStringBuilder canonicalHeaders = new CkStringBuilder();
    CkStringBuilder signedHeaders = new CkStringBuilder();
    CkStringBuilder scope = new CkStringBuilder();
    CkStringBuilder stringToSign = new CkStringBuilder();
    CkStringBuilder signingKey = new CkStringBuilder();
    CkStringBuilder authorization = new CkStringBuilder();
    CkStringBuilder url = new CkStringBuilder();
    CkStringBuilder query = new CkStringBuilder();
    CkStringBuilder number = new CkStringBuilder();
    CkStringBuilder host = new CkStringBuilder();
    CkStringBuilder uri = new CkStringBuilder();
    CkXml xml = new CkXml();
    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)) {
        System.out.println("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;
    CkFileAccess files = new CkFileAccess();
    String cacheDir = "qa_output/s3-download-cache";
    String manifestPath = "qa_output/s3-download-cache/state.json";
    String finalPath = "qa_output/s3-resumed.bin";
    String requestedVersionId = versionId;
    CkJsonObject state = new CkJsonObject();
    state.put_Strict(true);
    CkJsonObject identity = new CkJsonObject();
    boolean hasCheckpoint = files.FileExists(manifestPath);
    if (hasCheckpoint == true) {
        success = state.LoadFile(manifestPath);
        if (success != true) {
            System.out.println("Invalid download checkpoint. Preserve the cache.");
            return;
            }

        stringCompare.SetString(state.stringOf("schema"));
        boolean stringMatch4 = stringCompare.ContentsEqual("1",true);
        if (stringMatch4 != true) {
            System.out.println("Checkpoint settings differ. Use the original settings or a new empty cache.");
            return;
            }

        stringCompare.SetString(state.stringOf("bucket"));
        boolean stringMatch5 = stringCompare.ContentsEqual(bucketName,true);
        if (stringMatch5 != true) {
            System.out.println("Checkpoint settings differ. Use the original settings or a new empty cache.");
            return;
            }

        stringCompare.SetString(state.stringOf("key"));
        boolean stringMatch6 = stringCompare.ContentsEqual(objectKey,true);
        if (stringMatch6 != true) {
            System.out.println("Checkpoint settings differ. Use the original settings or a new empty cache.");
            return;
            }

        stringCompare.SetString(state.stringOf("region"));
        boolean stringMatch7 = stringCompare.ContentsEqual(region,true);
        if (stringMatch7 != true) {
            System.out.println("Checkpoint settings differ. Use the original settings or a new empty cache.");
            return;
            }

        stringCompare.SetString(state.stringOf("requestedVersion"));
        boolean stringMatch8 = stringCompare.ContentsEqual(requestedVersionId,true);
        if (stringMatch8 != true) {
            System.out.println("Checkpoint settings differ. Use the original settings or a new empty cache.");
            return;
            }

        stringCompare.SetString(state.stringOf("finalPath"));
        boolean stringMatch9 = stringCompare.ContentsEqual(finalPath,true);
        if (stringMatch9 != true) {
            System.out.println("Checkpoint settings differ. Use the original settings or a new empty cache.");
            return;
            }

        stringCompare.SetString(state.stringOf("chunkSize"));
        boolean stringMatch10 = stringCompare.ContentsEqual("8388608",true);
        if (stringMatch10 != true) {
            System.out.println("Checkpoint settings differ. Use the original settings or a new empty cache.");
            return;
            }

        versionId = state.stringOf("versionId");
        if (state.JsonTypeOf("versionId") != 1) {
            System.out.println("Checkpoint version ID is invalid.");
            return;
            }

        }

    query.Clear();
    stringCompare.SetString(versionId);
    boolean stringMatch11 = stringCompare.ContentsEqual("",true);
    if (stringMatch11 != true) {
        if (query.get_Length() > 0) {
            query.Append("&");
            }

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

    http.ClearHeaders();
    success = now.SetFromCurrentSystemTime();
    if (success != true) {
        System.out.println("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.get_LastMethodSuccess() != true) {
        System.out.println("Could not hash payload.");
        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("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.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("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.get_LastMethodSuccess() != true) {
        System.out.println("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) {
        System.out.println("Could not set signing key.");
        return;
        }

    derivedKey = signer.macStringENC(dateStamp);
    if (signer.get_LastMethodSuccess() != true) {
        System.out.println("Could not derive signing key.");
        return;
        }

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

    derivedKey = signer.macStringENC(region);
    if (signer.get_LastMethodSuccess() != true) {
        System.out.println("Could not derive signing key.");
        return;
        }

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

    derivedKey = signer.macStringENC("s3");
    if (signer.get_LastMethodSuccess() != true) {
        System.out.println("Could not derive signing key.");
        return;
        }

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

    derivedKey = signer.macStringENC("aws4_request");
    if (signer.get_LastMethodSuccess() != true) {
        System.out.println("Could not derive signing key.");
        return;
        }

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

    signature = signer.macStringENC(stringToSign.getAsString());
    if (signer.get_LastMethodSuccess() != true) {
        System.out.println("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.get_Length() > 0) {
        url.Append("?");
        url.Append(query.getAsString());
        }

    success = http.HttpNoBody("HEAD",url.getAsString(),response);
    if ((success != true) || (response.get_StatusCode() != 200)) {
        System.out.println("Request failed or returned unexpected HTTP status: " + response.get_StatusCode());
        //  Preserve progress. Inspect full diagnostics privately; do not log secrets.
        return;
        }

    etag = response.getHeaderField("ETag");
    stringCompare.SetString(etag);
    boolean stringMatch12 = stringCompare.ContentsEqual("",true);
    if ((response.get_LastMethodSuccess() != true) || (stringMatch12 == true)) {
        System.out.println("Missing required response header ETag.");
        return;
        }

    expectedSize = response.getHeaderField("Content-Length");
    stringCompare.SetString(expectedSize);
    boolean stringMatch13 = stringCompare.ContentsEqual("",true);
    if ((response.get_LastMethodSuccess() != true) || (stringMatch13 == true)) {
        System.out.println("Missing required response header Content-Length.");
        return;
        }

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

    stringCompare.SetString(versionId);
    boolean stringMatch14 = stringCompare.ContentsEqual("",true);
    if (stringMatch14 == true) {
        versionId = returnedVersion;
        }
    else {
        stringCompare.SetString(returnedVersion);
        boolean stringMatch15 = stringCompare.ContentsEqual(versionId,true);
        if (stringMatch15 != true) {
            System.out.println("Unexpected object version.");
            return;
            }

        }

    expectedChecksum = response.getHeaderField("x-amz-checksum-sha256");
    stringCompare.SetString(expectedChecksum);
    boolean stringMatch16 = stringCompare.ContentsEqual("",true);
    if ((response.get_LastMethodSuccess() != true) || (stringMatch16 == true)) {
        System.out.println("Missing required response header x-amz-checksum-sha256.");
        return;
        }

    checksumType = response.getHeaderField("x-amz-checksum-type");
    stringCompare.SetString(checksumType);
    boolean stringMatch17 = stringCompare.ContentsEqual("",true);
    if ((response.get_LastMethodSuccess() != true) || (stringMatch17 == true)) {
        System.out.println("Missing required response header x-amz-checksum-type.");
        return;
        }

    stringCompare.SetString(checksumType);
    boolean stringMatch18 = stringCompare.ContentsEqual("FULL_OBJECT",true);
    if (stringMatch18 != true) {
        System.out.println("This example requires a FULL_OBJECT SHA-256 checksum; COMPOSITE needs separate verification.");
        return;
        }

    //  Portable decimal long division; no 32-bit byte-offset overflow.
    int chunkSize = 8388608;
    int chunkCount = 0;
    int remainder = 0;
    int position = 0;
    CkStringBuilder sizeText = new CkStringBuilder();
    CkStringBuilder decimalDigits = new CkStringBuilder();
    CkStringBuilder digit = new CkStringBuilder();
    sizeText.Append(expectedSize);
    decimalDigits.Append("0123456789");
    if ((sizeText.get_Length() == 0) || (sizeText.get_Length() > 14)) {
        System.out.println("Invalid object size.");
        return;
        }

    while ((position < sizeText.get_Length())) {
        digit.SetString(sizeText.getRange(position,1,false));
        if (decimalDigits.Contains(digit.getAsString(),true) != true) {
            System.out.println("Invalid decimal object size.");
            return;
            }

        remainder = remainder * 10+digit.get_IntValue();
        chunkCount = chunkCount * 10;
        while ((remainder >= chunkSize)) {
            chunkCount = chunkCount+1;
            remainder = remainder - chunkSize;
            }

        position = position+1;
        }

    if (remainder != 0) {
        chunkCount = chunkCount+1;
        }

    if ((chunkCount < 1) || (chunkCount > 10000)) {
        System.out.println("Use a nonempty object of at most 10,000 fixed 8 MiB chunks; empty objects use the single-download example.");
        return;
        }

    success = identity.UpdateString("schema","1");
    if (success != true) {
        System.out.println("Could not save schema.");
        return;
        }

    success = identity.UpdateString("bucket",bucketName);
    if (success != true) {
        System.out.println("Could not save bucket.");
        return;
        }

    success = identity.UpdateString("key",objectKey);
    if (success != true) {
        System.out.println("Could not save key.");
        return;
        }

    success = identity.UpdateString("region",region);
    if (success != true) {
        System.out.println("Could not save region.");
        return;
        }

    success = identity.UpdateString("requestedVersion",requestedVersionId);
    if (success != true) {
        System.out.println("Could not save requestedVersion.");
        return;
        }

    success = identity.UpdateString("versionId",versionId);
    if (success != true) {
        System.out.println("Could not save versionId.");
        return;
        }

    success = identity.UpdateString("etag",etag);
    if (success != true) {
        System.out.println("Could not save etag.");
        return;
        }

    success = identity.UpdateString("size",expectedSize);
    if (success != true) {
        System.out.println("Could not save size.");
        return;
        }

    success = identity.UpdateString("checksum",expectedChecksum);
    if (success != true) {
        System.out.println("Could not save checksum.");
        return;
        }

    success = identity.UpdateString("finalPath",finalPath);
    if (success != true) {
        System.out.println("Could not save finalPath.");
        return;
        }

    success = identity.UpdateString("chunkSize","8388608");
    if (success != true) {
        System.out.println("Could not save chunkSize.");
        return;
        }

    if (hasCheckpoint == true) {
        stringCompare.SetString(state.stringOf("versionId"));
        boolean stringMatch19 = stringCompare.ContentsEqual(identity.stringOf("versionId"),true);
        if (stringMatch19 != true) {
            System.out.println("Object identity changed. Do not mix old cached bytes with this object.");
            return;
            }

        stringCompare.SetString(state.stringOf("etag"));
        boolean stringMatch20 = stringCompare.ContentsEqual(identity.stringOf("etag"),true);
        if (stringMatch20 != true) {
            System.out.println("Object identity changed. Do not mix old cached bytes with this object.");
            return;
            }

        stringCompare.SetString(state.stringOf("size"));
        boolean stringMatch21 = stringCompare.ContentsEqual(identity.stringOf("size"),true);
        if (stringMatch21 != true) {
            System.out.println("Object identity changed. Do not mix old cached bytes with this object.");
            return;
            }

        stringCompare.SetString(state.stringOf("checksum"));
        boolean stringMatch22 = stringCompare.ContentsEqual(identity.stringOf("checksum"),true);
        if (stringMatch22 != true) {
            System.out.println("Object identity changed. Do not mix old cached bytes with this object.");
            return;
            }

        }
    else {
        success = files.DirEnsureExists(cacheDir);
        if (success != true) {
            System.out.println("Could not create private cache.");
            return;
            }

        CkDirTree entries = new CkDirTree();
        entries.put_BaseDir(cacheDir);
        entries.put_Recurse(false);
        success = entries.BeginIterate();
        if ((success == true) || (entries.get_DoneIterating() != true)) {
            System.out.println("First download requires an empty, readable cache directory.");
            return;
            }

        success = identity.WriteFile("qa_output/s3-download-cache/state.json.tmp");
        if (success != true) {
            System.out.println("Could not save download identity.");
            return;
            }

        success = files.FileRename("qa_output/s3-download-cache/state.json.tmp",manifestPath);
        if (success != true) {
            System.out.println("Checkpoint remains at its temporary path.");
            return;
            }

        }

    CkCrypt2 digest = new CkCrypt2();
    digest.put_HashAlgorithm("sha256");
    digest.put_EncodingMode("base64");
    if (files.FileExists(finalPath) == true) {
        String existingSize = files.fileSizeStr(finalPath);
        String existingChecksum = digest.hashFileENC(finalPath);
        stringCompare.SetString(existingSize);
        boolean stringMatch23 = stringCompare.ContentsEqual(expectedSize,true);
        stringCompare.SetString(existingChecksum);
        boolean stringMatch24 = stringCompare.ContentsEqual(expectedChecksum,true);
        if ((digest.get_LastMethodSuccess() != true) || (stringMatch23 != true) || (stringMatch24 != true)) {
            System.out.println("Existing final file does not match; preserve it.");
            return;
            }

        System.out.println("Object already downloaded and checksum verified.");
        return;
        }

    digest.put_EncodingMode("hexlower");
    CkStringBuilder path = new CkStringBuilder();
    CkStringBuilder range = new CkStringBuilder();
    CkStringBuilder digits = new CkStringBuilder();
    CkStringBuilder rangeHeader = new CkStringBuilder();
    CkStringBuilder contentRange = new CkStringBuilder();
    CkStringBuilder byteCount = new CkStringBuilder();
    CkJsonObject receipt = new CkJsonObject();
    receipt.put_Strict(true);
    CkMime received = new CkMime();
    int chunkIndex = 0;
    int byteHigh = 0;
    int byteLow = 0;
    int endHigh;
    int endLow;
    String actualRange;
    String actualLength;
    String actualEtag;
    String actualVersion;
    String actualSize;
    String actualHash;
    while ((chunkIndex < chunkCount)) {
        int chunkBytes = chunkSize;
        if ((chunkIndex == chunkCount - 1) && (remainder != 0)) {
            chunkBytes = remainder;
            }

        range.Clear();
        digits.Clear();
        digits.AppendInt(byteLow);
        if (byteHigh > 0) {
            while ((digits.get_Length() < 9)) {
                digits.Prepend("0");
                }

            range.AppendInt(byteHigh);
            }

        range.Append(digits.getAsString());
        range.Append("-");
        endHigh = byteHigh;
        endLow = byteLow+chunkBytes - 1;
        if (endLow >= 1000000000) {
            endLow = endLow - 1000000000;
            endHigh = endHigh+1;
            }

        digits.Clear();
        digits.AppendInt(endLow);
        if (endHigh > 0) {
            while ((digits.get_Length() < 9)) {
                digits.Prepend("0");
                }

            range.AppendInt(endHigh);
            }

        range.Append(digits.getAsString());
        String rangeKey = range.getAsString();
        rangeHeader.SetString("bytes=");
        rangeHeader.Append(rangeKey);
        contentRange.SetString("bytes ");
        contentRange.Append(rangeKey);
        contentRange.Append("/");
        contentRange.Append(expectedSize);
        byteCount.Clear();
        byteCount.AppendInt(chunkBytes);
        path.SetString(cacheDir);
        path.Append("/chunk-");
        path.AppendInt(chunkIndex);
        String chunkPath = path.getAsString();
        path.Append(".json");
        String receiptPath = path.getAsString();
        path.SetString(chunkPath);
        path.Append(".part");
        String partialPath = path.getAsString();
        if (files.FileExists(chunkPath) == true) {
            success = receipt.LoadFile(receiptPath);
            if (success != true) {
                System.out.println("Cached chunk has no valid receipt. Preserve the cache.");
                return;
                }

            actualHash = digest.hashFileENC(chunkPath);
            stringCompare.SetString(actualHash);
            boolean stringMatch25 = stringCompare.ContentsEqual(receipt.stringOf("hash"),true);
            stringCompare.SetString(receipt.stringOf("range"));
            boolean stringMatch26 = stringCompare.ContentsEqual(rangeKey,true);
            stringCompare.SetString(files.fileSizeStr(chunkPath));
            boolean stringMatch27 = stringCompare.ContentsEqual(byteCount.getAsString(),true);
            if ((digest.get_LastMethodSuccess() != true) || (stringMatch25 != true) || (stringMatch26 != true) || (stringMatch27 != true)) {
                System.out.println("Cached chunk failed verification. Remove only this chunk and receipt before retrying.");
                return;
                }

            System.out.println("Reusing verified chunk: " + chunkIndex);
            }
        else {
            query.Clear();
            stringCompare.SetString(versionId);
            boolean stringMatch28 = stringCompare.ContentsEqual("",true);
            if (stringMatch28 != true) {
                if (query.get_Length() > 0) {
                    query.Append("&");
                    }

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

            http.ClearHeaders();
            success = now.SetFromCurrentSystemTime();
            if (success != true) {
                System.out.println("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.get_LastMethodSuccess() != true) {
                System.out.println("Could not hash payload.");
                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(etag);
            canonicalHeaders.Append("\n");
            http.SetRequestHeader("if-match",etag);
            if (signedHeaders.get_Length() > 0) {
                signedHeaders.Append(";");
                }

            signedHeaders.Append("range");
            canonicalHeaders.Append("range:");
            canonicalHeaders.Append(rangeHeader.getAsString());
            canonicalHeaders.Append("\n");
            http.SetRequestHeader("range",rangeHeader.getAsString());
            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) {
                System.out.println("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) {
                System.out.println("Could not set signing key.");
                return;
                }

            derivedKey = signer.macStringENC(dateStamp);
            if (signer.get_LastMethodSuccess() != true) {
                System.out.println("Could not derive signing key.");
                return;
                }

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

            derivedKey = signer.macStringENC(region);
            if (signer.get_LastMethodSuccess() != true) {
                System.out.println("Could not derive signing key.");
                return;
                }

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

            derivedKey = signer.macStringENC("s3");
            if (signer.get_LastMethodSuccess() != true) {
                System.out.println("Could not derive signing key.");
                return;
                }

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

            derivedKey = signer.macStringENC("aws4_request");
            if (signer.get_LastMethodSuccess() != true) {
                System.out.println("Could not derive signing key.");
                return;
                }

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

            signature = signer.macStringENC(stringToSign.getAsString());
            if (signer.get_LastMethodSuccess() != true) {
                System.out.println("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.get_Length() > 0) {
                url.Append("?");
                url.Append(query.getAsString());
                }

            success = http.Download(url.getAsString(),partialPath);
            if ((http.get_LastStatus() == 412) || (http.get_LastStatus() == 416)) {
                System.out.println("Object changed or range is invalid. Preserve the cache; do not append.");
                return;
                }

            if ((success != true) || (http.get_LastStatus() != 206)) {
                System.out.println("Request failed or returned unexpected HTTP status: " + http.get_LastStatus());
                //  Preserve progress. Inspect full diagnostics privately; do not log secrets.
                return;
                }

            success = received.LoadMime(http.lastResponseHeader());
            if (success != true) {
                System.out.println("Could not parse range response.");
                return;
                }

            actualRange = received.getHeaderField("Content-Range");
            stringCompare.SetString(actualRange);
            boolean stringMatch29 = stringCompare.ContentsEqual("",true);
            if ((received.get_LastMethodSuccess() != true) || (stringMatch29 == true)) {
                System.out.println("Missing download header Content-Range.");
                return;
                }

            actualLength = received.getHeaderField("Content-Length");
            stringCompare.SetString(actualLength);
            boolean stringMatch30 = stringCompare.ContentsEqual("",true);
            if ((received.get_LastMethodSuccess() != true) || (stringMatch30 == true)) {
                System.out.println("Missing download header Content-Length.");
                return;
                }

            actualEtag = received.getHeaderField("ETag");
            stringCompare.SetString(actualEtag);
            boolean stringMatch31 = stringCompare.ContentsEqual("",true);
            if ((received.get_LastMethodSuccess() != true) || (stringMatch31 == true)) {
                System.out.println("Missing download header ETag.");
                return;
                }

            stringCompare.SetString(actualRange);
            boolean stringMatch32 = stringCompare.ContentsEqual(contentRange.getAsString(),true);
            stringCompare.SetString(actualLength);
            boolean stringMatch33 = stringCompare.ContentsEqual(byteCount.getAsString(),true);
            stringCompare.SetString(actualEtag);
            boolean stringMatch34 = stringCompare.ContentsEqual(etag,true);
            if ((stringMatch32 != true) || (stringMatch33 != true) || (stringMatch34 != true)) {
                System.out.println("Unexpected range response; no chunk committed.");
                return;
                }

            stringCompare.SetString(versionId);
            boolean stringMatch35 = stringCompare.ContentsEqual("",true);
            if (stringMatch35 != true) {
                actualVersion = received.getHeaderField("x-amz-version-id");
                stringCompare.SetString(actualVersion);
                boolean stringMatch36 = stringCompare.ContentsEqual("",true);
                if ((received.get_LastMethodSuccess() != true) || (stringMatch36 == true)) {
                    System.out.println("Missing download header x-amz-version-id.");
                    return;
                    }

                stringCompare.SetString(actualVersion);
                boolean stringMatch37 = stringCompare.ContentsEqual(versionId,true);
                if (stringMatch37 != true) {
                    System.out.println("Unexpected returned version.");
                    return;
                    }

                }

            actualSize = files.fileSizeStr(partialPath);
            stringCompare.SetString(actualSize);
            boolean stringMatch38 = stringCompare.ContentsEqual(byteCount.getAsString(),true);
            if ((files.get_LastMethodSuccess() != true) || (stringMatch38 != true)) {
                System.out.println("Range byte count mismatch.");
                return;
                }

            actualHash = digest.hashFileENC(partialPath);
            if (digest.get_LastMethodSuccess() != true) {
                System.out.println("Could not hash range bytes.");
                return;
                }

            success = receipt.UpdateString("range",rangeKey);
            if (success != true) {
                System.out.println("Could not save range.");
                return;
                }

            success = receipt.UpdateString("hash",actualHash);
            if (success != true) {
                System.out.println("Could not save hash.");
                return;
                }

            success = receipt.WriteFile(receiptPath);
            if (success != true) {
                System.out.println("Could not save chunk receipt.");
                return;
                }

            success = files.FileRename(partialPath,chunkPath);
            if (success != true) {
                System.out.println("Could not commit downloaded chunk.");
                return;
                }

            System.out.println("Downloaded chunk: " + chunkIndex);
            }

        byteHigh = endHigh;
        byteLow = endLow+1;
        if (byteLow == 1000000000) {
            byteLow = 0;
            byteHigh = byteHigh+1;
            }

        chunkIndex = chunkIndex+1;
        }

    //  Cache hashes detect local damage, but only the final stored S3 checksum
    //  establishes whole-object integrity. A range is not verified by a full hash.
    String assembledPath = "qa_output/s3-download-cache/assembled.part";
    CkFileAccess assembled = new CkFileAccess();
    success = assembled.OpenForWrite(assembledPath);
    if (success != true) {
        System.out.println("Could not open assembly file.");
        return;
        }

    CkBinData data = new CkBinData();
    chunkIndex = 0;
    while ((chunkIndex < chunkCount)) {
        path.SetString(cacheDir);
        path.Append("/chunk-");
        path.AppendInt(chunkIndex);
        data.Clear();
        success = data.LoadFile(path.getAsString());
        if (success == true) {
            success = assembled.FileWriteBd(data,0,0);
            }

        if (success != true) {
            assembled.FileClose();
            System.out.println("Assembly failed; verified progress is retained.");
            return;
            }

        chunkIndex = chunkIndex+1;
        }

    assembled.FileClose();
    actualSize = files.fileSizeStr(assembledPath);
    digest.put_EncodingMode("base64");
    actualHash = digest.hashFileENC(assembledPath);
    stringCompare.SetString(actualSize);
    boolean stringMatch39 = stringCompare.ContentsEqual(expectedSize,true);
    stringCompare.SetString(actualHash);
    boolean stringMatch40 = stringCompare.ContentsEqual(expectedChecksum,true);
    if ((digest.get_LastMethodSuccess() != true) || (stringMatch39 != true) || (stringMatch40 != true)) {
        System.out.println("Assembled object checksum/size mismatch; final file not created.");
        return;
        }

    success = files.FileRename(assembledPath,finalPath);
    if (success != true) {
        System.out.println("Verified assembly remains in cache; rename failed.");
        return;
        }

    System.out.println("Resumable download completed and checksum verified. Cache retained for manual cleanup.");
  }
}