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

Delphi ActiveX
var
success: Integer;
stringCompare: TChilkatStringBuilder;
credentials: TChilkatJsonObject;
stringMatch1: Integer;
stringMatch2: Integer;
http: TChilkatHttp;
stringMatch3: Integer;
region: WideString;
endpoint: TChilkatStringBuilder;
bucketName: WideString;
objectKey: WideString;
response: TChilkatHttpResponse;
signer: TChilkatCrypt2;
now: TCkDateTime;
timestamp: TChilkatStringBuilder;
canonical: TChilkatStringBuilder;
canonicalHeaders: TChilkatStringBuilder;
signedHeaders: TChilkatStringBuilder;
scope: TChilkatStringBuilder;
stringToSign: TChilkatStringBuilder;
signingKey: TChilkatStringBuilder;
authorization: TChilkatStringBuilder;
url: TChilkatStringBuilder;
query: TChilkatStringBuilder;
number: TChilkatStringBuilder;
host: TChilkatStringBuilder;
uri: TChilkatStringBuilder;
xml: TChilkatXml;
amzDate: WideString;
dateStamp: WideString;
payloadHash: WideString;
canonicalHash: WideString;
derivedKey: WideString;
signature: WideString;
replaceCount: Integer;
versionId: WideString;
etag: WideString;
expectedSize: WideString;
expectedChecksum: WideString;
checksumType: WideString;
returnedVersion: WideString;
files: TCkFileAccess;
cacheDir: WideString;
manifestPath: WideString;
finalPath: WideString;
requestedVersionId: WideString;
state: TChilkatJsonObject;
identity: TChilkatJsonObject;
hasCheckpoint: Integer;
stringMatch4: Integer;
stringMatch5: Integer;
stringMatch6: Integer;
stringMatch7: Integer;
stringMatch8: Integer;
stringMatch9: Integer;
stringMatch10: Integer;
stringMatch11: Integer;
stringMatch12: Integer;
stringMatch13: Integer;
stringMatch14: Integer;
stringMatch15: Integer;
stringMatch16: Integer;
stringMatch17: Integer;
stringMatch18: Integer;
chunkSize: Integer;
chunkCount: Integer;
remainder: Integer;
position: Integer;
sizeText: TChilkatStringBuilder;
decimalDigits: TChilkatStringBuilder;
digit: TChilkatStringBuilder;
stringMatch19: Integer;
stringMatch20: Integer;
stringMatch21: Integer;
stringMatch22: Integer;
entries: TChilkatDirTree;
digest: TChilkatCrypt2;
existingSize: WideString;
existingChecksum: WideString;
stringMatch23: Integer;
stringMatch24: Integer;
path: TChilkatStringBuilder;
range: TChilkatStringBuilder;
digits: TChilkatStringBuilder;
rangeHeader: TChilkatStringBuilder;
contentRange: TChilkatStringBuilder;
byteCount: TChilkatStringBuilder;
receipt: TChilkatJsonObject;
received: TChilkatMime;
chunkIndex: Integer;
byteHigh: Integer;
byteLow: Integer;
endHigh: Integer;
endLow: Integer;
actualRange: WideString;
actualLength: WideString;
actualEtag: WideString;
actualVersion: WideString;
actualSize: WideString;
actualHash: WideString;
chunkBytes: Integer;
rangeKey: WideString;
chunkPath: WideString;
receiptPath: WideString;
partialPath: WideString;
stringMatch25: Integer;
stringMatch26: Integer;
stringMatch27: Integer;
stringMatch28: Integer;
stringMatch29: Integer;
stringMatch30: Integer;
stringMatch31: Integer;
stringMatch32: Integer;
stringMatch33: Integer;
stringMatch34: Integer;
stringMatch35: Integer;
stringMatch36: Integer;
stringMatch37: Integer;
stringMatch38: Integer;
assembledPath: WideString;
assembled: TCkFileAccess;
data: TChilkatBinData;
stringMatch39: Integer;
stringMatch40: Integer;

begin
success := 0;

stringCompare := TChilkatStringBuilder.Create(Self);
//  This example requires the Chilkat API to have been previously unlocked.
//  See Global Unlock Sample for sample code.
//  Load private credentials; never put access keys or session tokens in source.
credentials := TChilkatJsonObject.Create(Self);
credentials.Strict := 1;
success := credentials.LoadFile('qa_data/aws/s3.json');
if (success <> 1) then
  begin
    Memo1.Lines.Add('Could not load private S3 credentials.');
    Exit;
  end;
stringCompare.SetString(credentials.StringOf('access_key'));
stringMatch1 := stringCompare.ContentsEqual('',1);
if ((credentials.JsonTypeOf('access_key') <> 1) or (stringMatch1 = 1)) then
  begin
    Memo1.Lines.Add('Missing or invalid access_key.');
    Exit;
  end;
stringCompare.SetString(credentials.StringOf('secret_key'));
stringMatch2 := stringCompare.ContentsEqual('',1);
if ((credentials.JsonTypeOf('secret_key') <> 1) or (stringMatch2 = 1)) then
  begin
    Memo1.Lines.Add('Missing or invalid secret_key.');
    Exit;
  end;
http := TChilkatHttp.Create(Self);
http.AwsAccessKey := credentials.StringOf('access_key');
http.AwsSecretKey := credentials.StringOf('secret_key');
if (credentials.HasMember('session_token') = 1) then
  begin
    stringCompare.SetString(credentials.StringOf('session_token'));
    stringMatch3 := stringCompare.ContentsEqual('',1);
    if ((credentials.JsonTypeOf('session_token') <> 1) or (stringMatch3 = 1)) then
      begin
        Memo1.Lines.Add('session_token must be a nonempty string when supplied.');
        Exit;
      end;
    http.AwsSessionToken := credentials.StringOf('session_token');
  end;
//  Current Chilkat uses SigV4 by default. Do not select deprecated SigV2.
//  Set the actual bucket region, not the caller's location.
region := 'us-west-2';
http.AwsRegion := region;
endpoint := TChilkatStringBuilder.Create(Self);
endpoint.Append('s3.');
endpoint.Append(region);
endpoint.Append('.amazonaws.com');
http.AwsEndpoint := endpoint.GetAsString();
http.RequireSslCertVerify := 1;
http.FollowRedirects := 0;
//  A region redirect is not success. Correct the endpoint and signing region.
bucketName := 'your-bucket-name';
objectKey := 'examples/archive.bin';
response := TChilkatHttpResponse.Create(Self);
signer := TChilkatCrypt2.Create(Self);
signer.Charset := 'utf-8';
signer.HashAlgorithm := 'sha256';
signer.EncodingMode := 'hexlower';
signer.MacAlgorithm := 'hmac';
now := TCkDateTime.Create(Self);
timestamp := TChilkatStringBuilder.Create(Self);
canonical := TChilkatStringBuilder.Create(Self);
canonicalHeaders := TChilkatStringBuilder.Create(Self);
signedHeaders := TChilkatStringBuilder.Create(Self);
scope := TChilkatStringBuilder.Create(Self);
stringToSign := TChilkatStringBuilder.Create(Self);
signingKey := TChilkatStringBuilder.Create(Self);
authorization := TChilkatStringBuilder.Create(Self);
url := TChilkatStringBuilder.Create(Self);
query := TChilkatStringBuilder.Create(Self);
number := TChilkatStringBuilder.Create(Self);
host := TChilkatStringBuilder.Create(Self);
uri := TChilkatStringBuilder.Create(Self);
xml := TChilkatXml.Create(Self);

host.Append(bucketName);
host.Append('.');
host.Append(endpoint.GetAsString());
//  Encode the original key exactly once, preserving S3 path separators.
uri.SetString(http.UrlEncode(objectKey));
replaceCount := uri.ReplaceNoCase('%2f','/');
if ((uri.StartsWith('/',1) = 1) or (uri.Contains('/../',1) = 1) or (uri.Contains('/./',1) = 1)) then
  begin
    Memo1.Lines.Add('Use a key without a leading slash or dot path segments for these examples.');
    Exit;
  end;
uri.Prepend('/');
versionId := '';

files := TCkFileAccess.Create(Self);
cacheDir := 'qa_output/s3-download-cache';
manifestPath := 'qa_output/s3-download-cache/state.json';
finalPath := 'qa_output/s3-resumed.bin';
requestedVersionId := versionId;
state := TChilkatJsonObject.Create(Self);
state.Strict := 1;
identity := TChilkatJsonObject.Create(Self);
hasCheckpoint := files.FileExists(manifestPath);
if (hasCheckpoint = 1) then
  begin
    success := state.LoadFile(manifestPath);
    if (success <> 1) then
      begin
        Memo1.Lines.Add('Invalid download checkpoint. Preserve the cache.');
        Exit;
      end;
    stringCompare.SetString(state.StringOf('schema'));
    stringMatch4 := stringCompare.ContentsEqual('1',1);
    if (stringMatch4 <> 1) then
      begin
        Memo1.Lines.Add('Checkpoint settings differ. Use the original settings or a new empty cache.');
        Exit;
      end;
    stringCompare.SetString(state.StringOf('bucket'));
    stringMatch5 := stringCompare.ContentsEqual(bucketName,1);
    if (stringMatch5 <> 1) then
      begin
        Memo1.Lines.Add('Checkpoint settings differ. Use the original settings or a new empty cache.');
        Exit;
      end;
    stringCompare.SetString(state.StringOf('key'));
    stringMatch6 := stringCompare.ContentsEqual(objectKey,1);
    if (stringMatch6 <> 1) then
      begin
        Memo1.Lines.Add('Checkpoint settings differ. Use the original settings or a new empty cache.');
        Exit;
      end;
    stringCompare.SetString(state.StringOf('region'));
    stringMatch7 := stringCompare.ContentsEqual(region,1);
    if (stringMatch7 <> 1) then
      begin
        Memo1.Lines.Add('Checkpoint settings differ. Use the original settings or a new empty cache.');
        Exit;
      end;
    stringCompare.SetString(state.StringOf('requestedVersion'));
    stringMatch8 := stringCompare.ContentsEqual(requestedVersionId,1);
    if (stringMatch8 <> 1) then
      begin
        Memo1.Lines.Add('Checkpoint settings differ. Use the original settings or a new empty cache.');
        Exit;
      end;
    stringCompare.SetString(state.StringOf('finalPath'));
    stringMatch9 := stringCompare.ContentsEqual(finalPath,1);
    if (stringMatch9 <> 1) then
      begin
        Memo1.Lines.Add('Checkpoint settings differ. Use the original settings or a new empty cache.');
        Exit;
      end;
    stringCompare.SetString(state.StringOf('chunkSize'));
    stringMatch10 := stringCompare.ContentsEqual('8388608',1);
    if (stringMatch10 <> 1) then
      begin
        Memo1.Lines.Add('Checkpoint settings differ. Use the original settings or a new empty cache.');
        Exit;
      end;
    versionId := state.StringOf('versionId');
    if (state.JsonTypeOf('versionId') <> 1) then
      begin
        Memo1.Lines.Add('Checkpoint version ID is invalid.');
        Exit;
      end;
  end;
query.Clear();
stringCompare.SetString(versionId);
stringMatch11 := stringCompare.ContentsEqual('',1);
if (stringMatch11 <> 1) then
  begin
    if (query.Length > 0) then
      begin
        query.Append('&');
      end;
    query.Append('versionId=');
    query.Append(http.UrlEncode(versionId));
  end;
http.ClearHeaders();
success := now.SetFromCurrentSystemTime();
if (success <> 1) then
  begin
    Memo1.Lines.Add('Could not read system time.');
    Exit;
  end;
timestamp.SetString(now.GetAsTimestamp(0));
replaceCount := timestamp.Replace('-','');
replaceCount := timestamp.Replace(':','');
amzDate := timestamp.GetAsString();
dateStamp := timestamp.GetRange(0,8,0);
payloadHash := signer.HashStringENC('');
if (signer.LastMethodSuccess <> 1) then
  begin
    Memo1.Lines.Add('Could not hash payload.');
    Exit;
  end;
canonicalHeaders.Clear();
signedHeaders.Clear();
if (signedHeaders.Length > 0) then
  begin
    signedHeaders.Append(';');
  end;
signedHeaders.Append('host');
canonicalHeaders.Append('host:');
canonicalHeaders.Append(host.GetAsString());
canonicalHeaders.Append(#10);
http.SetRequestHeader('host',host.GetAsString());
if (signedHeaders.Length > 0) then
  begin
    signedHeaders.Append(';');
  end;
signedHeaders.Append('x-amz-checksum-mode');
canonicalHeaders.Append('x-amz-checksum-mode:');
canonicalHeaders.Append('ENABLED');
canonicalHeaders.Append(#10);
http.SetRequestHeader('x-amz-checksum-mode','ENABLED');
if (signedHeaders.Length > 0) then
  begin
    signedHeaders.Append(';');
  end;
signedHeaders.Append('x-amz-content-sha256');
canonicalHeaders.Append('x-amz-content-sha256:');
canonicalHeaders.Append(payloadHash);
canonicalHeaders.Append(#10);
http.SetRequestHeader('x-amz-content-sha256',payloadHash);
if (signedHeaders.Length > 0) then
  begin
    signedHeaders.Append(';');
  end;
signedHeaders.Append('x-amz-date');
canonicalHeaders.Append('x-amz-date:');
canonicalHeaders.Append(amzDate);
canonicalHeaders.Append(#10);
http.SetRequestHeader('x-amz-date',amzDate);
if (credentials.HasMember('session_token') = 1) then
  begin
    if (signedHeaders.Length > 0) then
      begin
        signedHeaders.Append(';');
      end;
    signedHeaders.Append('x-amz-security-token');
    canonicalHeaders.Append('x-amz-security-token:');
    canonicalHeaders.Append(credentials.StringOf('session_token'));
    canonicalHeaders.Append(#10);
    http.SetRequestHeader('x-amz-security-token',credentials.StringOf('session_token'));
  end;
canonical.Clear();
canonical.Append('HEAD' + #10);
canonical.Append(uri.GetAsString());
canonical.Append(#10);
canonical.Append(query.GetAsString());
canonical.Append(#10);
canonical.Append(canonicalHeaders.GetAsString());
canonical.Append(#10);
canonical.Append(signedHeaders.GetAsString());
canonical.Append(#10);
canonical.Append(payloadHash);
canonicalHash := signer.HashStringENC(canonical.GetAsString());
if (signer.LastMethodSuccess <> 1) then
  begin
    Memo1.Lines.Add('Could not hash canonical request.');
    Exit;
  end;
scope.Clear();
scope.Append(dateStamp);
scope.Append('/');
scope.Append(region);
scope.Append('/s3/aws4_request');
stringToSign.Clear();
stringToSign.Append('AWS4-HMAC-SHA256' + #10);
stringToSign.Append(amzDate);
stringToSign.Append(#10);
stringToSign.Append(scope.GetAsString());
stringToSign.Append(#10);
stringToSign.Append(canonicalHash);
signingKey.SetString('AWS4');
signingKey.Append(credentials.StringOf('secret_key'));
success := signer.SetMacKeyString(signingKey.GetAsString());
if (success <> 1) then
  begin
    Memo1.Lines.Add('Could not set signing key.');
    Exit;
  end;
derivedKey := signer.MacStringENC(dateStamp);
if (signer.LastMethodSuccess <> 1) then
  begin
    Memo1.Lines.Add('Could not derive signing key.');
    Exit;
  end;
success := signer.SetMacKeyEncoded(derivedKey,'hex');
if (success <> 1) then
  begin
    Memo1.Lines.Add('Could not set signing key.');
    Exit;
  end;
derivedKey := signer.MacStringENC(region);
if (signer.LastMethodSuccess <> 1) then
  begin
    Memo1.Lines.Add('Could not derive signing key.');
    Exit;
  end;
success := signer.SetMacKeyEncoded(derivedKey,'hex');
if (success <> 1) then
  begin
    Memo1.Lines.Add('Could not set signing key.');
    Exit;
  end;
derivedKey := signer.MacStringENC('s3');
if (signer.LastMethodSuccess <> 1) then
  begin
    Memo1.Lines.Add('Could not derive signing key.');
    Exit;
  end;
success := signer.SetMacKeyEncoded(derivedKey,'hex');
if (success <> 1) then
  begin
    Memo1.Lines.Add('Could not set signing key.');
    Exit;
  end;
derivedKey := signer.MacStringENC('aws4_request');
if (signer.LastMethodSuccess <> 1) then
  begin
    Memo1.Lines.Add('Could not derive signing key.');
    Exit;
  end;
success := signer.SetMacKeyEncoded(derivedKey,'hex');
if (success <> 1) then
  begin
    Memo1.Lines.Add('Could not set signing key.');
    Exit;
  end;
signature := signer.MacStringENC(stringToSign.GetAsString());
if (signer.LastMethodSuccess <> 1) then
  begin
    Memo1.Lines.Add('Could not sign request.');
    Exit;
  end;
authorization.Clear();
authorization.Append('AWS4-HMAC-SHA256 Credential=');
authorization.Append(credentials.StringOf('access_key'));
authorization.Append('/');
authorization.Append(scope.GetAsString());
authorization.Append(', SignedHeaders=');
authorization.Append(signedHeaders.GetAsString());
authorization.Append(', Signature=');
authorization.Append(signature);
http.SetRequestHeader('Authorization',authorization.GetAsString());
url.SetString('https://');
url.Append(host.GetAsString());
url.Append(uri.GetAsString());
if (query.Length > 0) then
  begin
    url.Append('?');
    url.Append(query.GetAsString());
  end;
success := http.HttpNoBody('HEAD',url.GetAsString(),response.ControlInterface);
if ((success <> 1) or (response.StatusCode <> 200)) then
  begin
    Memo1.Lines.Add('Request failed or returned unexpected HTTP status: ' + IntToStr(response.StatusCode));
    //  Preserve progress. Inspect full diagnostics privately; do not log secrets.
    Exit;
  end;
etag := response.GetHeaderField('ETag');
stringCompare.SetString(etag);
stringMatch12 := stringCompare.ContentsEqual('',1);
if ((response.LastMethodSuccess <> 1) or (stringMatch12 = 1)) then
  begin
    Memo1.Lines.Add('Missing required response header ETag.');
    Exit;
  end;
expectedSize := response.GetHeaderField('Content-Length');
stringCompare.SetString(expectedSize);
stringMatch13 := stringCompare.ContentsEqual('',1);
if ((response.LastMethodSuccess <> 1) or (stringMatch13 = 1)) then
  begin
    Memo1.Lines.Add('Missing required response header Content-Length.');
    Exit;
  end;
returnedVersion := response.GetHeaderField('x-amz-version-id');
if (response.LastMethodSuccess <> 1) then
  begin
    returnedVersion := '';
  end;
stringCompare.SetString(versionId);
stringMatch14 := stringCompare.ContentsEqual('',1);
if (stringMatch14 = 1) then
  begin
    versionId := returnedVersion;
  end
else
  begin
    stringCompare.SetString(returnedVersion);
    stringMatch15 := stringCompare.ContentsEqual(versionId,1);
    if (stringMatch15 <> 1) then
      begin
        Memo1.Lines.Add('Unexpected object version.');
        Exit;
      end;
  end;
expectedChecksum := response.GetHeaderField('x-amz-checksum-sha256');
stringCompare.SetString(expectedChecksum);
stringMatch16 := stringCompare.ContentsEqual('',1);
if ((response.LastMethodSuccess <> 1) or (stringMatch16 = 1)) then
  begin
    Memo1.Lines.Add('Missing required response header x-amz-checksum-sha256.');
    Exit;
  end;
checksumType := response.GetHeaderField('x-amz-checksum-type');
stringCompare.SetString(checksumType);
stringMatch17 := stringCompare.ContentsEqual('',1);
if ((response.LastMethodSuccess <> 1) or (stringMatch17 = 1)) then
  begin
    Memo1.Lines.Add('Missing required response header x-amz-checksum-type.');
    Exit;
  end;
stringCompare.SetString(checksumType);
stringMatch18 := stringCompare.ContentsEqual('FULL_OBJECT',1);
if (stringMatch18 <> 1) then
  begin
    Memo1.Lines.Add('This example requires a FULL_OBJECT SHA-256 checksum; COMPOSITE needs separate verification.');
    Exit;
  end;
//  Portable decimal long division; no 32-bit byte-offset overflow.
chunkSize := 8388608;
chunkCount := 0;
remainder := 0;
position := 0;
sizeText := TChilkatStringBuilder.Create(Self);
decimalDigits := TChilkatStringBuilder.Create(Self);
digit := TChilkatStringBuilder.Create(Self);
sizeText.Append(expectedSize);
decimalDigits.Append('0123456789');
if ((sizeText.Length = 0) or (sizeText.Length > 14)) then
  begin
    Memo1.Lines.Add('Invalid object size.');
    Exit;
  end;
while (position < sizeText.Length) do
  begin
    digit.SetString(sizeText.GetRange(position,1,0));
    if (decimalDigits.Contains(digit.GetAsString(),1) <> 1) then
      begin
        Memo1.Lines.Add('Invalid decimal object size.');
        Exit;
      end;
    remainder := remainder * 10 + digit.IntValue;
    chunkCount := chunkCount * 10;
    while (remainder >= chunkSize) do
      begin
        chunkCount := chunkCount + 1;
        remainder := remainder - chunkSize;
      end;

    position := position + 1;
  end;

if (remainder <> 0) then
  begin
    chunkCount := chunkCount + 1;
  end;
if ((chunkCount < 1) or (chunkCount > 10000)) then
  begin
    Memo1.Lines.Add('Use a nonempty object of at most 10,000 fixed 8 MiB chunks; empty objects use the single-download example.');
    Exit;
  end;
success := identity.UpdateString('schema','1');
if (success <> 1) then
  begin
    Memo1.Lines.Add('Could not save schema.');
    Exit;
  end;
success := identity.UpdateString('bucket',bucketName);
if (success <> 1) then
  begin
    Memo1.Lines.Add('Could not save bucket.');
    Exit;
  end;
success := identity.UpdateString('key',objectKey);
if (success <> 1) then
  begin
    Memo1.Lines.Add('Could not save key.');
    Exit;
  end;
success := identity.UpdateString('region',region);
if (success <> 1) then
  begin
    Memo1.Lines.Add('Could not save region.');
    Exit;
  end;
success := identity.UpdateString('requestedVersion',requestedVersionId);
if (success <> 1) then
  begin
    Memo1.Lines.Add('Could not save requestedVersion.');
    Exit;
  end;
success := identity.UpdateString('versionId',versionId);
if (success <> 1) then
  begin
    Memo1.Lines.Add('Could not save versionId.');
    Exit;
  end;
success := identity.UpdateString('etag',etag);
if (success <> 1) then
  begin
    Memo1.Lines.Add('Could not save etag.');
    Exit;
  end;
success := identity.UpdateString('size',expectedSize);
if (success <> 1) then
  begin
    Memo1.Lines.Add('Could not save size.');
    Exit;
  end;
success := identity.UpdateString('checksum',expectedChecksum);
if (success <> 1) then
  begin
    Memo1.Lines.Add('Could not save checksum.');
    Exit;
  end;
success := identity.UpdateString('finalPath',finalPath);
if (success <> 1) then
  begin
    Memo1.Lines.Add('Could not save finalPath.');
    Exit;
  end;
success := identity.UpdateString('chunkSize','8388608');
if (success <> 1) then
  begin
    Memo1.Lines.Add('Could not save chunkSize.');
    Exit;
  end;
if (hasCheckpoint = 1) then
  begin
    stringCompare.SetString(state.StringOf('versionId'));
    stringMatch19 := stringCompare.ContentsEqual(identity.StringOf('versionId'),1);
    if (stringMatch19 <> 1) then
      begin
        Memo1.Lines.Add('Object identity changed. Do not mix old cached bytes with this object.');
        Exit;
      end;
    stringCompare.SetString(state.StringOf('etag'));
    stringMatch20 := stringCompare.ContentsEqual(identity.StringOf('etag'),1);
    if (stringMatch20 <> 1) then
      begin
        Memo1.Lines.Add('Object identity changed. Do not mix old cached bytes with this object.');
        Exit;
      end;
    stringCompare.SetString(state.StringOf('size'));
    stringMatch21 := stringCompare.ContentsEqual(identity.StringOf('size'),1);
    if (stringMatch21 <> 1) then
      begin
        Memo1.Lines.Add('Object identity changed. Do not mix old cached bytes with this object.');
        Exit;
      end;
    stringCompare.SetString(state.StringOf('checksum'));
    stringMatch22 := stringCompare.ContentsEqual(identity.StringOf('checksum'),1);
    if (stringMatch22 <> 1) then
      begin
        Memo1.Lines.Add('Object identity changed. Do not mix old cached bytes with this object.');
        Exit;
      end;
  end
else
  begin
    success := files.DirEnsureExists(cacheDir);
    if (success <> 1) then
      begin
        Memo1.Lines.Add('Could not create private cache.');
        Exit;
      end;
    entries := TChilkatDirTree.Create(Self);
    entries.BaseDir := cacheDir;
    entries.Recurse := 0;
    success := entries.BeginIterate();
    if ((success = 1) or (entries.DoneIterating <> 1)) then
      begin
        Memo1.Lines.Add('First download requires an empty, readable cache directory.');
        Exit;
      end;
    success := identity.WriteFile('qa_output/s3-download-cache/state.json.tmp');
    if (success <> 1) then
      begin
        Memo1.Lines.Add('Could not save download identity.');
        Exit;
      end;
    success := files.FileRename('qa_output/s3-download-cache/state.json.tmp',manifestPath);
    if (success <> 1) then
      begin
        Memo1.Lines.Add('Checkpoint remains at its temporary path.');
        Exit;
      end;
  end;
digest := TChilkatCrypt2.Create(Self);
digest.HashAlgorithm := 'sha256';
digest.EncodingMode := 'base64';
if (files.FileExists(finalPath) = 1) then
  begin
    existingSize := files.FileSizeStr(finalPath);
    existingChecksum := digest.HashFileENC(finalPath);
    stringCompare.SetString(existingSize);
    stringMatch23 := stringCompare.ContentsEqual(expectedSize,1);
    stringCompare.SetString(existingChecksum);
    stringMatch24 := stringCompare.ContentsEqual(expectedChecksum,1);
    if ((digest.LastMethodSuccess <> 1) or (stringMatch23 <> 1) or (stringMatch24 <> 1)) then
      begin
        Memo1.Lines.Add('Existing final file does not match; preserve it.');
        Exit;
      end;
    Memo1.Lines.Add('Object already downloaded and checksum verified.');
    Exit;
  end;
digest.EncodingMode := 'hexlower';
path := TChilkatStringBuilder.Create(Self);
range := TChilkatStringBuilder.Create(Self);
digits := TChilkatStringBuilder.Create(Self);
rangeHeader := TChilkatStringBuilder.Create(Self);
contentRange := TChilkatStringBuilder.Create(Self);
byteCount := TChilkatStringBuilder.Create(Self);
receipt := TChilkatJsonObject.Create(Self);
receipt.Strict := 1;
received := TChilkatMime.Create(Self);
chunkIndex := 0;
byteHigh := 0;
byteLow := 0;

while (chunkIndex < chunkCount) do
  begin
    chunkBytes := chunkSize;
    if ((chunkIndex = chunkCount - 1) and (remainder <> 0)) then
      begin
        chunkBytes := remainder;
      end;
    range.Clear();
    digits.Clear();
    digits.AppendInt(byteLow);
    if (byteHigh > 0) then
      begin
        while (digits.Length < 9) do
          begin
            digits.Prepend('0');
          end;

        range.AppendInt(byteHigh);
      end;
    range.Append(digits.GetAsString());
    range.Append('-');
    endHigh := byteHigh;
    endLow := byteLow + chunkBytes - 1;
    if (endLow >= 1000000000) then
      begin
        endLow := endLow - 1000000000;
        endHigh := endHigh + 1;
      end;
    digits.Clear();
    digits.AppendInt(endLow);
    if (endHigh > 0) then
      begin
        while (digits.Length < 9) do
          begin
            digits.Prepend('0');
          end;

        range.AppendInt(endHigh);
      end;
    range.Append(digits.GetAsString());
    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);
    chunkPath := path.GetAsString();
    path.Append('.json');
    receiptPath := path.GetAsString();
    path.SetString(chunkPath);
    path.Append('.part');
    partialPath := path.GetAsString();
    if (files.FileExists(chunkPath) = 1) then
      begin
        success := receipt.LoadFile(receiptPath);
        if (success <> 1) then
          begin
            Memo1.Lines.Add('Cached chunk has no valid receipt. Preserve the cache.');
            Exit;
          end;
        actualHash := digest.HashFileENC(chunkPath);
        stringCompare.SetString(actualHash);
        stringMatch25 := stringCompare.ContentsEqual(receipt.StringOf('hash'),1);
        stringCompare.SetString(receipt.StringOf('range'));
        stringMatch26 := stringCompare.ContentsEqual(rangeKey,1);
        stringCompare.SetString(files.FileSizeStr(chunkPath));
        stringMatch27 := stringCompare.ContentsEqual(byteCount.GetAsString(),1);
        if ((digest.LastMethodSuccess <> 1) or (stringMatch25 <> 1) or (stringMatch26 <> 1) or (stringMatch27 <> 1)) then
          begin
            Memo1.Lines.Add('Cached chunk failed verification. Remove only this chunk and receipt before retrying.');
            Exit;
          end;
        Memo1.Lines.Add('Reusing verified chunk: ' + IntToStr(chunkIndex));
      end
    else
      begin
        query.Clear();
        stringCompare.SetString(versionId);
        stringMatch28 := stringCompare.ContentsEqual('',1);
        if (stringMatch28 <> 1) then
          begin
            if (query.Length > 0) then
              begin
                query.Append('&');
              end;
            query.Append('versionId=');
            query.Append(http.UrlEncode(versionId));
          end;
        http.ClearHeaders();
        success := now.SetFromCurrentSystemTime();
        if (success <> 1) then
          begin
            Memo1.Lines.Add('Could not read system time.');
            Exit;
          end;
        timestamp.SetString(now.GetAsTimestamp(0));
        replaceCount := timestamp.Replace('-','');
        replaceCount := timestamp.Replace(':','');
        amzDate := timestamp.GetAsString();
        dateStamp := timestamp.GetRange(0,8,0);
        payloadHash := signer.HashStringENC('');
        if (signer.LastMethodSuccess <> 1) then
          begin
            Memo1.Lines.Add('Could not hash payload.');
            Exit;
          end;
        canonicalHeaders.Clear();
        signedHeaders.Clear();
        if (signedHeaders.Length > 0) then
          begin
            signedHeaders.Append(';');
          end;
        signedHeaders.Append('host');
        canonicalHeaders.Append('host:');
        canonicalHeaders.Append(host.GetAsString());
        canonicalHeaders.Append(#10);
        http.SetRequestHeader('host',host.GetAsString());
        if (signedHeaders.Length > 0) then
          begin
            signedHeaders.Append(';');
          end;
        signedHeaders.Append('if-match');
        canonicalHeaders.Append('if-match:');
        canonicalHeaders.Append(etag);
        canonicalHeaders.Append(#10);
        http.SetRequestHeader('if-match',etag);
        if (signedHeaders.Length > 0) then
          begin
            signedHeaders.Append(';');
          end;
        signedHeaders.Append('range');
        canonicalHeaders.Append('range:');
        canonicalHeaders.Append(rangeHeader.GetAsString());
        canonicalHeaders.Append(#10);
        http.SetRequestHeader('range',rangeHeader.GetAsString());
        if (signedHeaders.Length > 0) then
          begin
            signedHeaders.Append(';');
          end;
        signedHeaders.Append('x-amz-content-sha256');
        canonicalHeaders.Append('x-amz-content-sha256:');
        canonicalHeaders.Append(payloadHash);
        canonicalHeaders.Append(#10);
        http.SetRequestHeader('x-amz-content-sha256',payloadHash);
        if (signedHeaders.Length > 0) then
          begin
            signedHeaders.Append(';');
          end;
        signedHeaders.Append('x-amz-date');
        canonicalHeaders.Append('x-amz-date:');
        canonicalHeaders.Append(amzDate);
        canonicalHeaders.Append(#10);
        http.SetRequestHeader('x-amz-date',amzDate);
        if (credentials.HasMember('session_token') = 1) then
          begin
            if (signedHeaders.Length > 0) then
              begin
                signedHeaders.Append(';');
              end;
            signedHeaders.Append('x-amz-security-token');
            canonicalHeaders.Append('x-amz-security-token:');
            canonicalHeaders.Append(credentials.StringOf('session_token'));
            canonicalHeaders.Append(#10);
            http.SetRequestHeader('x-amz-security-token',credentials.StringOf('session_token'));
          end;
        canonical.Clear();
        canonical.Append('GET' + #10);
        canonical.Append(uri.GetAsString());
        canonical.Append(#10);
        canonical.Append(query.GetAsString());
        canonical.Append(#10);
        canonical.Append(canonicalHeaders.GetAsString());
        canonical.Append(#10);
        canonical.Append(signedHeaders.GetAsString());
        canonical.Append(#10);
        canonical.Append(payloadHash);
        canonicalHash := signer.HashStringENC(canonical.GetAsString());
        if (signer.LastMethodSuccess <> 1) then
          begin
            Memo1.Lines.Add('Could not hash canonical request.');
            Exit;
          end;
        scope.Clear();
        scope.Append(dateStamp);
        scope.Append('/');
        scope.Append(region);
        scope.Append('/s3/aws4_request');
        stringToSign.Clear();
        stringToSign.Append('AWS4-HMAC-SHA256' + #10);
        stringToSign.Append(amzDate);
        stringToSign.Append(#10);
        stringToSign.Append(scope.GetAsString());
        stringToSign.Append(#10);
        stringToSign.Append(canonicalHash);
        signingKey.SetString('AWS4');
        signingKey.Append(credentials.StringOf('secret_key'));
        success := signer.SetMacKeyString(signingKey.GetAsString());
        if (success <> 1) then
          begin
            Memo1.Lines.Add('Could not set signing key.');
            Exit;
          end;
        derivedKey := signer.MacStringENC(dateStamp);
        if (signer.LastMethodSuccess <> 1) then
          begin
            Memo1.Lines.Add('Could not derive signing key.');
            Exit;
          end;
        success := signer.SetMacKeyEncoded(derivedKey,'hex');
        if (success <> 1) then
          begin
            Memo1.Lines.Add('Could not set signing key.');
            Exit;
          end;
        derivedKey := signer.MacStringENC(region);
        if (signer.LastMethodSuccess <> 1) then
          begin
            Memo1.Lines.Add('Could not derive signing key.');
            Exit;
          end;
        success := signer.SetMacKeyEncoded(derivedKey,'hex');
        if (success <> 1) then
          begin
            Memo1.Lines.Add('Could not set signing key.');
            Exit;
          end;
        derivedKey := signer.MacStringENC('s3');
        if (signer.LastMethodSuccess <> 1) then
          begin
            Memo1.Lines.Add('Could not derive signing key.');
            Exit;
          end;
        success := signer.SetMacKeyEncoded(derivedKey,'hex');
        if (success <> 1) then
          begin
            Memo1.Lines.Add('Could not set signing key.');
            Exit;
          end;
        derivedKey := signer.MacStringENC('aws4_request');
        if (signer.LastMethodSuccess <> 1) then
          begin
            Memo1.Lines.Add('Could not derive signing key.');
            Exit;
          end;
        success := signer.SetMacKeyEncoded(derivedKey,'hex');
        if (success <> 1) then
          begin
            Memo1.Lines.Add('Could not set signing key.');
            Exit;
          end;
        signature := signer.MacStringENC(stringToSign.GetAsString());
        if (signer.LastMethodSuccess <> 1) then
          begin
            Memo1.Lines.Add('Could not sign request.');
            Exit;
          end;
        authorization.Clear();
        authorization.Append('AWS4-HMAC-SHA256 Credential=');
        authorization.Append(credentials.StringOf('access_key'));
        authorization.Append('/');
        authorization.Append(scope.GetAsString());
        authorization.Append(', SignedHeaders=');
        authorization.Append(signedHeaders.GetAsString());
        authorization.Append(', Signature=');
        authorization.Append(signature);
        http.SetRequestHeader('Authorization',authorization.GetAsString());
        url.SetString('https://');
        url.Append(host.GetAsString());
        url.Append(uri.GetAsString());
        if (query.Length > 0) then
          begin
            url.Append('?');
            url.Append(query.GetAsString());
          end;
        success := http.Download(url.GetAsString(),partialPath);
        if ((http.LastStatus = 412) or (http.LastStatus = 416)) then
          begin
            Memo1.Lines.Add('Object changed or range is invalid. Preserve the cache; do not append.');
            Exit;
          end;
        if ((success <> 1) or (http.LastStatus <> 206)) then
          begin
            Memo1.Lines.Add('Request failed or returned unexpected HTTP status: ' + IntToStr(http.LastStatus));
            //  Preserve progress. Inspect full diagnostics privately; do not log secrets.
            Exit;
          end;
        success := received.LoadMime(http.LastResponseHeader);
        if (success <> 1) then
          begin
            Memo1.Lines.Add('Could not parse range response.');
            Exit;
          end;
        actualRange := received.GetHeaderField('Content-Range');
        stringCompare.SetString(actualRange);
        stringMatch29 := stringCompare.ContentsEqual('',1);
        if ((received.LastMethodSuccess <> 1) or (stringMatch29 = 1)) then
          begin
            Memo1.Lines.Add('Missing download header Content-Range.');
            Exit;
          end;
        actualLength := received.GetHeaderField('Content-Length');
        stringCompare.SetString(actualLength);
        stringMatch30 := stringCompare.ContentsEqual('',1);
        if ((received.LastMethodSuccess <> 1) or (stringMatch30 = 1)) then
          begin
            Memo1.Lines.Add('Missing download header Content-Length.');
            Exit;
          end;
        actualEtag := received.GetHeaderField('ETag');
        stringCompare.SetString(actualEtag);
        stringMatch31 := stringCompare.ContentsEqual('',1);
        if ((received.LastMethodSuccess <> 1) or (stringMatch31 = 1)) then
          begin
            Memo1.Lines.Add('Missing download header ETag.');
            Exit;
          end;
        stringCompare.SetString(actualRange);
        stringMatch32 := stringCompare.ContentsEqual(contentRange.GetAsString(),1);
        stringCompare.SetString(actualLength);
        stringMatch33 := stringCompare.ContentsEqual(byteCount.GetAsString(),1);
        stringCompare.SetString(actualEtag);
        stringMatch34 := stringCompare.ContentsEqual(etag,1);
        if ((stringMatch32 <> 1) or (stringMatch33 <> 1) or (stringMatch34 <> 1)) then
          begin
            Memo1.Lines.Add('Unexpected range response; no chunk committed.');
            Exit;
          end;
        stringCompare.SetString(versionId);
        stringMatch35 := stringCompare.ContentsEqual('',1);
        if (stringMatch35 <> 1) then
          begin
            actualVersion := received.GetHeaderField('x-amz-version-id');
            stringCompare.SetString(actualVersion);
            stringMatch36 := stringCompare.ContentsEqual('',1);
            if ((received.LastMethodSuccess <> 1) or (stringMatch36 = 1)) then
              begin
                Memo1.Lines.Add('Missing download header x-amz-version-id.');
                Exit;
              end;
            stringCompare.SetString(actualVersion);
            stringMatch37 := stringCompare.ContentsEqual(versionId,1);
            if (stringMatch37 <> 1) then
              begin
                Memo1.Lines.Add('Unexpected returned version.');
                Exit;
              end;
          end;
        actualSize := files.FileSizeStr(partialPath);
        stringCompare.SetString(actualSize);
        stringMatch38 := stringCompare.ContentsEqual(byteCount.GetAsString(),1);
        if ((files.LastMethodSuccess <> 1) or (stringMatch38 <> 1)) then
          begin
            Memo1.Lines.Add('Range byte count mismatch.');
            Exit;
          end;
        actualHash := digest.HashFileENC(partialPath);
        if (digest.LastMethodSuccess <> 1) then
          begin
            Memo1.Lines.Add('Could not hash range bytes.');
            Exit;
          end;
        success := receipt.UpdateString('range',rangeKey);
        if (success <> 1) then
          begin
            Memo1.Lines.Add('Could not save range.');
            Exit;
          end;
        success := receipt.UpdateString('hash',actualHash);
        if (success <> 1) then
          begin
            Memo1.Lines.Add('Could not save hash.');
            Exit;
          end;
        success := receipt.WriteFile(receiptPath);
        if (success <> 1) then
          begin
            Memo1.Lines.Add('Could not save chunk receipt.');
            Exit;
          end;
        success := files.FileRename(partialPath,chunkPath);
        if (success <> 1) then
          begin
            Memo1.Lines.Add('Could not commit downloaded chunk.');
            Exit;
          end;
        Memo1.Lines.Add('Downloaded chunk: ' + IntToStr(chunkIndex));
      end;
    byteHigh := endHigh;
    byteLow := endLow + 1;
    if (byteLow = 1000000000) then
      begin
        byteLow := 0;
        byteHigh := byteHigh + 1;
      end;
    chunkIndex := chunkIndex + 1;
  end;

//  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.
assembledPath := 'qa_output/s3-download-cache/assembled.part';
assembled := TCkFileAccess.Create(Self);
success := assembled.OpenForWrite(assembledPath);
if (success <> 1) then
  begin
    Memo1.Lines.Add('Could not open assembly file.');
    Exit;
  end;
data := TChilkatBinData.Create(Self);
chunkIndex := 0;
while (chunkIndex < chunkCount) do
  begin
    path.SetString(cacheDir);
    path.Append('/chunk-');
    path.AppendInt(chunkIndex);
    data.Clear();
    success := data.LoadFile(path.GetAsString());
    if (success = 1) then
      begin
        success := assembled.FileWriteBd(data.ControlInterface,0,0);
      end;
    if (success <> 1) then
      begin
        assembled.FileClose();
        Memo1.Lines.Add('Assembly failed; verified progress is retained.');
        Exit;
      end;
    chunkIndex := chunkIndex + 1;
  end;

assembled.FileClose();
actualSize := files.FileSizeStr(assembledPath);
digest.EncodingMode := 'base64';
actualHash := digest.HashFileENC(assembledPath);
stringCompare.SetString(actualSize);
stringMatch39 := stringCompare.ContentsEqual(expectedSize,1);
stringCompare.SetString(actualHash);
stringMatch40 := stringCompare.ContentsEqual(expectedChecksum,1);
if ((digest.LastMethodSuccess <> 1) or (stringMatch39 <> 1) or (stringMatch40 <> 1)) then
  begin
    Memo1.Lines.Add('Assembled object checksum/size mismatch; final file not created.');
    Exit;
  end;
success := files.FileRename(assembledPath,finalPath);
if (success <> 1) then
  begin
    Memo1.Lines.Add('Verified assembly remains in cache; rename failed.');
    Exit;
  end;
Memo1.Lines.Add('Resumable download completed and checksum verified. Cache retained for manual cleanup.');