S3 Http: Download and Verify a Full-Object SHA-256 Checksum
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.
For objects uploaded with a FULL_OBJECT SHA-256 checksum, reads HEAD checksum metadata, pins a returned version ID and ETag, downloads using If-Match, and checks returned metadata, actual byte count and the locally computed base64 SHA-256 before renaming. Empty objects are supported. Create qa_output first; existing output paths are not overwritten.
COMPOSITE or absent SHA-256 checksums stop explicitly. Use the companion single-PUT checksum upload to create a suitable object. Requires s3:GetObject/s3:GetObjectVersion and applicable KMS permissions. No multipart ETag-as-MD5 assumption.
Chilkat Lua Downloads
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 finalPath = "qa_output/s3-download.bin"
local partialPath = "qa_output/s3-download.bin.part"
if (files:file_exists(finalPath)) or (files:file_exists(partialPath)) then
print("Choose unused output paths.")
return
end
query:clear()
stringCompare:set_string(versionId)
local stringMatch4 = stringCompare:contents_equal("", true)
if not stringMatch4 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 stringMatch5 = stringCompare:contents_equal("", true)
if (not response.last_method_success) or (stringMatch5) then
print("Missing required response header ETag.")
return
end
local expectedSize = response:get_header_field("Content-Length")
stringCompare:set_string(expectedSize)
local stringMatch6 = stringCompare:contents_equal("", true)
if (not response.last_method_success) or (stringMatch6) 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 stringMatch7 = stringCompare:contents_equal("", true)
if stringMatch7 then
versionId = returnedVersion
else
stringCompare:set_string(returnedVersion)
local stringMatch8 = stringCompare:contents_equal(versionId, true)
if not stringMatch8 then
print("Unexpected object version.")
return
end
end
local expectedChecksum = response:get_header_field("x-amz-checksum-sha256")
stringCompare:set_string(expectedChecksum)
local stringMatch9 = stringCompare:contents_equal("", true)
if (not response.last_method_success) or (stringMatch9) 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 stringMatch10 = stringCompare:contents_equal("", true)
if (not response.last_method_success) or (stringMatch10) then
print("Missing required response header x-amz-checksum-type.")
return
end
stringCompare:set_string(checksumType)
local stringMatch11 = stringCompare:contents_equal("FULL_OBJECT", true)
if not stringMatch11 then
print("This example requires a FULL_OBJECT SHA-256 checksum; COMPOSITE needs separate verification.")
return
end
query:clear()
stringCompare:set_string(versionId)
local stringMatch12 = stringCompare:contents_equal("", true)
if not stringMatch12 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("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("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 (not success) or (http.last_status ~= 200) then
print("Request failed or returned unexpected HTTP status: " .. http.last_status)
-- Preserve progress. Inspect full diagnostics privately; do not log secrets.
return
end
local received = chilkat.Mime.new()
success = received:load_mime(http.last_response_header)
if not success then
print("Could not parse download headers.")
return
end
local receivedSize = received:get_header_field("Content-Length")
stringCompare:set_string(receivedSize)
local stringMatch13 = stringCompare:contents_equal("", true)
if (not received.last_method_success) or (stringMatch13) then
print("Missing download header Content-Length.")
return
end
local receivedHash = received:get_header_field("x-amz-checksum-sha256")
stringCompare:set_string(receivedHash)
local stringMatch14 = stringCompare:contents_equal("", true)
if (not received.last_method_success) or (stringMatch14) then
print("Missing download header x-amz-checksum-sha256.")
return
end
local receivedType = received:get_header_field("x-amz-checksum-type")
stringCompare:set_string(receivedType)
local stringMatch15 = stringCompare:contents_equal("", true)
if (not received.last_method_success) or (stringMatch15) then
print("Missing download header x-amz-checksum-type.")
return
end
stringCompare:set_string(receivedSize)
local stringMatch16 = stringCompare:contents_equal(expectedSize, true)
stringCompare:set_string(receivedHash)
local stringMatch17 = stringCompare:contents_equal(expectedChecksum, true)
stringCompare:set_string(receivedType)
local stringMatch18 = stringCompare:contents_equal("FULL_OBJECT", true)
if (not stringMatch16) or ((not stringMatch17) or (not stringMatch18)) then
print("Download metadata changed; preserve the temporary file.")
return
end
local actualSize = files:file_size_str(partialPath)
stringCompare:set_string(actualSize)
local stringMatch19 = stringCompare:contents_equal(expectedSize, true)
if (not files.last_method_success) or (not stringMatch19) then
print("Downloaded size mismatch.")
return
end
local digest = chilkat.Crypt2.new()
digest.hash_algorithm = "sha256"
digest.encoding_mode = "base64"
local actualChecksum = digest:hash_file_enc(partialPath)
stringCompare:set_string(actualChecksum)
local stringMatch20 = stringCompare:contents_equal(expectedChecksum, true)
if (not digest.last_method_success) or (not stringMatch20) then
print("Downloaded checksum mismatch.")
return
end
success = files:file_rename(partialPath, finalPath)
if not success then
print("Verified download remains at the temporary path.")
return
end
print("Full-object SHA-256 download verified.")