Sample code for 30+ languages & platforms
Objective-C 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 Objective-C Downloads

Objective-C
#import <CkoStringBuilder.h>
#import <CkoJsonObject.h>
#import <CkoHttp.h>
#import <NSString.h>
#import <CkoHttpResponse.h>
#import <CkoCrypt2.h>
#import <CkoDateTime.h>
#import <CkoXml.h>
#import <CkoFileAccess.h>
#import <CkoDirTree.h>
#import <CkoMime.h>
#import <CkoBinData.h>

BOOL success = NO;

CkoStringBuilder *stringCompare = [[CkoStringBuilder alloc] init];
//  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.
CkoJsonObject *credentials = [[CkoJsonObject alloc] init];
credentials.Strict = YES;
success = [credentials LoadFile: @"qa_data/aws/s3.json"];
if (success != YES) {
    NSLog(@"%@",@"Could not load private S3 credentials.");
    return;
}

[stringCompare SetString: [credentials StringOf: @"access_key"]];
BOOL stringMatch1 = [stringCompare ContentsEqual: @"" caseSensitive: YES];
if (([[credentials JsonTypeOf: @"access_key"] intValue] != 1) || (stringMatch1 == YES)) {
    NSLog(@"%@",@"Missing or invalid access_key.");
    return;
}

[stringCompare SetString: [credentials StringOf: @"secret_key"]];
BOOL stringMatch2 = [stringCompare ContentsEqual: @"" caseSensitive: YES];
if (([[credentials JsonTypeOf: @"secret_key"] intValue] != 1) || (stringMatch2 == YES)) {
    NSLog(@"%@",@"Missing or invalid secret_key.");
    return;
}

CkoHttp *http = [[CkoHttp alloc] init];
http.AwsAccessKey = [credentials StringOf: @"access_key"];
http.AwsSecretKey = [credentials StringOf: @"secret_key"];
if ([credentials HasMember: @"session_token"] == YES) {
    [stringCompare SetString: [credentials StringOf: @"session_token"]];
    BOOL stringMatch3 = [stringCompare ContentsEqual: @"" caseSensitive: YES];
    if (([[credentials JsonTypeOf: @"session_token"] intValue] != 1) || (stringMatch3 == YES)) {
        NSLog(@"%@",@"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.
NSString *region = @"us-west-2";
http.AwsRegion = region;
CkoStringBuilder *endpoint = [[CkoStringBuilder alloc] init];
[endpoint Append: @"s3."];
[endpoint Append: region];
[endpoint Append: @".amazonaws.com"];
http.AwsEndpoint = [endpoint GetAsString];
http.RequireSslCertVerify = YES;
http.FollowRedirects = NO;
//  A region redirect is not success. Correct the endpoint and signing region.
NSString *bucketName = @"your-bucket-name";
NSString *objectKey = @"examples/archive.bin";
CkoHttpResponse *response = [[CkoHttpResponse alloc] init];
CkoCrypt2 *signer = [[CkoCrypt2 alloc] init];
signer.Charset = @"utf-8";
signer.HashAlgorithm = @"sha256";
signer.EncodingMode = @"hexlower";
signer.MacAlgorithm = @"hmac";
CkoDateTime *now = [[CkoDateTime alloc] init];
CkoStringBuilder *timestamp = [[CkoStringBuilder alloc] init];
CkoStringBuilder *canonical = [[CkoStringBuilder alloc] init];
CkoStringBuilder *canonicalHeaders = [[CkoStringBuilder alloc] init];
CkoStringBuilder *signedHeaders = [[CkoStringBuilder alloc] init];
CkoStringBuilder *scope = [[CkoStringBuilder alloc] init];
CkoStringBuilder *stringToSign = [[CkoStringBuilder alloc] init];
CkoStringBuilder *signingKey = [[CkoStringBuilder alloc] init];
CkoStringBuilder *authorization = [[CkoStringBuilder alloc] init];
CkoStringBuilder *url = [[CkoStringBuilder alloc] init];
CkoStringBuilder *query = [[CkoStringBuilder alloc] init];
CkoStringBuilder *number = [[CkoStringBuilder alloc] init];
CkoStringBuilder *host = [[CkoStringBuilder alloc] init];
CkoStringBuilder *uri = [[CkoStringBuilder alloc] init];
CkoXml *xml = [[CkoXml alloc] init];
NSString *amzDate = 0;
NSString *dateStamp = 0;
NSString *payloadHash = 0;
NSString *canonicalHash = 0;
NSString *derivedKey = 0;
NSString *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" replacement: @"/"] intValue];
if (([uri StartsWith: @"/" caseSensitive: YES] == YES) || ([uri Contains: @"/../" caseSensitive: YES] == YES) || ([uri Contains: @"/./" caseSensitive: YES] == YES)) {
    NSLog(@"%@",@"Use a key without a leading slash or dot path segments for these examples.");
    return;
}

[uri Prepend: @"/"];
NSString *versionId = @"";
NSString *etag = 0;
NSString *expectedSize = 0;
NSString *expectedChecksum = 0;
NSString *checksumType = 0;
NSString *returnedVersion = 0;
CkoFileAccess *files = [[CkoFileAccess alloc] init];
NSString *cacheDir = @"qa_output/s3-download-cache";
NSString *manifestPath = @"qa_output/s3-download-cache/state.json";
NSString *finalPath = @"qa_output/s3-resumed.bin";
NSString *requestedVersionId = versionId;
CkoJsonObject *state = [[CkoJsonObject alloc] init];
state.Strict = YES;
CkoJsonObject *identity = [[CkoJsonObject alloc] init];
BOOL hasCheckpoint = [files FileExists: manifestPath];
if (hasCheckpoint == YES) {
    success = [state LoadFile: manifestPath];
    if (success != YES) {
        NSLog(@"%@",@"Invalid download checkpoint. Preserve the cache.");
        return;
    }

    [stringCompare SetString: [state StringOf: @"schema"]];
    BOOL stringMatch4 = [stringCompare ContentsEqual: @"1" caseSensitive: YES];
    if (stringMatch4 != YES) {
        NSLog(@"%@",@"Checkpoint settings differ. Use the original settings or a new empty cache.");
        return;
    }

    [stringCompare SetString: [state StringOf: @"bucket"]];
    BOOL stringMatch5 = [stringCompare ContentsEqual: bucketName caseSensitive: YES];
    if (stringMatch5 != YES) {
        NSLog(@"%@",@"Checkpoint settings differ. Use the original settings or a new empty cache.");
        return;
    }

    [stringCompare SetString: [state StringOf: @"key"]];
    BOOL stringMatch6 = [stringCompare ContentsEqual: objectKey caseSensitive: YES];
    if (stringMatch6 != YES) {
        NSLog(@"%@",@"Checkpoint settings differ. Use the original settings or a new empty cache.");
        return;
    }

    [stringCompare SetString: [state StringOf: @"region"]];
    BOOL stringMatch7 = [stringCompare ContentsEqual: region caseSensitive: YES];
    if (stringMatch7 != YES) {
        NSLog(@"%@",@"Checkpoint settings differ. Use the original settings or a new empty cache.");
        return;
    }

    [stringCompare SetString: [state StringOf: @"requestedVersion"]];
    BOOL stringMatch8 = [stringCompare ContentsEqual: requestedVersionId caseSensitive: YES];
    if (stringMatch8 != YES) {
        NSLog(@"%@",@"Checkpoint settings differ. Use the original settings or a new empty cache.");
        return;
    }

    [stringCompare SetString: [state StringOf: @"finalPath"]];
    BOOL stringMatch9 = [stringCompare ContentsEqual: finalPath caseSensitive: YES];
    if (stringMatch9 != YES) {
        NSLog(@"%@",@"Checkpoint settings differ. Use the original settings or a new empty cache.");
        return;
    }

    [stringCompare SetString: [state StringOf: @"chunkSize"]];
    BOOL stringMatch10 = [stringCompare ContentsEqual: @"8388608" caseSensitive: YES];
    if (stringMatch10 != YES) {
        NSLog(@"%@",@"Checkpoint settings differ. Use the original settings or a new empty cache.");
        return;
    }

    versionId = [state StringOf: @"versionId"];
    if ([[state JsonTypeOf: @"versionId"] intValue] != 1) {
        NSLog(@"%@",@"Checkpoint version ID is invalid.");
        return;
    }

}

[query Clear];
[stringCompare SetString: versionId];
BOOL stringMatch11 = [stringCompare ContentsEqual: @"" caseSensitive: YES];
if (stringMatch11 != YES) {
    if ([query.Length intValue] > 0) {
        [query Append: @"&"];
    }

    [query Append: @"versionId="];
    [query Append: [http UrlEncode: versionId]];
}

[http ClearHeaders];
success = [now SetFromCurrentSystemTime];
if (success != YES) {
    NSLog(@"%@",@"Could not read system time.");
    return;
}

[timestamp SetString: [now GetAsTimestamp: NO]];
replaceCount = [[timestamp Replace: @"-" replacement: @""] intValue];
replaceCount = [[timestamp Replace: @":" replacement: @""] intValue];
amzDate = [timestamp GetAsString];
dateStamp = [timestamp GetRange: [NSNumber numberWithInt: 0] numChars: [NSNumber numberWithInt: 8] removeFlag: NO];
payloadHash = [signer HashStringENC: @""];
if (signer.LastMethodSuccess != YES) {
    NSLog(@"%@",@"Could not hash payload.");
    return;
}

[canonicalHeaders Clear];
[signedHeaders Clear];
if ([signedHeaders.Length intValue] > 0) {
    [signedHeaders Append: @";"];
}

[signedHeaders Append: @"host"];
[canonicalHeaders Append: @"host:"];
[canonicalHeaders Append: [host GetAsString]];
[canonicalHeaders Append: @"\n"];
[http SetRequestHeader: @"host" value: [host GetAsString]];
if ([signedHeaders.Length intValue] > 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" value: @"ENABLED"];
if ([signedHeaders.Length intValue] > 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" value: payloadHash];
if ([signedHeaders.Length intValue] > 0) {
    [signedHeaders Append: @";"];
}

[signedHeaders Append: @"x-amz-date"];
[canonicalHeaders Append: @"x-amz-date:"];
[canonicalHeaders Append: amzDate];
[canonicalHeaders Append: @"\n"];
[http SetRequestHeader: @"x-amz-date" value: amzDate];
if ([credentials HasMember: @"session_token"] == YES) {
    if ([signedHeaders.Length intValue] > 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" value: [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 != YES) {
    NSLog(@"%@",@"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 != YES) {
    NSLog(@"%@",@"Could not set signing key.");
    return;
}

derivedKey = [signer MacStringENC: dateStamp];
if (signer.LastMethodSuccess != YES) {
    NSLog(@"%@",@"Could not derive signing key.");
    return;
}

success = [signer SetMacKeyEncoded: derivedKey encoding: @"hex"];
if (success != YES) {
    NSLog(@"%@",@"Could not set signing key.");
    return;
}

derivedKey = [signer MacStringENC: region];
if (signer.LastMethodSuccess != YES) {
    NSLog(@"%@",@"Could not derive signing key.");
    return;
}

success = [signer SetMacKeyEncoded: derivedKey encoding: @"hex"];
if (success != YES) {
    NSLog(@"%@",@"Could not set signing key.");
    return;
}

derivedKey = [signer MacStringENC: @"s3"];
if (signer.LastMethodSuccess != YES) {
    NSLog(@"%@",@"Could not derive signing key.");
    return;
}

success = [signer SetMacKeyEncoded: derivedKey encoding: @"hex"];
if (success != YES) {
    NSLog(@"%@",@"Could not set signing key.");
    return;
}

derivedKey = [signer MacStringENC: @"aws4_request"];
if (signer.LastMethodSuccess != YES) {
    NSLog(@"%@",@"Could not derive signing key.");
    return;
}

success = [signer SetMacKeyEncoded: derivedKey encoding: @"hex"];
if (success != YES) {
    NSLog(@"%@",@"Could not set signing key.");
    return;
}

signature = [signer MacStringENC: [stringToSign GetAsString]];
if (signer.LastMethodSuccess != YES) {
    NSLog(@"%@",@"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" value: [authorization GetAsString]];
[url SetString: @"https://"];
[url Append: [host GetAsString]];
[url Append: [uri GetAsString]];
if ([query.Length intValue] > 0) {
    [url Append: @"?"];
    [url Append: [query GetAsString]];
}

success = [http HttpNoBody: @"HEAD" url: [url GetAsString] response: response];
if ((success != YES) || ([response.StatusCode intValue] != 200)) {
    NSLog(@"%@%d",@"Request failed or returned unexpected HTTP status: ",[response.StatusCode intValue]);
    //  Preserve progress. Inspect full diagnostics privately; do not log secrets.
    return;
}

etag = [response GetHeaderField: @"ETag"];
[stringCompare SetString: etag];
BOOL stringMatch12 = [stringCompare ContentsEqual: @"" caseSensitive: YES];
if ((response.LastMethodSuccess != YES) || (stringMatch12 == YES)) {
    NSLog(@"%@",@"Missing required response header ETag.");
    return;
}

expectedSize = [response GetHeaderField: @"Content-Length"];
[stringCompare SetString: expectedSize];
BOOL stringMatch13 = [stringCompare ContentsEqual: @"" caseSensitive: YES];
if ((response.LastMethodSuccess != YES) || (stringMatch13 == YES)) {
    NSLog(@"%@",@"Missing required response header Content-Length.");
    return;
}

returnedVersion = [response GetHeaderField: @"x-amz-version-id"];
if (response.LastMethodSuccess != YES) {
    returnedVersion = @"";
}

[stringCompare SetString: versionId];
BOOL stringMatch14 = [stringCompare ContentsEqual: @"" caseSensitive: YES];
if (stringMatch14 == YES) {
    versionId = returnedVersion;
}
else {
    [stringCompare SetString: returnedVersion];
    BOOL stringMatch15 = [stringCompare ContentsEqual: versionId caseSensitive: YES];
    if (stringMatch15 != YES) {
        NSLog(@"%@",@"Unexpected object version.");
        return;
    }

}

expectedChecksum = [response GetHeaderField: @"x-amz-checksum-sha256"];
[stringCompare SetString: expectedChecksum];
BOOL stringMatch16 = [stringCompare ContentsEqual: @"" caseSensitive: YES];
if ((response.LastMethodSuccess != YES) || (stringMatch16 == YES)) {
    NSLog(@"%@",@"Missing required response header x-amz-checksum-sha256.");
    return;
}

checksumType = [response GetHeaderField: @"x-amz-checksum-type"];
[stringCompare SetString: checksumType];
BOOL stringMatch17 = [stringCompare ContentsEqual: @"" caseSensitive: YES];
if ((response.LastMethodSuccess != YES) || (stringMatch17 == YES)) {
    NSLog(@"%@",@"Missing required response header x-amz-checksum-type.");
    return;
}

[stringCompare SetString: checksumType];
BOOL stringMatch18 = [stringCompare ContentsEqual: @"FULL_OBJECT" caseSensitive: YES];
if (stringMatch18 != YES) {
    NSLog(@"%@",@"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;
CkoStringBuilder *sizeText = [[CkoStringBuilder alloc] init];
CkoStringBuilder *decimalDigits = [[CkoStringBuilder alloc] init];
CkoStringBuilder *digit = [[CkoStringBuilder alloc] init];
[sizeText Append: expectedSize];
[decimalDigits Append: @"0123456789"];
if (([sizeText.Length intValue] == 0) || ([sizeText.Length intValue] > 14)) {
    NSLog(@"%@",@"Invalid object size.");
    return;
}

while ((position < [sizeText.Length intValue])) {
    [digit SetString: [sizeText GetRange: [NSNumber numberWithInt: position] numChars: [NSNumber numberWithInt: 1] removeFlag: NO]];
    if ([decimalDigits Contains: [digit GetAsString] caseSensitive: YES] != YES) {
        NSLog(@"%@",@"Invalid decimal object size.");
        return;
    }

    remainder = remainder * 10 + [digit.IntValue 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)) {
    NSLog(@"%@",@"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" value: @"1"];
if (success != YES) {
    NSLog(@"%@",@"Could not save schema.");
    return;
}

success = [identity UpdateString: @"bucket" value: bucketName];
if (success != YES) {
    NSLog(@"%@",@"Could not save bucket.");
    return;
}

success = [identity UpdateString: @"key" value: objectKey];
if (success != YES) {
    NSLog(@"%@",@"Could not save key.");
    return;
}

success = [identity UpdateString: @"region" value: region];
if (success != YES) {
    NSLog(@"%@",@"Could not save region.");
    return;
}

success = [identity UpdateString: @"requestedVersion" value: requestedVersionId];
if (success != YES) {
    NSLog(@"%@",@"Could not save requestedVersion.");
    return;
}

success = [identity UpdateString: @"versionId" value: versionId];
if (success != YES) {
    NSLog(@"%@",@"Could not save versionId.");
    return;
}

success = [identity UpdateString: @"etag" value: etag];
if (success != YES) {
    NSLog(@"%@",@"Could not save etag.");
    return;
}

success = [identity UpdateString: @"size" value: expectedSize];
if (success != YES) {
    NSLog(@"%@",@"Could not save size.");
    return;
}

success = [identity UpdateString: @"checksum" value: expectedChecksum];
if (success != YES) {
    NSLog(@"%@",@"Could not save checksum.");
    return;
}

success = [identity UpdateString: @"finalPath" value: finalPath];
if (success != YES) {
    NSLog(@"%@",@"Could not save finalPath.");
    return;
}

success = [identity UpdateString: @"chunkSize" value: @"8388608"];
if (success != YES) {
    NSLog(@"%@",@"Could not save chunkSize.");
    return;
}

if (hasCheckpoint == YES) {
    [stringCompare SetString: [state StringOf: @"versionId"]];
    BOOL stringMatch19 = [stringCompare ContentsEqual: [identity StringOf: @"versionId"] caseSensitive: YES];
    if (stringMatch19 != YES) {
        NSLog(@"%@",@"Object identity changed. Do not mix old cached bytes with this object.");
        return;
    }

    [stringCompare SetString: [state StringOf: @"etag"]];
    BOOL stringMatch20 = [stringCompare ContentsEqual: [identity StringOf: @"etag"] caseSensitive: YES];
    if (stringMatch20 != YES) {
        NSLog(@"%@",@"Object identity changed. Do not mix old cached bytes with this object.");
        return;
    }

    [stringCompare SetString: [state StringOf: @"size"]];
    BOOL stringMatch21 = [stringCompare ContentsEqual: [identity StringOf: @"size"] caseSensitive: YES];
    if (stringMatch21 != YES) {
        NSLog(@"%@",@"Object identity changed. Do not mix old cached bytes with this object.");
        return;
    }

    [stringCompare SetString: [state StringOf: @"checksum"]];
    BOOL stringMatch22 = [stringCompare ContentsEqual: [identity StringOf: @"checksum"] caseSensitive: YES];
    if (stringMatch22 != YES) {
        NSLog(@"%@",@"Object identity changed. Do not mix old cached bytes with this object.");
        return;
    }

}
else {
    success = [files DirEnsureExists: cacheDir];
    if (success != YES) {
        NSLog(@"%@",@"Could not create private cache.");
        return;
    }

    CkoDirTree *entries = [[CkoDirTree alloc] init];
    entries.BaseDir = cacheDir;
    entries.Recurse = NO;
    success = [entries BeginIterate];
    if ((success == YES) || (entries.DoneIterating != YES)) {
        NSLog(@"%@",@"First download requires an empty, readable cache directory.");
        return;
    }

    success = [identity WriteFile: @"qa_output/s3-download-cache/state.json.tmp"];
    if (success != YES) {
        NSLog(@"%@",@"Could not save download identity.");
        return;
    }

    success = [files FileRename: @"qa_output/s3-download-cache/state.json.tmp" newPath: manifestPath];
    if (success != YES) {
        NSLog(@"%@",@"Checkpoint remains at its temporary path.");
        return;
    }

}

CkoCrypt2 *digest = [[CkoCrypt2 alloc] init];
digest.HashAlgorithm = @"sha256";
digest.EncodingMode = @"base64";
if ([files FileExists: finalPath] == YES) {
    NSString *existingSize = [files FileSizeStr: finalPath];
    NSString *existingChecksum = [digest HashFileENC: finalPath];
    [stringCompare SetString: existingSize];
    BOOL stringMatch23 = [stringCompare ContentsEqual: expectedSize caseSensitive: YES];
    [stringCompare SetString: existingChecksum];
    BOOL stringMatch24 = [stringCompare ContentsEqual: expectedChecksum caseSensitive: YES];
    if ((digest.LastMethodSuccess != YES) || (stringMatch23 != YES) || (stringMatch24 != YES)) {
        NSLog(@"%@",@"Existing final file does not match; preserve it.");
        return;
    }

    NSLog(@"%@",@"Object already downloaded and checksum verified.");
    return;
}

digest.EncodingMode = @"hexlower";
CkoStringBuilder *path = [[CkoStringBuilder alloc] init];
CkoStringBuilder *range = [[CkoStringBuilder alloc] init];
CkoStringBuilder *digits = [[CkoStringBuilder alloc] init];
CkoStringBuilder *rangeHeader = [[CkoStringBuilder alloc] init];
CkoStringBuilder *contentRange = [[CkoStringBuilder alloc] init];
CkoStringBuilder *byteCount = [[CkoStringBuilder alloc] init];
CkoJsonObject *receipt = [[CkoJsonObject alloc] init];
receipt.Strict = YES;
CkoMime *received = [[CkoMime alloc] init];
int chunkIndex = 0;
int byteHigh = 0;
int byteLow = 0;
int endHigh;
int endLow;
NSString *actualRange = 0;
NSString *actualLength = 0;
NSString *actualEtag = 0;
NSString *actualVersion = 0;
NSString *actualSize = 0;
NSString *actualHash = 0;
while ((chunkIndex < chunkCount)) {
    int chunkBytes = chunkSize;
    if ((chunkIndex == chunkCount - 1) && (remainder != 0)) {
        chunkBytes = remainder;
    }

    [range Clear];
    [digits Clear];
    [digits AppendInt: [NSNumber numberWithInt: byteLow]];
    if (byteHigh > 0) {
        while (([digits.Length intValue] < 9)) {
            [digits Prepend: @"0"];
        }

        [range AppendInt: [NSNumber numberWithInt: 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: [NSNumber numberWithInt: endLow]];
    if (endHigh > 0) {
        while (([digits.Length intValue] < 9)) {
            [digits Prepend: @"0"];
        }

        [range AppendInt: [NSNumber numberWithInt: endHigh]];
    }

    [range Append: [digits GetAsString]];
    NSString *rangeKey = [range GetAsString];
    [rangeHeader SetString: @"bytes="];
    [rangeHeader Append: rangeKey];
    [contentRange SetString: @"bytes "];
    [contentRange Append: rangeKey];
    [contentRange Append: @"/"];
    [contentRange Append: expectedSize];
    [byteCount Clear];
    [byteCount AppendInt: [NSNumber numberWithInt: chunkBytes]];
    [path SetString: cacheDir];
    [path Append: @"/chunk-"];
    [path AppendInt: [NSNumber numberWithInt: chunkIndex]];
    NSString *chunkPath = [path GetAsString];
    [path Append: @".json"];
    NSString *receiptPath = [path GetAsString];
    [path SetString: chunkPath];
    [path Append: @".part"];
    NSString *partialPath = [path GetAsString];
    if ([files FileExists: chunkPath] == YES) {
        success = [receipt LoadFile: receiptPath];
        if (success != YES) {
            NSLog(@"%@",@"Cached chunk has no valid receipt. Preserve the cache.");
            return;
        }

        actualHash = [digest HashFileENC: chunkPath];
        [stringCompare SetString: actualHash];
        BOOL stringMatch25 = [stringCompare ContentsEqual: [receipt StringOf: @"hash"] caseSensitive: YES];
        [stringCompare SetString: [receipt StringOf: @"range"]];
        BOOL stringMatch26 = [stringCompare ContentsEqual: rangeKey caseSensitive: YES];
        [stringCompare SetString: [files FileSizeStr: chunkPath]];
        BOOL stringMatch27 = [stringCompare ContentsEqual: [byteCount GetAsString] caseSensitive: YES];
        if ((digest.LastMethodSuccess != YES) || (stringMatch25 != YES) || (stringMatch26 != YES) || (stringMatch27 != YES)) {
            NSLog(@"%@",@"Cached chunk failed verification. Remove only this chunk and receipt before retrying.");
            return;
        }

        NSLog(@"%@%d",@"Reusing verified chunk: ",chunkIndex);
    }
    else {
        [query Clear];
        [stringCompare SetString: versionId];
        BOOL stringMatch28 = [stringCompare ContentsEqual: @"" caseSensitive: YES];
        if (stringMatch28 != YES) {
            if ([query.Length intValue] > 0) {
                [query Append: @"&"];
            }

            [query Append: @"versionId="];
            [query Append: [http UrlEncode: versionId]];
        }

        [http ClearHeaders];
        success = [now SetFromCurrentSystemTime];
        if (success != YES) {
            NSLog(@"%@",@"Could not read system time.");
            return;
        }

        [timestamp SetString: [now GetAsTimestamp: NO]];
        replaceCount = [[timestamp Replace: @"-" replacement: @""] intValue];
        replaceCount = [[timestamp Replace: @":" replacement: @""] intValue];
        amzDate = [timestamp GetAsString];
        dateStamp = [timestamp GetRange: [NSNumber numberWithInt: 0] numChars: [NSNumber numberWithInt: 8] removeFlag: NO];
        payloadHash = [signer HashStringENC: @""];
        if (signer.LastMethodSuccess != YES) {
            NSLog(@"%@",@"Could not hash payload.");
            return;
        }

        [canonicalHeaders Clear];
        [signedHeaders Clear];
        if ([signedHeaders.Length intValue] > 0) {
            [signedHeaders Append: @";"];
        }

        [signedHeaders Append: @"host"];
        [canonicalHeaders Append: @"host:"];
        [canonicalHeaders Append: [host GetAsString]];
        [canonicalHeaders Append: @"\n"];
        [http SetRequestHeader: @"host" value: [host GetAsString]];
        if ([signedHeaders.Length intValue] > 0) {
            [signedHeaders Append: @";"];
        }

        [signedHeaders Append: @"if-match"];
        [canonicalHeaders Append: @"if-match:"];
        [canonicalHeaders Append: etag];
        [canonicalHeaders Append: @"\n"];
        [http SetRequestHeader: @"if-match" value: etag];
        if ([signedHeaders.Length intValue] > 0) {
            [signedHeaders Append: @";"];
        }

        [signedHeaders Append: @"range"];
        [canonicalHeaders Append: @"range:"];
        [canonicalHeaders Append: [rangeHeader GetAsString]];
        [canonicalHeaders Append: @"\n"];
        [http SetRequestHeader: @"range" value: [rangeHeader GetAsString]];
        if ([signedHeaders.Length intValue] > 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" value: payloadHash];
        if ([signedHeaders.Length intValue] > 0) {
            [signedHeaders Append: @";"];
        }

        [signedHeaders Append: @"x-amz-date"];
        [canonicalHeaders Append: @"x-amz-date:"];
        [canonicalHeaders Append: amzDate];
        [canonicalHeaders Append: @"\n"];
        [http SetRequestHeader: @"x-amz-date" value: amzDate];
        if ([credentials HasMember: @"session_token"] == YES) {
            if ([signedHeaders.Length intValue] > 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" value: [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 != YES) {
            NSLog(@"%@",@"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 != YES) {
            NSLog(@"%@",@"Could not set signing key.");
            return;
        }

        derivedKey = [signer MacStringENC: dateStamp];
        if (signer.LastMethodSuccess != YES) {
            NSLog(@"%@",@"Could not derive signing key.");
            return;
        }

        success = [signer SetMacKeyEncoded: derivedKey encoding: @"hex"];
        if (success != YES) {
            NSLog(@"%@",@"Could not set signing key.");
            return;
        }

        derivedKey = [signer MacStringENC: region];
        if (signer.LastMethodSuccess != YES) {
            NSLog(@"%@",@"Could not derive signing key.");
            return;
        }

        success = [signer SetMacKeyEncoded: derivedKey encoding: @"hex"];
        if (success != YES) {
            NSLog(@"%@",@"Could not set signing key.");
            return;
        }

        derivedKey = [signer MacStringENC: @"s3"];
        if (signer.LastMethodSuccess != YES) {
            NSLog(@"%@",@"Could not derive signing key.");
            return;
        }

        success = [signer SetMacKeyEncoded: derivedKey encoding: @"hex"];
        if (success != YES) {
            NSLog(@"%@",@"Could not set signing key.");
            return;
        }

        derivedKey = [signer MacStringENC: @"aws4_request"];
        if (signer.LastMethodSuccess != YES) {
            NSLog(@"%@",@"Could not derive signing key.");
            return;
        }

        success = [signer SetMacKeyEncoded: derivedKey encoding: @"hex"];
        if (success != YES) {
            NSLog(@"%@",@"Could not set signing key.");
            return;
        }

        signature = [signer MacStringENC: [stringToSign GetAsString]];
        if (signer.LastMethodSuccess != YES) {
            NSLog(@"%@",@"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" value: [authorization GetAsString]];
        [url SetString: @"https://"];
        [url Append: [host GetAsString]];
        [url Append: [uri GetAsString]];
        if ([query.Length intValue] > 0) {
            [url Append: @"?"];
            [url Append: [query GetAsString]];
        }

        success = [http Download: [url GetAsString] saveToPath: partialPath];
        if (([http.LastStatus intValue] == 412) || ([http.LastStatus intValue] == 416)) {
            NSLog(@"%@",@"Object changed or range is invalid. Preserve the cache; do not append.");
            return;
        }

        if ((success != YES) || ([http.LastStatus intValue] != 206)) {
            NSLog(@"%@%d",@"Request failed or returned unexpected HTTP status: ",[http.LastStatus intValue]);
            //  Preserve progress. Inspect full diagnostics privately; do not log secrets.
            return;
        }

        success = [received LoadMime: http.LastResponseHeader];
        if (success != YES) {
            NSLog(@"%@",@"Could not parse range response.");
            return;
        }

        actualRange = [received GetHeaderField: @"Content-Range"];
        [stringCompare SetString: actualRange];
        BOOL stringMatch29 = [stringCompare ContentsEqual: @"" caseSensitive: YES];
        if ((received.LastMethodSuccess != YES) || (stringMatch29 == YES)) {
            NSLog(@"%@",@"Missing download header Content-Range.");
            return;
        }

        actualLength = [received GetHeaderField: @"Content-Length"];
        [stringCompare SetString: actualLength];
        BOOL stringMatch30 = [stringCompare ContentsEqual: @"" caseSensitive: YES];
        if ((received.LastMethodSuccess != YES) || (stringMatch30 == YES)) {
            NSLog(@"%@",@"Missing download header Content-Length.");
            return;
        }

        actualEtag = [received GetHeaderField: @"ETag"];
        [stringCompare SetString: actualEtag];
        BOOL stringMatch31 = [stringCompare ContentsEqual: @"" caseSensitive: YES];
        if ((received.LastMethodSuccess != YES) || (stringMatch31 == YES)) {
            NSLog(@"%@",@"Missing download header ETag.");
            return;
        }

        [stringCompare SetString: actualRange];
        BOOL stringMatch32 = [stringCompare ContentsEqual: [contentRange GetAsString] caseSensitive: YES];
        [stringCompare SetString: actualLength];
        BOOL stringMatch33 = [stringCompare ContentsEqual: [byteCount GetAsString] caseSensitive: YES];
        [stringCompare SetString: actualEtag];
        BOOL stringMatch34 = [stringCompare ContentsEqual: etag caseSensitive: YES];
        if ((stringMatch32 != YES) || (stringMatch33 != YES) || (stringMatch34 != YES)) {
            NSLog(@"%@",@"Unexpected range response; no chunk committed.");
            return;
        }

        [stringCompare SetString: versionId];
        BOOL stringMatch35 = [stringCompare ContentsEqual: @"" caseSensitive: YES];
        if (stringMatch35 != YES) {
            actualVersion = [received GetHeaderField: @"x-amz-version-id"];
            [stringCompare SetString: actualVersion];
            BOOL stringMatch36 = [stringCompare ContentsEqual: @"" caseSensitive: YES];
            if ((received.LastMethodSuccess != YES) || (stringMatch36 == YES)) {
                NSLog(@"%@",@"Missing download header x-amz-version-id.");
                return;
            }

            [stringCompare SetString: actualVersion];
            BOOL stringMatch37 = [stringCompare ContentsEqual: versionId caseSensitive: YES];
            if (stringMatch37 != YES) {
                NSLog(@"%@",@"Unexpected returned version.");
                return;
            }

        }

        actualSize = [files FileSizeStr: partialPath];
        [stringCompare SetString: actualSize];
        BOOL stringMatch38 = [stringCompare ContentsEqual: [byteCount GetAsString] caseSensitive: YES];
        if ((files.LastMethodSuccess != YES) || (stringMatch38 != YES)) {
            NSLog(@"%@",@"Range byte count mismatch.");
            return;
        }

        actualHash = [digest HashFileENC: partialPath];
        if (digest.LastMethodSuccess != YES) {
            NSLog(@"%@",@"Could not hash range bytes.");
            return;
        }

        success = [receipt UpdateString: @"range" value: rangeKey];
        if (success != YES) {
            NSLog(@"%@",@"Could not save range.");
            return;
        }

        success = [receipt UpdateString: @"hash" value: actualHash];
        if (success != YES) {
            NSLog(@"%@",@"Could not save hash.");
            return;
        }

        success = [receipt WriteFile: receiptPath];
        if (success != YES) {
            NSLog(@"%@",@"Could not save chunk receipt.");
            return;
        }

        success = [files FileRename: partialPath newPath: chunkPath];
        if (success != YES) {
            NSLog(@"%@",@"Could not commit downloaded chunk.");
            return;
        }

        NSLog(@"%@%d",@"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.
NSString *assembledPath = @"qa_output/s3-download-cache/assembled.part";
CkoFileAccess *assembled = [[CkoFileAccess alloc] init];
success = [assembled OpenForWrite: assembledPath];
if (success != YES) {
    NSLog(@"%@",@"Could not open assembly file.");
    return;
}

CkoBinData *data = [[CkoBinData alloc] init];
chunkIndex = 0;
while ((chunkIndex < chunkCount)) {
    [path SetString: cacheDir];
    [path Append: @"/chunk-"];
    [path AppendInt: [NSNumber numberWithInt: chunkIndex]];
    [data Clear];
    success = [data LoadFile: [path GetAsString]];
    if (success == YES) {
        success = [assembled FileWriteBd: data offset: [NSNumber numberWithInt: 0] numBytes: [NSNumber numberWithInt: 0]];
    }

    if (success != YES) {
        [assembled FileClose];
        NSLog(@"%@",@"Assembly failed; verified progress is retained.");
        return;
    }

    chunkIndex = chunkIndex + 1;
}

[assembled FileClose];
actualSize = [files FileSizeStr: assembledPath];
digest.EncodingMode = @"base64";
actualHash = [digest HashFileENC: assembledPath];
[stringCompare SetString: actualSize];
BOOL stringMatch39 = [stringCompare ContentsEqual: expectedSize caseSensitive: YES];
[stringCompare SetString: actualHash];
BOOL stringMatch40 = [stringCompare ContentsEqual: expectedChecksum caseSensitive: YES];
if ((digest.LastMethodSuccess != YES) || (stringMatch39 != YES) || (stringMatch40 != YES)) {
    NSLog(@"%@",@"Assembled object checksum/size mismatch; final file not created.");
    return;
}

success = [files FileRename: assembledPath newPath: finalPath];
if (success != YES) {
    NSLog(@"%@",@"Verified assembly remains in cache; rename failed.");
    return;
}

NSLog(@"%@",@"Resumable download completed and checksum verified. Cache retained for manual cleanup.");