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

Ruby
require 'chilkat'

success = false

stringCompare = Chilkat::CkStringBuilder.new()
#  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 = Chilkat::CkJsonObject.new()
credentials.put_Strict(true)
success = credentials.LoadFile("qa_data/aws/s3.json")
if (success != true)
    print "Could not load private S3 credentials." + "\n";
    exit
end

stringCompare.SetString(credentials.stringOf("access_key"))
stringMatch1 = stringCompare.ContentsEqual("",true)
if ((credentials.JsonTypeOf("access_key") != 1) or (stringMatch1 == true))
    print "Missing or invalid access_key." + "\n";
    exit
end

stringCompare.SetString(credentials.stringOf("secret_key"))
stringMatch2 = stringCompare.ContentsEqual("",true)
if ((credentials.JsonTypeOf("secret_key") != 1) or (stringMatch2 == true))
    print "Missing or invalid secret_key." + "\n";
    exit
end

http = Chilkat::CkHttp.new()
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"))
    stringMatch3 = stringCompare.ContentsEqual("",true)
    if ((credentials.JsonTypeOf("session_token") != 1) or (stringMatch3 == true))
        print "session_token must be a nonempty string when supplied." + "\n";
        exit
    end

    http.put_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.put_AwsRegion(region)
endpoint = Chilkat::CkStringBuilder.new()
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.
bucketName = "your-bucket-name"
objectKey = "examples/archive.bin"
response = Chilkat::CkHttpResponse.new()
signer = Chilkat::CkCrypt2.new()
signer.put_Charset("utf-8")
signer.put_HashAlgorithm("sha256")
signer.put_EncodingMode("hexlower")
signer.put_MacAlgorithm("hmac")
now = Chilkat::CkDateTime.new()
timestamp = Chilkat::CkStringBuilder.new()
canonical = Chilkat::CkStringBuilder.new()
canonicalHeaders = Chilkat::CkStringBuilder.new()
signedHeaders = Chilkat::CkStringBuilder.new()
scope = Chilkat::CkStringBuilder.new()
stringToSign = Chilkat::CkStringBuilder.new()
signingKey = Chilkat::CkStringBuilder.new()
authorization = Chilkat::CkStringBuilder.new()
url = Chilkat::CkStringBuilder.new()
query = Chilkat::CkStringBuilder.new()
number = Chilkat::CkStringBuilder.new()
host = Chilkat::CkStringBuilder.new()
uri = Chilkat::CkStringBuilder.new()
xml = Chilkat::CkXml.new()

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) or (uri.Contains("/../",true) == true) or (uri.Contains("/./",true) == true))
    print "Use a key without a leading slash or dot path segments for these examples." + "\n";
    exit
end

uri.Prepend("/")
versionId = ""

files = Chilkat::CkFileAccess.new()
cacheDir = "qa_output/s3-download-cache"
manifestPath = "qa_output/s3-download-cache/state.json"
finalPath = "qa_output/s3-resumed.bin"
requestedVersionId = versionId
state = Chilkat::CkJsonObject.new()
state.put_Strict(true)
identity = Chilkat::CkJsonObject.new()
hasCheckpoint = files.FileExists(manifestPath)
if (hasCheckpoint == true)
    success = state.LoadFile(manifestPath)
    if (success != true)
        print "Invalid download checkpoint. Preserve the cache." + "\n";
        exit
    end

    stringCompare.SetString(state.stringOf("schema"))
    stringMatch4 = stringCompare.ContentsEqual("1",true)
    if (stringMatch4 != true)
        print "Checkpoint settings differ. Use the original settings or a new empty cache." + "\n";
        exit
    end

    stringCompare.SetString(state.stringOf("bucket"))
    stringMatch5 = stringCompare.ContentsEqual(bucketName,true)
    if (stringMatch5 != true)
        print "Checkpoint settings differ. Use the original settings or a new empty cache." + "\n";
        exit
    end

    stringCompare.SetString(state.stringOf("key"))
    stringMatch6 = stringCompare.ContentsEqual(objectKey,true)
    if (stringMatch6 != true)
        print "Checkpoint settings differ. Use the original settings or a new empty cache." + "\n";
        exit
    end

    stringCompare.SetString(state.stringOf("region"))
    stringMatch7 = stringCompare.ContentsEqual(region,true)
    if (stringMatch7 != true)
        print "Checkpoint settings differ. Use the original settings or a new empty cache." + "\n";
        exit
    end

    stringCompare.SetString(state.stringOf("requestedVersion"))
    stringMatch8 = stringCompare.ContentsEqual(requestedVersionId,true)
    if (stringMatch8 != true)
        print "Checkpoint settings differ. Use the original settings or a new empty cache." + "\n";
        exit
    end

    stringCompare.SetString(state.stringOf("finalPath"))
    stringMatch9 = stringCompare.ContentsEqual(finalPath,true)
    if (stringMatch9 != true)
        print "Checkpoint settings differ. Use the original settings or a new empty cache." + "\n";
        exit
    end

    stringCompare.SetString(state.stringOf("chunkSize"))
    stringMatch10 = stringCompare.ContentsEqual("8388608",true)
    if (stringMatch10 != true)
        print "Checkpoint settings differ. Use the original settings or a new empty cache." + "\n";
        exit
    end

    versionId = state.stringOf("versionId")
    if (state.JsonTypeOf("versionId") != 1)
        print "Checkpoint version ID is invalid." + "\n";
        exit
    end

end

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

    query.Append("versionId=")
    query.Append(http.urlEncode(versionId))
end

http.ClearHeaders()
success = now.SetFromCurrentSystemTime()
if (success != true)
    print "Could not read system time." + "\n";
    exit
end

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)
    print "Could not hash payload." + "\n";
    exit
end

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

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(";")
end

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(";")
end

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(";")
end

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(";")
    end

    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"))
end

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)
    print "Could not hash canonical request." + "\n";
    exit
end

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)
    print "Could not set signing key." + "\n";
    exit
end

derivedKey = signer.macStringENC(dateStamp)
if (signer.get_LastMethodSuccess() != true)
    print "Could not derive signing key." + "\n";
    exit
end

success = signer.SetMacKeyEncoded(derivedKey,"hex")
if (success != true)
    print "Could not set signing key." + "\n";
    exit
end

derivedKey = signer.macStringENC(region)
if (signer.get_LastMethodSuccess() != true)
    print "Could not derive signing key." + "\n";
    exit
end

success = signer.SetMacKeyEncoded(derivedKey,"hex")
if (success != true)
    print "Could not set signing key." + "\n";
    exit
end

derivedKey = signer.macStringENC("s3")
if (signer.get_LastMethodSuccess() != true)
    print "Could not derive signing key." + "\n";
    exit
end

success = signer.SetMacKeyEncoded(derivedKey,"hex")
if (success != true)
    print "Could not set signing key." + "\n";
    exit
end

derivedKey = signer.macStringENC("aws4_request")
if (signer.get_LastMethodSuccess() != true)
    print "Could not derive signing key." + "\n";
    exit
end

success = signer.SetMacKeyEncoded(derivedKey,"hex")
if (success != true)
    print "Could not set signing key." + "\n";
    exit
end

signature = signer.macStringENC(stringToSign.getAsString())
if (signer.get_LastMethodSuccess() != true)
    print "Could not sign request." + "\n";
    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.get_Length() > 0)
    url.Append("?")
    url.Append(query.getAsString())
end

success = http.HttpNoBody("HEAD",url.getAsString(),response)
if ((success != true) or (response.get_StatusCode() != 200))
    print "Request failed or returned unexpected HTTP status: " + response.get_StatusCode().to_s() + "\n";
    #  Preserve progress. Inspect full diagnostics privately; do not log secrets.
    exit
end

etag = response.getHeaderField("ETag")
stringCompare.SetString(etag)
stringMatch12 = stringCompare.ContentsEqual("",true)
if ((response.get_LastMethodSuccess() != true) or (stringMatch12 == true))
    print "Missing required response header ETag." + "\n";
    exit
end

expectedSize = response.getHeaderField("Content-Length")
stringCompare.SetString(expectedSize)
stringMatch13 = stringCompare.ContentsEqual("",true)
if ((response.get_LastMethodSuccess() != true) or (stringMatch13 == true))
    print "Missing required response header Content-Length." + "\n";
    exit
end

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

stringCompare.SetString(versionId)
stringMatch14 = stringCompare.ContentsEqual("",true)
if (stringMatch14 == true)
    versionId = returnedVersion
else
    stringCompare.SetString(returnedVersion)
    stringMatch15 = stringCompare.ContentsEqual(versionId,true)
    if (stringMatch15 != true)
        print "Unexpected object version." + "\n";
        exit
    end

end

expectedChecksum = response.getHeaderField("x-amz-checksum-sha256")
stringCompare.SetString(expectedChecksum)
stringMatch16 = stringCompare.ContentsEqual("",true)
if ((response.get_LastMethodSuccess() != true) or (stringMatch16 == true))
    print "Missing required response header x-amz-checksum-sha256." + "\n";
    exit
end

checksumType = response.getHeaderField("x-amz-checksum-type")
stringCompare.SetString(checksumType)
stringMatch17 = stringCompare.ContentsEqual("",true)
if ((response.get_LastMethodSuccess() != true) or (stringMatch17 == true))
    print "Missing required response header x-amz-checksum-type." + "\n";
    exit
end

stringCompare.SetString(checksumType)
stringMatch18 = stringCompare.ContentsEqual("FULL_OBJECT",true)
if (stringMatch18 != true)
    print "This example requires a FULL_OBJECT SHA-256 checksum; COMPOSITE needs separate verification." + "\n";
    exit
end

#  Portable decimal long division; no 32-bit byte-offset overflow.
chunkSize = 8388608
chunkCount = 0
remainder = 0
position = 0
sizeText = Chilkat::CkStringBuilder.new()
decimalDigits = Chilkat::CkStringBuilder.new()
digit = Chilkat::CkStringBuilder.new()
sizeText.Append(expectedSize)
decimalDigits.Append("0123456789")
if ((sizeText.get_Length() == 0) or (sizeText.get_Length() > 14))
    print "Invalid object size." + "\n";
    exit
end

while (position < sizeText.get_Length())
    digit.SetString(sizeText.getRange(position,1,false))
    if (decimalDigits.Contains(digit.getAsString(),true) != true)
        print "Invalid decimal object size." + "\n";
        exit
    end

    remainder = remainder * 10 + digit.get_IntValue()
    chunkCount = chunkCount * 10
    while (remainder >= chunkSize)
        chunkCount = chunkCount + 1
        remainder = remainder - chunkSize
    end
    position = position + 1
end
if (remainder != 0)
    chunkCount = chunkCount + 1
end

if ((chunkCount < 1) or (chunkCount > 10000))
    print "Use a nonempty object of at most 10,000 fixed 8 MiB chunks; empty objects use the single-download example." + "\n";
    exit
end

success = identity.UpdateString("schema","1")
if (success != true)
    print "Could not save schema." + "\n";
    exit
end

success = identity.UpdateString("bucket",bucketName)
if (success != true)
    print "Could not save bucket." + "\n";
    exit
end

success = identity.UpdateString("key",objectKey)
if (success != true)
    print "Could not save key." + "\n";
    exit
end

success = identity.UpdateString("region",region)
if (success != true)
    print "Could not save region." + "\n";
    exit
end

success = identity.UpdateString("requestedVersion",requestedVersionId)
if (success != true)
    print "Could not save requestedVersion." + "\n";
    exit
end

success = identity.UpdateString("versionId",versionId)
if (success != true)
    print "Could not save versionId." + "\n";
    exit
end

success = identity.UpdateString("etag",etag)
if (success != true)
    print "Could not save etag." + "\n";
    exit
end

success = identity.UpdateString("size",expectedSize)
if (success != true)
    print "Could not save size." + "\n";
    exit
end

success = identity.UpdateString("checksum",expectedChecksum)
if (success != true)
    print "Could not save checksum." + "\n";
    exit
end

success = identity.UpdateString("finalPath",finalPath)
if (success != true)
    print "Could not save finalPath." + "\n";
    exit
end

success = identity.UpdateString("chunkSize","8388608")
if (success != true)
    print "Could not save chunkSize." + "\n";
    exit
end

if (hasCheckpoint == true)
    stringCompare.SetString(state.stringOf("versionId"))
    stringMatch19 = stringCompare.ContentsEqual(identity.stringOf("versionId"),true)
    if (stringMatch19 != true)
        print "Object identity changed. Do not mix old cached bytes with this object." + "\n";
        exit
    end

    stringCompare.SetString(state.stringOf("etag"))
    stringMatch20 = stringCompare.ContentsEqual(identity.stringOf("etag"),true)
    if (stringMatch20 != true)
        print "Object identity changed. Do not mix old cached bytes with this object." + "\n";
        exit
    end

    stringCompare.SetString(state.stringOf("size"))
    stringMatch21 = stringCompare.ContentsEqual(identity.stringOf("size"),true)
    if (stringMatch21 != true)
        print "Object identity changed. Do not mix old cached bytes with this object." + "\n";
        exit
    end

    stringCompare.SetString(state.stringOf("checksum"))
    stringMatch22 = stringCompare.ContentsEqual(identity.stringOf("checksum"),true)
    if (stringMatch22 != true)
        print "Object identity changed. Do not mix old cached bytes with this object." + "\n";
        exit
    end

else
    success = files.DirEnsureExists(cacheDir)
    if (success != true)
        print "Could not create private cache." + "\n";
        exit
    end

    entries = Chilkat::CkDirTree.new()
    entries.put_BaseDir(cacheDir)
    entries.put_Recurse(false)
    success = entries.BeginIterate()
    if ((success == true) or (entries.get_DoneIterating() != true))
        print "First download requires an empty, readable cache directory." + "\n";
        exit
    end

    success = identity.WriteFile("qa_output/s3-download-cache/state.json.tmp")
    if (success != true)
        print "Could not save download identity." + "\n";
        exit
    end

    success = files.FileRename("qa_output/s3-download-cache/state.json.tmp",manifestPath)
    if (success != true)
        print "Checkpoint remains at its temporary path." + "\n";
        exit
    end

end

digest = Chilkat::CkCrypt2.new()
digest.put_HashAlgorithm("sha256")
digest.put_EncodingMode("base64")
if (files.FileExists(finalPath) == true)
    existingSize = files.fileSizeStr(finalPath)
    existingChecksum = digest.hashFileENC(finalPath)
    stringCompare.SetString(existingSize)
    stringMatch23 = stringCompare.ContentsEqual(expectedSize,true)
    stringCompare.SetString(existingChecksum)
    stringMatch24 = stringCompare.ContentsEqual(expectedChecksum,true)
    if ((digest.get_LastMethodSuccess() != true) or (stringMatch23 != true) or (stringMatch24 != true))
        print "Existing final file does not match; preserve it." + "\n";
        exit
    end

    print "Object already downloaded and checksum verified." + "\n";
    exit
end

digest.put_EncodingMode("hexlower")
path = Chilkat::CkStringBuilder.new()
range = Chilkat::CkStringBuilder.new()
digits = Chilkat::CkStringBuilder.new()
rangeHeader = Chilkat::CkStringBuilder.new()
contentRange = Chilkat::CkStringBuilder.new()
byteCount = Chilkat::CkStringBuilder.new()
receipt = Chilkat::CkJsonObject.new()
receipt.put_Strict(true)
received = Chilkat::CkMime.new()
chunkIndex = 0
byteHigh = 0
byteLow = 0

while (chunkIndex < chunkCount)
    chunkBytes = chunkSize
    if ((chunkIndex == chunkCount - 1) and (remainder != 0))
        chunkBytes = remainder
    end

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

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

    digits.Clear()
    digits.AppendInt(endLow)
    if (endHigh > 0)
        while (digits.get_Length() < 9)
            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) == true)
        success = receipt.LoadFile(receiptPath)
        if (success != true)
            print "Cached chunk has no valid receipt. Preserve the cache." + "\n";
            exit
        end

        actualHash = digest.hashFileENC(chunkPath)
        stringCompare.SetString(actualHash)
        stringMatch25 = stringCompare.ContentsEqual(receipt.stringOf("hash"),true)
        stringCompare.SetString(receipt.stringOf("range"))
        stringMatch26 = stringCompare.ContentsEqual(rangeKey,true)
        stringCompare.SetString(files.fileSizeStr(chunkPath))
        stringMatch27 = stringCompare.ContentsEqual(byteCount.getAsString(),true)
        if ((digest.get_LastMethodSuccess() != true) or (stringMatch25 != true) or (stringMatch26 != true) or (stringMatch27 != true))
            print "Cached chunk failed verification. Remove only this chunk and receipt before retrying." + "\n";
            exit
        end

        print "Reusing verified chunk: " + chunkIndex.to_s() + "\n";
    else
        query.Clear()
        stringCompare.SetString(versionId)
        stringMatch28 = stringCompare.ContentsEqual("",true)
        if (stringMatch28 != true)
            if (query.get_Length() > 0)
                query.Append("&")
            end

            query.Append("versionId=")
            query.Append(http.urlEncode(versionId))
        end

        http.ClearHeaders()
        success = now.SetFromCurrentSystemTime()
        if (success != true)
            print "Could not read system time." + "\n";
            exit
        end

        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)
            print "Could not hash payload." + "\n";
            exit
        end

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

        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(";")
        end

        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(";")
        end

        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(";")
        end

        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(";")
        end

        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(";")
            end

            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"))
        end

        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)
            print "Could not hash canonical request." + "\n";
            exit
        end

        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)
            print "Could not set signing key." + "\n";
            exit
        end

        derivedKey = signer.macStringENC(dateStamp)
        if (signer.get_LastMethodSuccess() != true)
            print "Could not derive signing key." + "\n";
            exit
        end

        success = signer.SetMacKeyEncoded(derivedKey,"hex")
        if (success != true)
            print "Could not set signing key." + "\n";
            exit
        end

        derivedKey = signer.macStringENC(region)
        if (signer.get_LastMethodSuccess() != true)
            print "Could not derive signing key." + "\n";
            exit
        end

        success = signer.SetMacKeyEncoded(derivedKey,"hex")
        if (success != true)
            print "Could not set signing key." + "\n";
            exit
        end

        derivedKey = signer.macStringENC("s3")
        if (signer.get_LastMethodSuccess() != true)
            print "Could not derive signing key." + "\n";
            exit
        end

        success = signer.SetMacKeyEncoded(derivedKey,"hex")
        if (success != true)
            print "Could not set signing key." + "\n";
            exit
        end

        derivedKey = signer.macStringENC("aws4_request")
        if (signer.get_LastMethodSuccess() != true)
            print "Could not derive signing key." + "\n";
            exit
        end

        success = signer.SetMacKeyEncoded(derivedKey,"hex")
        if (success != true)
            print "Could not set signing key." + "\n";
            exit
        end

        signature = signer.macStringENC(stringToSign.getAsString())
        if (signer.get_LastMethodSuccess() != true)
            print "Could not sign request." + "\n";
            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.get_Length() > 0)
            url.Append("?")
            url.Append(query.getAsString())
        end

        success = http.Download(url.getAsString(),partialPath)
        if ((http.get_LastStatus() == 412) or (http.get_LastStatus() == 416))
            print "Object changed or range is invalid. Preserve the cache; do not append." + "\n";
            exit
        end

        if ((success != true) or (http.get_LastStatus() != 206))
            print "Request failed or returned unexpected HTTP status: " + http.get_LastStatus().to_s() + "\n";
            #  Preserve progress. Inspect full diagnostics privately; do not log secrets.
            exit
        end

        success = received.LoadMime(http.lastResponseHeader())
        if (success != true)
            print "Could not parse range response." + "\n";
            exit
        end

        actualRange = received.getHeaderField("Content-Range")
        stringCompare.SetString(actualRange)
        stringMatch29 = stringCompare.ContentsEqual("",true)
        if ((received.get_LastMethodSuccess() != true) or (stringMatch29 == true))
            print "Missing download header Content-Range." + "\n";
            exit
        end

        actualLength = received.getHeaderField("Content-Length")
        stringCompare.SetString(actualLength)
        stringMatch30 = stringCompare.ContentsEqual("",true)
        if ((received.get_LastMethodSuccess() != true) or (stringMatch30 == true))
            print "Missing download header Content-Length." + "\n";
            exit
        end

        actualEtag = received.getHeaderField("ETag")
        stringCompare.SetString(actualEtag)
        stringMatch31 = stringCompare.ContentsEqual("",true)
        if ((received.get_LastMethodSuccess() != true) or (stringMatch31 == true))
            print "Missing download header ETag." + "\n";
            exit
        end

        stringCompare.SetString(actualRange)
        stringMatch32 = stringCompare.ContentsEqual(contentRange.getAsString(),true)
        stringCompare.SetString(actualLength)
        stringMatch33 = stringCompare.ContentsEqual(byteCount.getAsString(),true)
        stringCompare.SetString(actualEtag)
        stringMatch34 = stringCompare.ContentsEqual(etag,true)
        if ((stringMatch32 != true) or (stringMatch33 != true) or (stringMatch34 != true))
            print "Unexpected range response; no chunk committed." + "\n";
            exit
        end

        stringCompare.SetString(versionId)
        stringMatch35 = stringCompare.ContentsEqual("",true)
        if (stringMatch35 != true)
            actualVersion = received.getHeaderField("x-amz-version-id")
            stringCompare.SetString(actualVersion)
            stringMatch36 = stringCompare.ContentsEqual("",true)
            if ((received.get_LastMethodSuccess() != true) or (stringMatch36 == true))
                print "Missing download header x-amz-version-id." + "\n";
                exit
            end

            stringCompare.SetString(actualVersion)
            stringMatch37 = stringCompare.ContentsEqual(versionId,true)
            if (stringMatch37 != true)
                print "Unexpected returned version." + "\n";
                exit
            end

        end

        actualSize = files.fileSizeStr(partialPath)
        stringCompare.SetString(actualSize)
        stringMatch38 = stringCompare.ContentsEqual(byteCount.getAsString(),true)
        if ((files.get_LastMethodSuccess() != true) or (stringMatch38 != true))
            print "Range byte count mismatch." + "\n";
            exit
        end

        actualHash = digest.hashFileENC(partialPath)
        if (digest.get_LastMethodSuccess() != true)
            print "Could not hash range bytes." + "\n";
            exit
        end

        success = receipt.UpdateString("range",rangeKey)
        if (success != true)
            print "Could not save range." + "\n";
            exit
        end

        success = receipt.UpdateString("hash",actualHash)
        if (success != true)
            print "Could not save hash." + "\n";
            exit
        end

        success = receipt.WriteFile(receiptPath)
        if (success != true)
            print "Could not save chunk receipt." + "\n";
            exit
        end

        success = files.FileRename(partialPath,chunkPath)
        if (success != true)
            print "Could not commit downloaded chunk." + "\n";
            exit
        end

        print "Downloaded chunk: " + chunkIndex.to_s() + "\n";
    end

    byteHigh = endHigh
    byteLow = endLow + 1
    if (byteLow == 1000000000)
        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 = Chilkat::CkFileAccess.new()
success = assembled.OpenForWrite(assembledPath)
if (success != true)
    print "Could not open assembly file." + "\n";
    exit
end

data = Chilkat::CkBinData.new()
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)
    end

    if (success != true)
        assembled.FileClose()
        print "Assembly failed; verified progress is retained." + "\n";
        exit
    end

    chunkIndex = chunkIndex + 1
end
assembled.FileClose()
actualSize = files.fileSizeStr(assembledPath)
digest.put_EncodingMode("base64")
actualHash = digest.hashFileENC(assembledPath)
stringCompare.SetString(actualSize)
stringMatch39 = stringCompare.ContentsEqual(expectedSize,true)
stringCompare.SetString(actualHash)
stringMatch40 = stringCompare.ContentsEqual(expectedChecksum,true)
if ((digest.get_LastMethodSuccess() != true) or (stringMatch39 != true) or (stringMatch40 != true))
    print "Assembled object checksum/size mismatch; final file not created." + "\n";
    exit
end

success = files.FileRename(assembledPath,finalPath)
if (success != true)
    print "Verified assembly remains in cache; rename failed." + "\n";
    exit
end

print "Resumable download completed and checksum verified. Cache retained for manual cleanup." + "\n";