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

Lua
local chilkat = require("chilkat")

local stringCompare = chilkat.StringBuilder.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.
local credentials = chilkat.JsonObject.new()
credentials.strict = true
local success = credentials:load_file("qa_data/aws/s3.json")
if not success then
    print("Could not load private S3 credentials.")
    return
end

stringCompare:set_string(credentials:string_of("access_key"))
local stringMatch1 = stringCompare:contents_equal("", true)
if (credentials:json_type_of("access_key") ~= 1) or (stringMatch1) then
    print("Missing or invalid access_key.")
    return
end

stringCompare:set_string(credentials:string_of("secret_key"))
local stringMatch2 = stringCompare:contents_equal("", true)
if (credentials:json_type_of("secret_key") ~= 1) or (stringMatch2) then
    print("Missing or invalid secret_key.")
    return
end

local http = chilkat.Http.new()
http.aws_access_key = credentials:string_of("access_key")
http.aws_secret_key = credentials:string_of("secret_key")
if credentials:has_member("session_token") then
    stringCompare:set_string(credentials:string_of("session_token"))
    local stringMatch3 = stringCompare:contents_equal("", true)
    if (credentials:json_type_of("session_token") ~= 1) or (stringMatch3) then
        print("session_token must be a nonempty string when supplied.")
        return
    end

    http.aws_session_token = credentials:string_of("session_token")
end

-- Current Chilkat uses SigV4 by default. Do not select deprecated SigV2.
-- Set the actual bucket region, not the caller's location.
local region = "us-west-2"
http.aws_region = region
local endpoint = chilkat.StringBuilder.new()
endpoint:append("s3.")
endpoint:append(region)
endpoint:append(".amazonaws.com")
http.aws_endpoint = endpoint:get_as_string()
http.require_ssl_cert_verify = true
http.follow_redirects = false
-- A region redirect is not success. Correct the endpoint and signing region.
local bucketName = "your-bucket-name"
local objectKey = "examples/archive.bin"
local response = chilkat.HttpResponse.new()
local signer = chilkat.Crypt2.new()
signer.charset = "utf-8"
signer.hash_algorithm = "sha256"
signer.encoding_mode = "hexlower"
signer.mac_algorithm = "hmac"
local now = chilkat.DateTime.new()
local timestamp = chilkat.StringBuilder.new()
local canonical = chilkat.StringBuilder.new()
local canonicalHeaders = chilkat.StringBuilder.new()
local signedHeaders = chilkat.StringBuilder.new()
local scope = chilkat.StringBuilder.new()
local stringToSign = chilkat.StringBuilder.new()
local signingKey = chilkat.StringBuilder.new()
local authorization = chilkat.StringBuilder.new()
local url = chilkat.StringBuilder.new()
local query = chilkat.StringBuilder.new()
local number = chilkat.StringBuilder.new()
local host = chilkat.StringBuilder.new()
local uri = chilkat.StringBuilder.new()
local xml = chilkat.Xml.new()
host:append(bucketName)
host:append(".")
host:append(endpoint:get_as_string())
-- Encode the original key exactly once, preserving S3 path separators.
uri:set_string(http:url_encode(objectKey))
local replaceCount = uri:replace_no_case("%2f", "/")
if (uri:starts_with("/", true)) or ((uri:contains("/../", true)) or (uri:contains("/./", true))) then
    print("Use a key without a leading slash or dot path segments for these examples.")
    return
end

uri:prepend("/")
local versionId = ""
local files = chilkat.FileAccess.new()
local cacheDir = "qa_output/s3-download-cache"
local manifestPath = "qa_output/s3-download-cache/state.json"
local finalPath = "qa_output/s3-resumed.bin"
local requestedVersionId = versionId
local state = chilkat.JsonObject.new()
state.strict = true
local identity = chilkat.JsonObject.new()
local hasCheckpoint = files:file_exists(manifestPath)
if hasCheckpoint then
    success = state:load_file(manifestPath)
    if not success then
        print("Invalid download checkpoint. Preserve the cache.")
        return
    end

    stringCompare:set_string(state:string_of("schema"))
    local stringMatch4 = stringCompare:contents_equal("1", true)
    if not stringMatch4 then
        print("Checkpoint settings differ. Use the original settings or a new empty cache.")
        return
    end

    stringCompare:set_string(state:string_of("bucket"))
    local stringMatch5 = stringCompare:contents_equal(bucketName, true)
    if not stringMatch5 then
        print("Checkpoint settings differ. Use the original settings or a new empty cache.")
        return
    end

    stringCompare:set_string(state:string_of("key"))
    local stringMatch6 = stringCompare:contents_equal(objectKey, true)
    if not stringMatch6 then
        print("Checkpoint settings differ. Use the original settings or a new empty cache.")
        return
    end

    stringCompare:set_string(state:string_of("region"))
    local stringMatch7 = stringCompare:contents_equal(region, true)
    if not stringMatch7 then
        print("Checkpoint settings differ. Use the original settings or a new empty cache.")
        return
    end

    stringCompare:set_string(state:string_of("requestedVersion"))
    local stringMatch8 = stringCompare:contents_equal(requestedVersionId, true)
    if not stringMatch8 then
        print("Checkpoint settings differ. Use the original settings or a new empty cache.")
        return
    end

    stringCompare:set_string(state:string_of("finalPath"))
    local stringMatch9 = stringCompare:contents_equal(finalPath, true)
    if not stringMatch9 then
        print("Checkpoint settings differ. Use the original settings or a new empty cache.")
        return
    end

    stringCompare:set_string(state:string_of("chunkSize"))
    local stringMatch10 = stringCompare:contents_equal("8388608", true)
    if not stringMatch10 then
        print("Checkpoint settings differ. Use the original settings or a new empty cache.")
        return
    end

    versionId = state:string_of("versionId")
    if state:json_type_of("versionId") ~= 1 then
        print("Checkpoint version ID is invalid.")
        return
    end
end

query:clear()
stringCompare:set_string(versionId)
local stringMatch11 = stringCompare:contents_equal("", true)
if not stringMatch11 then
    if query.length > 0 then
        query:append("&")
    end

    query:append("versionId=")
    query:append(http:url_encode(versionId))
end

http:clear_headers()
success = now:set_from_current_system_time()
if not success then
    print("Could not read system time.")
    return
end

timestamp:set_string(now:get_as_timestamp(false))
replaceCount = timestamp:replace("-", "")
replaceCount = timestamp:replace(":", "")
local amzDate = timestamp:get_as_string()
local dateStamp = timestamp:get_range(0, 8, false)
local payloadHash = signer:hash_string_enc("")
if not signer.last_method_success then
    print("Could not hash payload.")
    return
end

canonicalHeaders:clear()
signedHeaders:clear()
if signedHeaders.length > 0 then
    signedHeaders:append(";")
end

signedHeaders:append("host")
canonicalHeaders:append("host:")
canonicalHeaders:append(host:get_as_string())
canonicalHeaders:append("\n")
http:set_request_header("host", host:get_as_string())
if signedHeaders.length > 0 then
    signedHeaders:append(";")
end

signedHeaders:append("x-amz-checksum-mode")
canonicalHeaders:append("x-amz-checksum-mode:")
canonicalHeaders:append("ENABLED")
canonicalHeaders:append("\n")
http:set_request_header("x-amz-checksum-mode", "ENABLED")
if signedHeaders.length > 0 then
    signedHeaders:append(";")
end

signedHeaders:append("x-amz-content-sha256")
canonicalHeaders:append("x-amz-content-sha256:")
canonicalHeaders:append(payloadHash)
canonicalHeaders:append("\n")
http:set_request_header("x-amz-content-sha256", payloadHash)
if signedHeaders.length > 0 then
    signedHeaders:append(";")
end

signedHeaders:append("x-amz-date")
canonicalHeaders:append("x-amz-date:")
canonicalHeaders:append(amzDate)
canonicalHeaders:append("\n")
http:set_request_header("x-amz-date", amzDate)
if credentials:has_member("session_token") then
    if signedHeaders.length > 0 then
        signedHeaders:append(";")
    end

    signedHeaders:append("x-amz-security-token")
    canonicalHeaders:append("x-amz-security-token:")
    canonicalHeaders:append(credentials:string_of("session_token"))
    canonicalHeaders:append("\n")
    http:set_request_header("x-amz-security-token", credentials:string_of("session_token"))
end

canonical:clear()
canonical:append("HEAD\n")
canonical:append(uri:get_as_string())
canonical:append("\n")
canonical:append(query:get_as_string())
canonical:append("\n")
canonical:append(canonicalHeaders:get_as_string())
canonical:append("\n")
canonical:append(signedHeaders:get_as_string())
canonical:append("\n")
canonical:append(payloadHash)
local canonicalHash = signer:hash_string_enc(canonical:get_as_string())
if not signer.last_method_success then
    print("Could not hash canonical request.")
    return
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:get_as_string())
stringToSign:append("\n")
stringToSign:append(canonicalHash)
signingKey:set_string("AWS4")
signingKey:append(credentials:string_of("secret_key"))
success = signer:set_mac_key_string(signingKey:get_as_string())
if not success then
    print("Could not set signing key.")
    return
end

local derivedKey = signer:mac_string_enc(dateStamp)
if not signer.last_method_success then
    print("Could not derive signing key.")
    return
end

success = signer:set_mac_key_encoded(derivedKey, "hex")
if not success then
    print("Could not set signing key.")
    return
end

derivedKey = signer:mac_string_enc(region)
if not signer.last_method_success then
    print("Could not derive signing key.")
    return
end

success = signer:set_mac_key_encoded(derivedKey, "hex")
if not success then
    print("Could not set signing key.")
    return
end

derivedKey = signer:mac_string_enc("s3")
if not signer.last_method_success then
    print("Could not derive signing key.")
    return
end

success = signer:set_mac_key_encoded(derivedKey, "hex")
if not success then
    print("Could not set signing key.")
    return
end

derivedKey = signer:mac_string_enc("aws4_request")
if not signer.last_method_success then
    print("Could not derive signing key.")
    return
end

success = signer:set_mac_key_encoded(derivedKey, "hex")
if not success then
    print("Could not set signing key.")
    return
end

local signature = signer:mac_string_enc(stringToSign:get_as_string())
if not signer.last_method_success then
    print("Could not sign request.")
    return
end

authorization:clear()
authorization:append("AWS4-HMAC-SHA256 Credential=")
authorization:append(credentials:string_of("access_key"))
authorization:append("/")
authorization:append(scope:get_as_string())
authorization:append(", SignedHeaders=")
authorization:append(signedHeaders:get_as_string())
authorization:append(", Signature=")
authorization:append(signature)
http:set_request_header("Authorization", authorization:get_as_string())
url:set_string("https://")
url:append(host:get_as_string())
url:append(uri:get_as_string())
if query.length > 0 then
    url:append("?")
    url:append(query:get_as_string())
end

success = http:http_no_body("HEAD", url:get_as_string(), response)
if (not success) or (response.status_code ~= 200) then
    print("Request failed or returned unexpected HTTP status: " .. response.status_code)
    -- Preserve progress. Inspect full diagnostics privately; do not log secrets.
    return
end

local etag = response:get_header_field("ETag")
stringCompare:set_string(etag)
local stringMatch12 = stringCompare:contents_equal("", true)
if (not response.last_method_success) or (stringMatch12) then
    print("Missing required response header ETag.")
    return
end

local expectedSize = response:get_header_field("Content-Length")
stringCompare:set_string(expectedSize)
local stringMatch13 = stringCompare:contents_equal("", true)
if (not response.last_method_success) or (stringMatch13) then
    print("Missing required response header Content-Length.")
    return
end

local returnedVersion = response:get_header_field("x-amz-version-id")
if not response.last_method_success then
    returnedVersion = ""
end

stringCompare:set_string(versionId)
local stringMatch14 = stringCompare:contents_equal("", true)
if stringMatch14 then
    versionId = returnedVersion
else
    stringCompare:set_string(returnedVersion)
    local stringMatch15 = stringCompare:contents_equal(versionId, true)
    if not stringMatch15 then
        print("Unexpected object version.")
        return
    end
end

local expectedChecksum = response:get_header_field("x-amz-checksum-sha256")
stringCompare:set_string(expectedChecksum)
local stringMatch16 = stringCompare:contents_equal("", true)
if (not response.last_method_success) or (stringMatch16) then
    print("Missing required response header x-amz-checksum-sha256.")
    return
end

local checksumType = response:get_header_field("x-amz-checksum-type")
stringCompare:set_string(checksumType)
local stringMatch17 = stringCompare:contents_equal("", true)
if (not response.last_method_success) or (stringMatch17) then
    print("Missing required response header x-amz-checksum-type.")
    return
end

stringCompare:set_string(checksumType)
local stringMatch18 = stringCompare:contents_equal("FULL_OBJECT", true)
if not stringMatch18 then
    print("This example requires a FULL_OBJECT SHA-256 checksum; COMPOSITE needs separate verification.")
    return
end

-- Portable decimal long division; no 32-bit byte-offset overflow.
local chunkSize = 8388608
local chunkCount = 0
local remainder = 0
local position = 0
local sizeText = chilkat.StringBuilder.new()
local decimalDigits = chilkat.StringBuilder.new()
local digit = chilkat.StringBuilder.new()
sizeText:append(expectedSize)
decimalDigits:append("0123456789")
if (sizeText.length == 0) or (sizeText.length > 14) then
    print("Invalid object size.")
    return
end

while position < sizeText.length do
    digit:set_string(sizeText:get_range(position, 1, false))
    if not decimalDigits:contains(digit:get_as_string(), true) then
        print("Invalid decimal object size.")
        return
    end

    remainder = remainder * 10 + digit.int_value
    chunkCount = chunkCount * 10
    while remainder >= chunkSize do
        chunkCount = chunkCount + 1
        remainder = remainder - chunkSize
    end

    position = position + 1
end

if remainder ~= 0 then
    chunkCount = chunkCount + 1
end

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

success = identity:update_string("schema", "1")
if not success then
    print("Could not save schema.")
    return
end

success = identity:update_string("bucket", bucketName)
if not success then
    print("Could not save bucket.")
    return
end

success = identity:update_string("key", objectKey)
if not success then
    print("Could not save key.")
    return
end

success = identity:update_string("region", region)
if not success then
    print("Could not save region.")
    return
end

success = identity:update_string("requestedVersion", requestedVersionId)
if not success then
    print("Could not save requestedVersion.")
    return
end

success = identity:update_string("versionId", versionId)
if not success then
    print("Could not save versionId.")
    return
end

success = identity:update_string("etag", etag)
if not success then
    print("Could not save etag.")
    return
end

success = identity:update_string("size", expectedSize)
if not success then
    print("Could not save size.")
    return
end

success = identity:update_string("checksum", expectedChecksum)
if not success then
    print("Could not save checksum.")
    return
end

success = identity:update_string("finalPath", finalPath)
if not success then
    print("Could not save finalPath.")
    return
end

success = identity:update_string("chunkSize", "8388608")
if not success then
    print("Could not save chunkSize.")
    return
end

if hasCheckpoint then
    stringCompare:set_string(state:string_of("versionId"))
    local stringMatch19 = stringCompare:contents_equal(identity:string_of("versionId"), true)
    if not stringMatch19 then
        print("Object identity changed. Do not mix old cached bytes with this object.")
        return
    end

    stringCompare:set_string(state:string_of("etag"))
    local stringMatch20 = stringCompare:contents_equal(identity:string_of("etag"), true)
    if not stringMatch20 then
        print("Object identity changed. Do not mix old cached bytes with this object.")
        return
    end

    stringCompare:set_string(state:string_of("size"))
    local stringMatch21 = stringCompare:contents_equal(identity:string_of("size"), true)
    if not stringMatch21 then
        print("Object identity changed. Do not mix old cached bytes with this object.")
        return
    end

    stringCompare:set_string(state:string_of("checksum"))
    local stringMatch22 = stringCompare:contents_equal(identity:string_of("checksum"), true)
    if not stringMatch22 then
        print("Object identity changed. Do not mix old cached bytes with this object.")
        return
    end
else
    success = files:dir_ensure_exists(cacheDir)
    if not success then
        print("Could not create private cache.")
        return
    end

    local entries = chilkat.DirTree.new()
    entries.base_dir = cacheDir
    entries.recurse = false
    success = entries:begin_iterate()
    if (success) or (not entries.done_iterating) then
        print("First download requires an empty, readable cache directory.")
        return
    end

    success = identity:write_file("qa_output/s3-download-cache/state.json.tmp")
    if not success then
        print("Could not save download identity.")
        return
    end

    success = files:file_rename("qa_output/s3-download-cache/state.json.tmp", manifestPath)
    if not success then
        print("Checkpoint remains at its temporary path.")
        return
    end
end

local digest = chilkat.Crypt2.new()
digest.hash_algorithm = "sha256"
digest.encoding_mode = "base64"
if files:file_exists(finalPath) then
    local existingSize = files:file_size_str(finalPath)
    local existingChecksum = digest:hash_file_enc(finalPath)
    stringCompare:set_string(existingSize)
    local stringMatch23 = stringCompare:contents_equal(expectedSize, true)
    stringCompare:set_string(existingChecksum)
    local stringMatch24 = stringCompare:contents_equal(expectedChecksum, true)
    if (not digest.last_method_success) or ((not stringMatch23) or (not stringMatch24)) then
        print("Existing final file does not match; preserve it.")
        return
    end

    print("Object already downloaded and checksum verified.")
    return
end

digest.encoding_mode = "hexlower"
local path = chilkat.StringBuilder.new()
local range = chilkat.StringBuilder.new()
local digits = chilkat.StringBuilder.new()
local rangeHeader = chilkat.StringBuilder.new()
local contentRange = chilkat.StringBuilder.new()
local byteCount = chilkat.StringBuilder.new()
local receipt = chilkat.JsonObject.new()
receipt.strict = true
local received = chilkat.Mime.new()
local chunkIndex = 0
local byteHigh = 0
local byteLow = 0
local endHigh = 0
local endLow = 0
local actualRange = ""
local actualLength = ""
local actualEtag = ""
local actualVersion = ""
local actualSize = ""
local actualHash = ""
while chunkIndex < chunkCount do
    local chunkBytes = chunkSize
    if (chunkIndex == chunkCount - 1) and (remainder ~= 0) then
        chunkBytes = remainder
    end

    range:clear()
    digits:clear()
    digits:append_int(byteLow)
    if byteHigh > 0 then
        while digits.length < 9 do
            digits:prepend("0")
        end

        range:append_int(byteHigh)
    end

    range:append(digits:get_as_string())
    range:append("-")
    endHigh = byteHigh
    endLow = byteLow + chunkBytes - 1
    if endLow >= 1000000000 then
        endLow = endLow - 1000000000
        endHigh = endHigh + 1
    end

    digits:clear()
    digits:append_int(endLow)
    if endHigh > 0 then
        while digits.length < 9 do
            digits:prepend("0")
        end

        range:append_int(endHigh)
    end

    range:append(digits:get_as_string())
    local rangeKey = range:get_as_string()
    rangeHeader:set_string("bytes=")
    rangeHeader:append(rangeKey)
    contentRange:set_string("bytes ")
    contentRange:append(rangeKey)
    contentRange:append("/")
    contentRange:append(expectedSize)
    byteCount:clear()
    byteCount:append_int(chunkBytes)
    path:set_string(cacheDir)
    path:append("/chunk-")
    path:append_int(chunkIndex)
    local chunkPath = path:get_as_string()
    path:append(".json")
    local receiptPath = path:get_as_string()
    path:set_string(chunkPath)
    path:append(".part")
    local partialPath = path:get_as_string()
    if files:file_exists(chunkPath) then
        success = receipt:load_file(receiptPath)
        if not success then
            print("Cached chunk has no valid receipt. Preserve the cache.")
            return
        end

        actualHash = digest:hash_file_enc(chunkPath)
        stringCompare:set_string(actualHash)
        local stringMatch25 = stringCompare:contents_equal(receipt:string_of("hash"), true)
        stringCompare:set_string(receipt:string_of("range"))
        local stringMatch26 = stringCompare:contents_equal(rangeKey, true)
        stringCompare:set_string(files:file_size_str(chunkPath))
        local stringMatch27 = stringCompare:contents_equal(byteCount:get_as_string(), true)
        if (not digest.last_method_success) or ((not stringMatch25) or ((not stringMatch26) or (not stringMatch27))) then
            print("Cached chunk failed verification. Remove only this chunk and receipt before retrying.")
            return
        end

        print("Reusing verified chunk: " .. chunkIndex)
    else
        query:clear()
        stringCompare:set_string(versionId)
        local stringMatch28 = stringCompare:contents_equal("", true)
        if not stringMatch28 then
            if query.length > 0 then
                query:append("&")
            end

            query:append("versionId=")
            query:append(http:url_encode(versionId))
        end

        http:clear_headers()
        success = now:set_from_current_system_time()
        if not success then
            print("Could not read system time.")
            return
        end

        timestamp:set_string(now:get_as_timestamp(false))
        replaceCount = timestamp:replace("-", "")
        replaceCount = timestamp:replace(":", "")
        amzDate = timestamp:get_as_string()
        dateStamp = timestamp:get_range(0, 8, false)
        payloadHash = signer:hash_string_enc("")
        if not signer.last_method_success then
            print("Could not hash payload.")
            return
        end

        canonicalHeaders:clear()
        signedHeaders:clear()
        if signedHeaders.length > 0 then
            signedHeaders:append(";")
        end

        signedHeaders:append("host")
        canonicalHeaders:append("host:")
        canonicalHeaders:append(host:get_as_string())
        canonicalHeaders:append("\n")
        http:set_request_header("host", host:get_as_string())
        if signedHeaders.length > 0 then
            signedHeaders:append(";")
        end

        signedHeaders:append("if-match")
        canonicalHeaders:append("if-match:")
        canonicalHeaders:append(etag)
        canonicalHeaders:append("\n")
        http:set_request_header("if-match", etag)
        if signedHeaders.length > 0 then
            signedHeaders:append(";")
        end

        signedHeaders:append("range")
        canonicalHeaders:append("range:")
        canonicalHeaders:append(rangeHeader:get_as_string())
        canonicalHeaders:append("\n")
        http:set_request_header("range", rangeHeader:get_as_string())
        if signedHeaders.length > 0 then
            signedHeaders:append(";")
        end

        signedHeaders:append("x-amz-content-sha256")
        canonicalHeaders:append("x-amz-content-sha256:")
        canonicalHeaders:append(payloadHash)
        canonicalHeaders:append("\n")
        http:set_request_header("x-amz-content-sha256", payloadHash)
        if signedHeaders.length > 0 then
            signedHeaders:append(";")
        end

        signedHeaders:append("x-amz-date")
        canonicalHeaders:append("x-amz-date:")
        canonicalHeaders:append(amzDate)
        canonicalHeaders:append("\n")
        http:set_request_header("x-amz-date", amzDate)
        if credentials:has_member("session_token") then
            if signedHeaders.length > 0 then
                signedHeaders:append(";")
            end

            signedHeaders:append("x-amz-security-token")
            canonicalHeaders:append("x-amz-security-token:")
            canonicalHeaders:append(credentials:string_of("session_token"))
            canonicalHeaders:append("\n")
            http:set_request_header("x-amz-security-token", credentials:string_of("session_token"))
        end

        canonical:clear()
        canonical:append("GET\n")
        canonical:append(uri:get_as_string())
        canonical:append("\n")
        canonical:append(query:get_as_string())
        canonical:append("\n")
        canonical:append(canonicalHeaders:get_as_string())
        canonical:append("\n")
        canonical:append(signedHeaders:get_as_string())
        canonical:append("\n")
        canonical:append(payloadHash)
        canonicalHash = signer:hash_string_enc(canonical:get_as_string())
        if not signer.last_method_success then
            print("Could not hash canonical request.")
            return
        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:get_as_string())
        stringToSign:append("\n")
        stringToSign:append(canonicalHash)
        signingKey:set_string("AWS4")
        signingKey:append(credentials:string_of("secret_key"))
        success = signer:set_mac_key_string(signingKey:get_as_string())
        if not success then
            print("Could not set signing key.")
            return
        end

        derivedKey = signer:mac_string_enc(dateStamp)
        if not signer.last_method_success then
            print("Could not derive signing key.")
            return
        end

        success = signer:set_mac_key_encoded(derivedKey, "hex")
        if not success then
            print("Could not set signing key.")
            return
        end

        derivedKey = signer:mac_string_enc(region)
        if not signer.last_method_success then
            print("Could not derive signing key.")
            return
        end

        success = signer:set_mac_key_encoded(derivedKey, "hex")
        if not success then
            print("Could not set signing key.")
            return
        end

        derivedKey = signer:mac_string_enc("s3")
        if not signer.last_method_success then
            print("Could not derive signing key.")
            return
        end

        success = signer:set_mac_key_encoded(derivedKey, "hex")
        if not success then
            print("Could not set signing key.")
            return
        end

        derivedKey = signer:mac_string_enc("aws4_request")
        if not signer.last_method_success then
            print("Could not derive signing key.")
            return
        end

        success = signer:set_mac_key_encoded(derivedKey, "hex")
        if not success then
            print("Could not set signing key.")
            return
        end

        signature = signer:mac_string_enc(stringToSign:get_as_string())
        if not signer.last_method_success then
            print("Could not sign request.")
            return
        end

        authorization:clear()
        authorization:append("AWS4-HMAC-SHA256 Credential=")
        authorization:append(credentials:string_of("access_key"))
        authorization:append("/")
        authorization:append(scope:get_as_string())
        authorization:append(", SignedHeaders=")
        authorization:append(signedHeaders:get_as_string())
        authorization:append(", Signature=")
        authorization:append(signature)
        http:set_request_header("Authorization", authorization:get_as_string())
        url:set_string("https://")
        url:append(host:get_as_string())
        url:append(uri:get_as_string())
        if query.length > 0 then
            url:append("?")
            url:append(query:get_as_string())
        end

        success = http:download(url:get_as_string(), partialPath)
        if (http.last_status == 412) or (http.last_status == 416) then
            print("Object changed or range is invalid. Preserve the cache; do not append.")
            return
        end

        if (not success) or (http.last_status ~= 206) then
            print("Request failed or returned unexpected HTTP status: " .. http.last_status)
            -- Preserve progress. Inspect full diagnostics privately; do not log secrets.
            return
        end

        success = received:load_mime(http.last_response_header)
        if not success then
            print("Could not parse range response.")
            return
        end

        actualRange = received:get_header_field("Content-Range")
        stringCompare:set_string(actualRange)
        local stringMatch29 = stringCompare:contents_equal("", true)
        if (not received.last_method_success) or (stringMatch29) then
            print("Missing download header Content-Range.")
            return
        end

        actualLength = received:get_header_field("Content-Length")
        stringCompare:set_string(actualLength)
        local stringMatch30 = stringCompare:contents_equal("", true)
        if (not received.last_method_success) or (stringMatch30) then
            print("Missing download header Content-Length.")
            return
        end

        actualEtag = received:get_header_field("ETag")
        stringCompare:set_string(actualEtag)
        local stringMatch31 = stringCompare:contents_equal("", true)
        if (not received.last_method_success) or (stringMatch31) then
            print("Missing download header ETag.")
            return
        end

        stringCompare:set_string(actualRange)
        local stringMatch32 = stringCompare:contents_equal(contentRange:get_as_string(), true)
        stringCompare:set_string(actualLength)
        local stringMatch33 = stringCompare:contents_equal(byteCount:get_as_string(), true)
        stringCompare:set_string(actualEtag)
        local stringMatch34 = stringCompare:contents_equal(etag, true)
        if (not stringMatch32) or ((not stringMatch33) or (not stringMatch34)) then
            print("Unexpected range response; no chunk committed.")
            return
        end

        stringCompare:set_string(versionId)
        local stringMatch35 = stringCompare:contents_equal("", true)
        if not stringMatch35 then
            actualVersion = received:get_header_field("x-amz-version-id")
            stringCompare:set_string(actualVersion)
            local stringMatch36 = stringCompare:contents_equal("", true)
            if (not received.last_method_success) or (stringMatch36) then
                print("Missing download header x-amz-version-id.")
                return
            end

            stringCompare:set_string(actualVersion)
            local stringMatch37 = stringCompare:contents_equal(versionId, true)
            if not stringMatch37 then
                print("Unexpected returned version.")
                return
            end
        end

        actualSize = files:file_size_str(partialPath)
        stringCompare:set_string(actualSize)
        local stringMatch38 = stringCompare:contents_equal(byteCount:get_as_string(), true)
        if (not files.last_method_success) or (not stringMatch38) then
            print("Range byte count mismatch.")
            return
        end

        actualHash = digest:hash_file_enc(partialPath)
        if not digest.last_method_success then
            print("Could not hash range bytes.")
            return
        end

        success = receipt:update_string("range", rangeKey)
        if not success then
            print("Could not save range.")
            return
        end

        success = receipt:update_string("hash", actualHash)
        if not success then
            print("Could not save hash.")
            return
        end

        success = receipt:write_file(receiptPath)
        if not success then
            print("Could not save chunk receipt.")
            return
        end

        success = files:file_rename(partialPath, chunkPath)
        if not success then
            print("Could not commit downloaded chunk.")
            return
        end

        print("Downloaded chunk: " .. chunkIndex)
    end

    byteHigh = endHigh
    byteLow = endLow + 1
    if byteLow == 1000000000 then
        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.
local assembledPath = "qa_output/s3-download-cache/assembled.part"
local assembled = chilkat.FileAccess.new()
success = assembled:open_for_write(assembledPath)
if not success then
    print("Could not open assembly file.")
    return
end

local data = chilkat.BinData.new()
chunkIndex = 0
while chunkIndex < chunkCount do
    path:set_string(cacheDir)
    path:append("/chunk-")
    path:append_int(chunkIndex)
    data:clear()
    success = data:load_file(path:get_as_string())
    if success then
        success = assembled:file_write_bd(data, 0, 0)
    end

    if not success then
        assembled:file_close()
        print("Assembly failed; verified progress is retained.")
        return
    end

    chunkIndex = chunkIndex + 1
end

assembled:file_close()
actualSize = files:file_size_str(assembledPath)
digest.encoding_mode = "base64"
actualHash = digest:hash_file_enc(assembledPath)
stringCompare:set_string(actualSize)
local stringMatch39 = stringCompare:contents_equal(expectedSize, true)
stringCompare:set_string(actualHash)
local stringMatch40 = stringCompare:contents_equal(expectedChecksum, true)
if (not digest.last_method_success) or ((not stringMatch39) or (not stringMatch40)) then
    print("Assembled object checksum/size mismatch; final file not created.")
    return
end

success = files:file_rename(assembledPath, finalPath)
if not success then
    print("Verified assembly remains in cache; rename failed.")
    return
end

print("Resumable download completed and checksum verified. Cache retained for manual cleanup.")