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.
Chilkat Java Downloads
import com.chilkatsoft.chilkat2.BinData;
import com.chilkatsoft.chilkat2.ChilkatException;
import com.chilkatsoft.chilkat2.Crypt2;
import com.chilkatsoft.chilkat2.DateTime;
import com.chilkatsoft.chilkat2.DirTree;
import com.chilkatsoft.chilkat2.FileAccess;
import com.chilkatsoft.chilkat2.Http;
import com.chilkatsoft.chilkat2.HttpResponse;
import com.chilkatsoft.chilkat2.JsonObject;
import com.chilkatsoft.chilkat2.Mime;
import com.chilkatsoft.chilkat2.StringBuilder;
import com.chilkatsoft.chilkat2.Xml;
public class ChilkatExample {
public static void main(String[] args) {
boolean success = false;
StringBuilder stringCompare = new StringBuilder();
// 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.
JsonObject credentials = new JsonObject();
credentials.setStrict(true);
try {
credentials.loadFile("qa_data/aws/s3.json");
} catch (ChilkatException e) {
System.out.println("Could not load private S3 credentials.");
return;
}
stringCompare.setString(credentials.stringOf("access_key"));
boolean stringMatch1 = stringCompare.contentsEqual("", true);
if ((credentials.jsonTypeOf("access_key") != 1) || (stringMatch1)) {
System.out.println("Missing or invalid access_key.");
return;
}
stringCompare.setString(credentials.stringOf("secret_key"));
boolean stringMatch2 = stringCompare.contentsEqual("", true);
if ((credentials.jsonTypeOf("secret_key") != 1) || (stringMatch2)) {
System.out.println("Missing or invalid secret_key.");
return;
}
Http http = new Http();
http.setAwsAccessKey(credentials.stringOf("access_key"));
http.setAwsSecretKey(credentials.stringOf("secret_key"));
if (credentials.hasMember("session_token")) {
stringCompare.setString(credentials.stringOf("session_token"));
boolean stringMatch3 = stringCompare.contentsEqual("", true);
if ((credentials.jsonTypeOf("session_token") != 1) || (stringMatch3)) {
System.out.println("session_token must be a nonempty string when supplied.");
return;
}
http.setAwsSessionToken(credentials.stringOf("session_token"));
}
// Current Chilkat uses SigV4 by default. Do not select deprecated SigV2.
// Set the actual bucket region, not the caller's location.
String region = "us-west-2";
http.setAwsRegion(region);
StringBuilder endpoint = new StringBuilder();
endpoint.append("s3.");
endpoint.append(region);
endpoint.append(".amazonaws.com");
http.setAwsEndpoint(endpoint.getAsString());
http.setRequireSslCertVerify(true);
http.setFollowRedirects(false);
// A region redirect is not success. Correct the endpoint and signing region.
String bucketName = "your-bucket-name";
String objectKey = "examples/archive.bin";
HttpResponse response = new HttpResponse();
Crypt2 signer = new Crypt2();
signer.setCharset("utf-8");
signer.setHashAlgorithm("sha256");
signer.setEncodingMode("hexlower");
signer.setMacAlgorithm("hmac");
DateTime now = new DateTime();
StringBuilder timestamp = new StringBuilder();
StringBuilder canonical = new StringBuilder();
StringBuilder canonicalHeaders = new StringBuilder();
StringBuilder signedHeaders = new StringBuilder();
StringBuilder scope = new StringBuilder();
StringBuilder stringToSign = new StringBuilder();
StringBuilder signingKey = new StringBuilder();
StringBuilder authorization = new StringBuilder();
StringBuilder url = new StringBuilder();
StringBuilder query = new StringBuilder();
StringBuilder number = new StringBuilder();
StringBuilder host = new StringBuilder();
StringBuilder uri = new StringBuilder();
Xml xml = new Xml();
String payloadHash = "";
String canonicalHash = "";
String derivedKey = "";
String signature = "";
host.append(bucketName);
host.append(".");
host.append(endpoint.getAsString());
// Encode the original key exactly once, preserving S3 path separators.
uri.setString(http.urlEncode(objectKey));
int replaceCount = uri.replaceNoCase("%2f", "/");
if ((uri.startsWith("/", true)) || ((uri.contains("/../", true)) || (uri.contains("/./", true)))) {
System.out.println("Use a key without a leading slash or dot path segments for these examples.");
return;
}
uri.prepend("/");
String versionId = "";
FileAccess files = new FileAccess();
String cacheDir = "qa_output/s3-download-cache";
String manifestPath = "qa_output/s3-download-cache/state.json";
String finalPath = "qa_output/s3-resumed.bin";
String requestedVersionId = versionId;
JsonObject state = new JsonObject();
state.setStrict(true);
JsonObject identity = new JsonObject();
boolean hasCheckpoint = files.fileExists(manifestPath);
if (hasCheckpoint) {
try {
state.loadFile(manifestPath);
} catch (ChilkatException e) {
System.out.println("Invalid download checkpoint. Preserve the cache.");
return;
}
stringCompare.setString(state.stringOf("schema"));
boolean stringMatch4 = stringCompare.contentsEqual("1", true);
if (!stringMatch4) {
System.out.println("Checkpoint settings differ. Use the original settings or a new empty cache.");
return;
}
stringCompare.setString(state.stringOf("bucket"));
boolean stringMatch5 = stringCompare.contentsEqual(bucketName, true);
if (!stringMatch5) {
System.out.println("Checkpoint settings differ. Use the original settings or a new empty cache.");
return;
}
stringCompare.setString(state.stringOf("key"));
boolean stringMatch6 = stringCompare.contentsEqual(objectKey, true);
if (!stringMatch6) {
System.out.println("Checkpoint settings differ. Use the original settings or a new empty cache.");
return;
}
stringCompare.setString(state.stringOf("region"));
boolean stringMatch7 = stringCompare.contentsEqual(region, true);
if (!stringMatch7) {
System.out.println("Checkpoint settings differ. Use the original settings or a new empty cache.");
return;
}
stringCompare.setString(state.stringOf("requestedVersion"));
boolean stringMatch8 = stringCompare.contentsEqual(requestedVersionId, true);
if (!stringMatch8) {
System.out.println("Checkpoint settings differ. Use the original settings or a new empty cache.");
return;
}
stringCompare.setString(state.stringOf("finalPath"));
boolean stringMatch9 = stringCompare.contentsEqual(finalPath, true);
if (!stringMatch9) {
System.out.println("Checkpoint settings differ. Use the original settings or a new empty cache.");
return;
}
stringCompare.setString(state.stringOf("chunkSize"));
boolean stringMatch10 = stringCompare.contentsEqual("8388608", true);
if (!stringMatch10) {
System.out.println("Checkpoint settings differ. Use the original settings or a new empty cache.");
return;
}
versionId = state.stringOf("versionId");
if (state.jsonTypeOf("versionId") != 1) {
System.out.println("Checkpoint version ID is invalid.");
return;
}
}
query.clear();
stringCompare.setString(versionId);
boolean stringMatch11 = stringCompare.contentsEqual("", true);
if (!stringMatch11) {
if (query.getLength() > 0) {
query.append("&");
}
query.append("versionId=");
query.append(http.urlEncode(versionId));
}
http.clearHeaders();
try {
now.setFromCurrentSystemTime();
} catch (ChilkatException e) {
System.out.println("Could not read system time.");
return;
}
timestamp.setString(now.getAsTimestamp(false));
replaceCount = timestamp.replace("-", "");
replaceCount = timestamp.replace(":", "");
String amzDate = timestamp.getAsString();
String dateStamp = timestamp.getRange(0, 8, false);
try {
payloadHash = signer.hashStringENC("");
} catch (ChilkatException e) {
System.out.println("Could not hash payload.");
return;
}
canonicalHeaders.clear();
signedHeaders.clear();
if (signedHeaders.getLength() > 0) {
signedHeaders.append(";");
}
signedHeaders.append("host");
canonicalHeaders.append("host:");
canonicalHeaders.append(host.getAsString());
canonicalHeaders.append("\n");
http.setRequestHeader("host", host.getAsString());
if (signedHeaders.getLength() > 0) {
signedHeaders.append(";");
}
signedHeaders.append("x-amz-checksum-mode");
canonicalHeaders.append("x-amz-checksum-mode:");
canonicalHeaders.append("ENABLED");
canonicalHeaders.append("\n");
http.setRequestHeader("x-amz-checksum-mode", "ENABLED");
if (signedHeaders.getLength() > 0) {
signedHeaders.append(";");
}
signedHeaders.append("x-amz-content-sha256");
canonicalHeaders.append("x-amz-content-sha256:");
canonicalHeaders.append(payloadHash);
canonicalHeaders.append("\n");
http.setRequestHeader("x-amz-content-sha256", payloadHash);
if (signedHeaders.getLength() > 0) {
signedHeaders.append(";");
}
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")) {
if (signedHeaders.getLength() > 0) {
signedHeaders.append(";");
}
signedHeaders.append("x-amz-security-token");
canonicalHeaders.append("x-amz-security-token:");
canonicalHeaders.append(credentials.stringOf("session_token"));
canonicalHeaders.append("\n");
http.setRequestHeader("x-amz-security-token", credentials.stringOf("session_token"));
}
canonical.clear();
canonical.append("HEAD\n");
canonical.append(uri.getAsString());
canonical.append("\n");
canonical.append(query.getAsString());
canonical.append("\n");
canonical.append(canonicalHeaders.getAsString());
canonical.append("\n");
canonical.append(signedHeaders.getAsString());
canonical.append("\n");
canonical.append(payloadHash);
try {
canonicalHash = signer.hashStringENC(canonical.getAsString());
} catch (ChilkatException e) {
System.out.println("Could not hash canonical request.");
return;
}
scope.clear();
scope.append(dateStamp);
scope.append("/");
scope.append(region);
scope.append("/s3/aws4_request");
stringToSign.clear();
stringToSign.append("AWS4-HMAC-SHA256\n");
stringToSign.append(amzDate);
stringToSign.append("\n");
stringToSign.append(scope.getAsString());
stringToSign.append("\n");
stringToSign.append(canonicalHash);
signingKey.setString("AWS4");
signingKey.append(credentials.stringOf("secret_key"));
try {
signer.setMacKeyString(signingKey.getAsString());
} catch (ChilkatException e) {
System.out.println("Could not set signing key.");
return;
}
try {
derivedKey = signer.macStringENC(dateStamp);
} catch (ChilkatException e) {
System.out.println("Could not derive signing key.");
return;
}
try {
signer.setMacKeyEncoded(derivedKey, "hex");
} catch (ChilkatException e) {
System.out.println("Could not set signing key.");
return;
}
try {
derivedKey = signer.macStringENC(region);
} catch (ChilkatException e) {
System.out.println("Could not derive signing key.");
return;
}
try {
signer.setMacKeyEncoded(derivedKey, "hex");
} catch (ChilkatException e) {
System.out.println("Could not set signing key.");
return;
}
try {
derivedKey = signer.macStringENC("s3");
} catch (ChilkatException e) {
System.out.println("Could not derive signing key.");
return;
}
try {
signer.setMacKeyEncoded(derivedKey, "hex");
} catch (ChilkatException e) {
System.out.println("Could not set signing key.");
return;
}
try {
derivedKey = signer.macStringENC("aws4_request");
} catch (ChilkatException e) {
System.out.println("Could not derive signing key.");
return;
}
try {
signer.setMacKeyEncoded(derivedKey, "hex");
} catch (ChilkatException e) {
System.out.println("Could not set signing key.");
return;
}
try {
signature = signer.macStringENC(stringToSign.getAsString());
} catch (ChilkatException e) {
System.out.println("Could not sign request.");
return;
}
authorization.clear();
authorization.append("AWS4-HMAC-SHA256 Credential=");
authorization.append(credentials.stringOf("access_key"));
authorization.append("/");
authorization.append(scope.getAsString());
authorization.append(", SignedHeaders=");
authorization.append(signedHeaders.getAsString());
authorization.append(", Signature=");
authorization.append(signature);
http.setRequestHeader("Authorization", authorization.getAsString());
url.setString("https://");
url.append(host.getAsString());
url.append(uri.getAsString());
if (query.getLength() > 0) {
url.append("?");
url.append(query.getAsString());
}
try {
http.httpNoBody("HEAD", url.getAsString(), response);
success = true;
} catch (ChilkatException e) {
success = false;
}
if ((!success) || (response.getStatusCode() != 200)) {
System.out.println("Request failed or returned unexpected HTTP status: " + response.getStatusCode());
// Preserve progress. Inspect full diagnostics privately; do not log secrets.
return;
}
String etag = response.getHeaderField("ETag");
stringCompare.setString(etag);
boolean stringMatch12 = stringCompare.contentsEqual("", true);
if ((!response.getLastMethodSuccess()) || (stringMatch12)) {
System.out.println("Missing required response header ETag.");
return;
}
String expectedSize = response.getHeaderField("Content-Length");
stringCompare.setString(expectedSize);
boolean stringMatch13 = stringCompare.contentsEqual("", true);
if ((!response.getLastMethodSuccess()) || (stringMatch13)) {
System.out.println("Missing required response header Content-Length.");
return;
}
String returnedVersion = response.getHeaderField("x-amz-version-id");
if (returnedVersion == null) {
returnedVersion = "";
}
stringCompare.setString(versionId);
boolean stringMatch14 = stringCompare.contentsEqual("", true);
if (stringMatch14) {
versionId = returnedVersion;
} else {
stringCompare.setString(returnedVersion);
boolean stringMatch15 = stringCompare.contentsEqual(versionId, true);
if (!stringMatch15) {
System.out.println("Unexpected object version.");
return;
}
}
String expectedChecksum = response.getHeaderField("x-amz-checksum-sha256");
stringCompare.setString(expectedChecksum);
boolean stringMatch16 = stringCompare.contentsEqual("", true);
if ((!response.getLastMethodSuccess()) || (stringMatch16)) {
System.out.println("Missing required response header x-amz-checksum-sha256.");
return;
}
String checksumType = response.getHeaderField("x-amz-checksum-type");
stringCompare.setString(checksumType);
boolean stringMatch17 = stringCompare.contentsEqual("", true);
if ((!response.getLastMethodSuccess()) || (stringMatch17)) {
System.out.println("Missing required response header x-amz-checksum-type.");
return;
}
stringCompare.setString(checksumType);
boolean stringMatch18 = stringCompare.contentsEqual("FULL_OBJECT", true);
if (!stringMatch18) {
System.out.println("This example requires a FULL_OBJECT SHA-256 checksum; COMPOSITE needs separate verification.");
return;
}
// Portable decimal long division; no 32-bit byte-offset overflow.
int chunkSize = 8388608;
int chunkCount = 0;
int remainder = 0;
int position = 0;
StringBuilder sizeText = new StringBuilder();
StringBuilder decimalDigits = new StringBuilder();
StringBuilder digit = new StringBuilder();
sizeText.append(expectedSize);
decimalDigits.append("0123456789");
if ((sizeText.getLength() == 0) || (sizeText.getLength() > 14)) {
System.out.println("Invalid object size.");
return;
}
while (position < sizeText.getLength()) {
digit.setString(sizeText.getRange(position, 1, false));
if (!decimalDigits.contains(digit.getAsString(), true)) {
System.out.println("Invalid decimal object size.");
return;
}
remainder = remainder * 10 + digit.getIntValue();
chunkCount = chunkCount * 10;
while (remainder >= chunkSize) {
chunkCount = chunkCount + 1;
remainder = remainder - chunkSize;
}
position = position + 1;
}
if (remainder != 0) {
chunkCount = chunkCount + 1;
}
if ((chunkCount < 1) || (chunkCount > 10000)) {
System.out.println("Use a nonempty object of at most 10,000 fixed 8 MiB chunks; empty objects use the single-download example.");
return;
}
try {
identity.updateString("schema", "1");
} catch (ChilkatException e) {
System.out.println("Could not save schema.");
return;
}
try {
identity.updateString("bucket", bucketName);
} catch (ChilkatException e) {
System.out.println("Could not save bucket.");
return;
}
try {
identity.updateString("key", objectKey);
} catch (ChilkatException e) {
System.out.println("Could not save key.");
return;
}
try {
identity.updateString("region", region);
} catch (ChilkatException e) {
System.out.println("Could not save region.");
return;
}
try {
identity.updateString("requestedVersion", requestedVersionId);
} catch (ChilkatException e) {
System.out.println("Could not save requestedVersion.");
return;
}
try {
identity.updateString("versionId", versionId);
} catch (ChilkatException e) {
System.out.println("Could not save versionId.");
return;
}
try {
identity.updateString("etag", etag);
} catch (ChilkatException e) {
System.out.println("Could not save etag.");
return;
}
try {
identity.updateString("size", expectedSize);
} catch (ChilkatException e) {
System.out.println("Could not save size.");
return;
}
try {
identity.updateString("checksum", expectedChecksum);
} catch (ChilkatException e) {
System.out.println("Could not save checksum.");
return;
}
try {
identity.updateString("finalPath", finalPath);
} catch (ChilkatException e) {
System.out.println("Could not save finalPath.");
return;
}
try {
identity.updateString("chunkSize", "8388608");
} catch (ChilkatException e) {
System.out.println("Could not save chunkSize.");
return;
}
if (hasCheckpoint) {
stringCompare.setString(state.stringOf("versionId"));
boolean stringMatch19 = stringCompare.contentsEqual(identity.stringOf("versionId"), true);
if (!stringMatch19) {
System.out.println("Object identity changed. Do not mix old cached bytes with this object.");
return;
}
stringCompare.setString(state.stringOf("etag"));
boolean stringMatch20 = stringCompare.contentsEqual(identity.stringOf("etag"), true);
if (!stringMatch20) {
System.out.println("Object identity changed. Do not mix old cached bytes with this object.");
return;
}
stringCompare.setString(state.stringOf("size"));
boolean stringMatch21 = stringCompare.contentsEqual(identity.stringOf("size"), true);
if (!stringMatch21) {
System.out.println("Object identity changed. Do not mix old cached bytes with this object.");
return;
}
stringCompare.setString(state.stringOf("checksum"));
boolean stringMatch22 = stringCompare.contentsEqual(identity.stringOf("checksum"), true);
if (!stringMatch22) {
System.out.println("Object identity changed. Do not mix old cached bytes with this object.");
return;
}
} else {
try {
files.dirEnsureExists(cacheDir);
} catch (ChilkatException e) {
System.out.println("Could not create private cache.");
return;
}
DirTree entries = new DirTree();
entries.setBaseDir(cacheDir);
entries.setRecurse(false);
try {
entries.beginIterate();
success = true;
} catch (ChilkatException e) {
success = false;
}
if ((success) || (!entries.getDoneIterating())) {
System.out.println("First download requires an empty, readable cache directory.");
return;
}
try {
identity.writeFile("qa_output/s3-download-cache/state.json.tmp");
} catch (ChilkatException e) {
System.out.println("Could not save download identity.");
return;
}
try {
files.fileRename("qa_output/s3-download-cache/state.json.tmp", manifestPath);
} catch (ChilkatException e) {
System.out.println("Checkpoint remains at its temporary path.");
return;
}
}
Crypt2 digest = new Crypt2();
digest.setHashAlgorithm("sha256");
digest.setEncodingMode("base64");
if (files.fileExists(finalPath)) {
String existingSize = files.fileSizeStr(finalPath);
String existingChecksum = digest.hashFileENC(finalPath);
stringCompare.setString(existingSize);
boolean stringMatch23 = stringCompare.contentsEqual(expectedSize, true);
stringCompare.setString(existingChecksum);
boolean stringMatch24 = stringCompare.contentsEqual(expectedChecksum, true);
if ((!digest.getLastMethodSuccess()) || ((!stringMatch23) || (!stringMatch24))) {
System.out.println("Existing final file does not match; preserve it.");
return;
}
System.out.println("Object already downloaded and checksum verified.");
return;
}
digest.setEncodingMode("hexlower");
StringBuilder path = new StringBuilder();
StringBuilder range = new StringBuilder();
StringBuilder digits = new StringBuilder();
StringBuilder rangeHeader = new StringBuilder();
StringBuilder contentRange = new StringBuilder();
StringBuilder byteCount = new StringBuilder();
JsonObject receipt = new JsonObject();
receipt.setStrict(true);
Mime received = new Mime();
int chunkIndex = 0;
int byteHigh = 0;
int byteLow = 0;
int endHigh = 0;
int endLow = 0;
String actualRange = "";
String actualLength = "";
String actualEtag = "";
String actualVersion = "";
String actualSize = "";
String actualHash = "";
while (chunkIndex < chunkCount) {
int chunkBytes = chunkSize;
if ((chunkIndex == chunkCount - 1) && (remainder != 0)) {
chunkBytes = remainder;
}
range.clear();
digits.clear();
digits.appendInt(byteLow);
if (byteHigh > 0) {
while (digits.getLength() < 9) {
digits.prepend("0");
}
range.appendInt(byteHigh);
}
range.append(digits.getAsString());
range.append("-");
endHigh = byteHigh;
endLow = byteLow + chunkBytes - 1;
if (endLow >= 1000000000) {
endLow = endLow - 1000000000;
endHigh = endHigh + 1;
}
digits.clear();
digits.appendInt(endLow);
if (endHigh > 0) {
while (digits.getLength() < 9) {
digits.prepend("0");
}
range.appendInt(endHigh);
}
range.append(digits.getAsString());
String 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);
String chunkPath = path.getAsString();
path.append(".json");
String receiptPath = path.getAsString();
path.setString(chunkPath);
path.append(".part");
String partialPath = path.getAsString();
if (files.fileExists(chunkPath)) {
try {
receipt.loadFile(receiptPath);
} catch (ChilkatException e) {
System.out.println("Cached chunk has no valid receipt. Preserve the cache.");
return;
}
actualHash = digest.hashFileENC(chunkPath);
stringCompare.setString(actualHash);
boolean stringMatch25 = stringCompare.contentsEqual(receipt.stringOf("hash"), true);
stringCompare.setString(receipt.stringOf("range"));
boolean stringMatch26 = stringCompare.contentsEqual(rangeKey, true);
stringCompare.setString(files.fileSizeStr(chunkPath));
boolean stringMatch27 = stringCompare.contentsEqual(byteCount.getAsString(), true);
if ((!digest.getLastMethodSuccess()) || ((!stringMatch25) || ((!stringMatch26) || (!stringMatch27)))) {
System.out.println("Cached chunk failed verification. Remove only this chunk and receipt before retrying.");
return;
}
System.out.println("Reusing verified chunk: " + chunkIndex);
} else {
query.clear();
stringCompare.setString(versionId);
boolean stringMatch28 = stringCompare.contentsEqual("", true);
if (!stringMatch28) {
if (query.getLength() > 0) {
query.append("&");
}
query.append("versionId=");
query.append(http.urlEncode(versionId));
}
http.clearHeaders();
try {
now.setFromCurrentSystemTime();
} catch (ChilkatException e) {
System.out.println("Could not read system time.");
return;
}
timestamp.setString(now.getAsTimestamp(false));
replaceCount = timestamp.replace("-", "");
replaceCount = timestamp.replace(":", "");
amzDate = timestamp.getAsString();
dateStamp = timestamp.getRange(0, 8, false);
try {
payloadHash = signer.hashStringENC("");
} catch (ChilkatException e) {
System.out.println("Could not hash payload.");
return;
}
canonicalHeaders.clear();
signedHeaders.clear();
if (signedHeaders.getLength() > 0) {
signedHeaders.append(";");
}
signedHeaders.append("host");
canonicalHeaders.append("host:");
canonicalHeaders.append(host.getAsString());
canonicalHeaders.append("\n");
http.setRequestHeader("host", host.getAsString());
if (signedHeaders.getLength() > 0) {
signedHeaders.append(";");
}
signedHeaders.append("if-match");
canonicalHeaders.append("if-match:");
canonicalHeaders.append(etag);
canonicalHeaders.append("\n");
http.setRequestHeader("if-match", etag);
if (signedHeaders.getLength() > 0) {
signedHeaders.append(";");
}
signedHeaders.append("range");
canonicalHeaders.append("range:");
canonicalHeaders.append(rangeHeader.getAsString());
canonicalHeaders.append("\n");
http.setRequestHeader("range", rangeHeader.getAsString());
if (signedHeaders.getLength() > 0) {
signedHeaders.append(";");
}
signedHeaders.append("x-amz-content-sha256");
canonicalHeaders.append("x-amz-content-sha256:");
canonicalHeaders.append(payloadHash);
canonicalHeaders.append("\n");
http.setRequestHeader("x-amz-content-sha256", payloadHash);
if (signedHeaders.getLength() > 0) {
signedHeaders.append(";");
}
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")) {
if (signedHeaders.getLength() > 0) {
signedHeaders.append(";");
}
signedHeaders.append("x-amz-security-token");
canonicalHeaders.append("x-amz-security-token:");
canonicalHeaders.append(credentials.stringOf("session_token"));
canonicalHeaders.append("\n");
http.setRequestHeader("x-amz-security-token", credentials.stringOf("session_token"));
}
canonical.clear();
canonical.append("GET\n");
canonical.append(uri.getAsString());
canonical.append("\n");
canonical.append(query.getAsString());
canonical.append("\n");
canonical.append(canonicalHeaders.getAsString());
canonical.append("\n");
canonical.append(signedHeaders.getAsString());
canonical.append("\n");
canonical.append(payloadHash);
try {
canonicalHash = signer.hashStringENC(canonical.getAsString());
} catch (ChilkatException e) {
System.out.println("Could not hash canonical request.");
return;
}
scope.clear();
scope.append(dateStamp);
scope.append("/");
scope.append(region);
scope.append("/s3/aws4_request");
stringToSign.clear();
stringToSign.append("AWS4-HMAC-SHA256\n");
stringToSign.append(amzDate);
stringToSign.append("\n");
stringToSign.append(scope.getAsString());
stringToSign.append("\n");
stringToSign.append(canonicalHash);
signingKey.setString("AWS4");
signingKey.append(credentials.stringOf("secret_key"));
try {
signer.setMacKeyString(signingKey.getAsString());
} catch (ChilkatException e) {
System.out.println("Could not set signing key.");
return;
}
try {
derivedKey = signer.macStringENC(dateStamp);
} catch (ChilkatException e) {
System.out.println("Could not derive signing key.");
return;
}
try {
signer.setMacKeyEncoded(derivedKey, "hex");
} catch (ChilkatException e) {
System.out.println("Could not set signing key.");
return;
}
try {
derivedKey = signer.macStringENC(region);
} catch (ChilkatException e) {
System.out.println("Could not derive signing key.");
return;
}
try {
signer.setMacKeyEncoded(derivedKey, "hex");
} catch (ChilkatException e) {
System.out.println("Could not set signing key.");
return;
}
try {
derivedKey = signer.macStringENC("s3");
} catch (ChilkatException e) {
System.out.println("Could not derive signing key.");
return;
}
try {
signer.setMacKeyEncoded(derivedKey, "hex");
} catch (ChilkatException e) {
System.out.println("Could not set signing key.");
return;
}
try {
derivedKey = signer.macStringENC("aws4_request");
} catch (ChilkatException e) {
System.out.println("Could not derive signing key.");
return;
}
try {
signer.setMacKeyEncoded(derivedKey, "hex");
} catch (ChilkatException e) {
System.out.println("Could not set signing key.");
return;
}
try {
signature = signer.macStringENC(stringToSign.getAsString());
} catch (ChilkatException e) {
System.out.println("Could not sign request.");
return;
}
authorization.clear();
authorization.append("AWS4-HMAC-SHA256 Credential=");
authorization.append(credentials.stringOf("access_key"));
authorization.append("/");
authorization.append(scope.getAsString());
authorization.append(", SignedHeaders=");
authorization.append(signedHeaders.getAsString());
authorization.append(", Signature=");
authorization.append(signature);
http.setRequestHeader("Authorization", authorization.getAsString());
url.setString("https://");
url.append(host.getAsString());
url.append(uri.getAsString());
if (query.getLength() > 0) {
url.append("?");
url.append(query.getAsString());
}
try {
http.download(url.getAsString(), partialPath);
success = true;
} catch (ChilkatException e) {
success = false;
}
if ((http.getLastStatus() == 412) || (http.getLastStatus() == 416)) {
System.out.println("Object changed or range is invalid. Preserve the cache; do not append.");
return;
}
if ((!success) || (http.getLastStatus() != 206)) {
System.out.println("Request failed or returned unexpected HTTP status: " + http.getLastStatus());
// Preserve progress. Inspect full diagnostics privately; do not log secrets.
return;
}
try {
received.loadMime(http.getLastResponseHeader());
} catch (ChilkatException e) {
System.out.println("Could not parse range response.");
return;
}
actualRange = received.getHeaderField("Content-Range");
stringCompare.setString(actualRange);
boolean stringMatch29 = stringCompare.contentsEqual("", true);
if ((!received.getLastMethodSuccess()) || (stringMatch29)) {
System.out.println("Missing download header Content-Range.");
return;
}
actualLength = received.getHeaderField("Content-Length");
stringCompare.setString(actualLength);
boolean stringMatch30 = stringCompare.contentsEqual("", true);
if ((!received.getLastMethodSuccess()) || (stringMatch30)) {
System.out.println("Missing download header Content-Length.");
return;
}
actualEtag = received.getHeaderField("ETag");
stringCompare.setString(actualEtag);
boolean stringMatch31 = stringCompare.contentsEqual("", true);
if ((!received.getLastMethodSuccess()) || (stringMatch31)) {
System.out.println("Missing download header ETag.");
return;
}
stringCompare.setString(actualRange);
boolean stringMatch32 = stringCompare.contentsEqual(contentRange.getAsString(), true);
stringCompare.setString(actualLength);
boolean stringMatch33 = stringCompare.contentsEqual(byteCount.getAsString(), true);
stringCompare.setString(actualEtag);
boolean stringMatch34 = stringCompare.contentsEqual(etag, true);
if ((!stringMatch32) || ((!stringMatch33) || (!stringMatch34))) {
System.out.println("Unexpected range response; no chunk committed.");
return;
}
stringCompare.setString(versionId);
boolean stringMatch35 = stringCompare.contentsEqual("", true);
if (!stringMatch35) {
actualVersion = received.getHeaderField("x-amz-version-id");
stringCompare.setString(actualVersion);
boolean stringMatch36 = stringCompare.contentsEqual("", true);
if ((!received.getLastMethodSuccess()) || (stringMatch36)) {
System.out.println("Missing download header x-amz-version-id.");
return;
}
stringCompare.setString(actualVersion);
boolean stringMatch37 = stringCompare.contentsEqual(versionId, true);
if (!stringMatch37) {
System.out.println("Unexpected returned version.");
return;
}
}
actualSize = files.fileSizeStr(partialPath);
stringCompare.setString(actualSize);
boolean stringMatch38 = stringCompare.contentsEqual(byteCount.getAsString(), true);
if ((!files.getLastMethodSuccess()) || (!stringMatch38)) {
System.out.println("Range byte count mismatch.");
return;
}
try {
actualHash = digest.hashFileENC(partialPath);
} catch (ChilkatException e) {
System.out.println("Could not hash range bytes.");
return;
}
try {
receipt.updateString("range", rangeKey);
} catch (ChilkatException e) {
System.out.println("Could not save range.");
return;
}
try {
receipt.updateString("hash", actualHash);
} catch (ChilkatException e) {
System.out.println("Could not save hash.");
return;
}
try {
receipt.writeFile(receiptPath);
} catch (ChilkatException e) {
System.out.println("Could not save chunk receipt.");
return;
}
try {
files.fileRename(partialPath, chunkPath);
} catch (ChilkatException e) {
System.out.println("Could not commit downloaded chunk.");
return;
}
System.out.println("Downloaded chunk: " + chunkIndex);
}
byteHigh = endHigh;
byteLow = endLow + 1;
if (byteLow == 1000000000) {
byteLow = 0;
byteHigh = byteHigh + 1;
}
chunkIndex = chunkIndex + 1;
}
// Cache hashes detect local damage, but only the final stored S3 checksum
// establishes whole-object integrity. A range is not verified by a full hash.
String assembledPath = "qa_output/s3-download-cache/assembled.part";
FileAccess assembled = new FileAccess();
try {
assembled.openForWrite(assembledPath);
} catch (ChilkatException e) {
System.out.println("Could not open assembly file.");
return;
}
BinData data = new BinData();
chunkIndex = 0;
while (chunkIndex < chunkCount) {
path.setString(cacheDir);
path.append("/chunk-");
path.appendInt(chunkIndex);
data.clear();
try {
data.loadFile(path.getAsString());
assembled.fileWriteBd(data, 0, 0);
} catch (ChilkatException e) {
assembled.fileClose();
System.out.println("Assembly failed; verified progress is retained.");
return;
}
chunkIndex = chunkIndex + 1;
}
assembled.fileClose();
actualSize = files.fileSizeStr(assembledPath);
digest.setEncodingMode("base64");
actualHash = digest.hashFileENC(assembledPath);
stringCompare.setString(actualSize);
boolean stringMatch39 = stringCompare.contentsEqual(expectedSize, true);
stringCompare.setString(actualHash);
boolean stringMatch40 = stringCompare.contentsEqual(expectedChecksum, true);
if ((!digest.getLastMethodSuccess()) || ((!stringMatch39) || (!stringMatch40))) {
System.out.println("Assembled object checksum/size mismatch; final file not created.");
return;
}
try {
files.fileRename(assembledPath, finalPath);
} catch (ChilkatException e) {
System.out.println("Verified assembly remains in cache; rename failed.");
return;
}
System.out.println("Resumable download completed and checksum verified. Cache retained for manual cleanup.");
}
}