Sample code for 30+ languages & platforms
C# Requires Chilkat v11.6.0+

S3 Http: Multipart Upload with Checksums and Checkpoint

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.

Uses a private checkpoint directory for one upload and an immutable source file. Run one process per checkpoint; never run upload/resume concurrently with abort. The fixed 8 MiB part size limits this demonstration to nonempty files of at most 10,000 parts (78.125 GiB). It does not impose that limit on S3 itself; choose larger valid part sizes for larger objects.

Uses SHA-256 COMPOSITE multipart checksums, validates part checksums, and verifies the returned composite checksum. ETags are retained for completion but never treated as MD5. Completion can return an error inside HTTP 200; the XML result is checked. Source identity is SHA-256, not just filename/length. The checkpoint contains no AWS credentials.

Requires s3:PutObject, s3:ListMultipartUploadParts for resume, and s3:GetObject for uncertain-completion recovery, plus relevant KMS permissions if bucket defaults use KMS. Incomplete parts incur storage charges until completed or aborted. Configure a suitable incomplete-multipart lifecycle rule as an operational safeguard. Timeout during initiation may leave an upload without a checkpoint; list uploads and investigate before initiating another.

Starts, transfers and completes one upload. Saves state before parts and a pending completion record before completion. Run the resume companion after interruptions; do not rerun start against an existing cache. Metadata binds an uncertain completion to a random upload identity.

AWS reference

Chilkat C# Downloads

C#
bool success = false;

Chilkat.StringBuilder stringCompare = new Chilkat.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.
Chilkat.JsonObject credentials = new Chilkat.JsonObject();
credentials.Strict = true;
success = credentials.LoadFile("qa_data/aws/s3.json");
if (success != true) {
    Debug.WriteLine("Could not load private S3 credentials.");
    return;
}

stringCompare.SetString(credentials.StringOf("access_key"));
bool stringMatch1 = stringCompare.ContentsEqual("",true);
if ((credentials.JsonTypeOf("access_key") != 1) || (stringMatch1 == true)) {
    Debug.WriteLine("Missing or invalid access_key.");
    return;
}

stringCompare.SetString(credentials.StringOf("secret_key"));
bool stringMatch2 = stringCompare.ContentsEqual("",true);
if ((credentials.JsonTypeOf("secret_key") != 1) || (stringMatch2 == true)) {
    Debug.WriteLine("Missing or invalid secret_key.");
    return;
}

Chilkat.Http http = new Chilkat.Http();
http.AwsAccessKey = credentials.StringOf("access_key");
http.AwsSecretKey = credentials.StringOf("secret_key");
if (credentials.HasMember("session_token") == true) {
    stringCompare.SetString(credentials.StringOf("session_token"));
    bool stringMatch3 = stringCompare.ContentsEqual("",true);
    if ((credentials.JsonTypeOf("session_token") != 1) || (stringMatch3 == true)) {
        Debug.WriteLine("session_token must be a nonempty string when supplied.");
        return;
    }

    http.AwsSessionToken = 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.AwsRegion = region;
Chilkat.StringBuilder endpoint = new Chilkat.StringBuilder();
endpoint.Append("s3.");
endpoint.Append(region);
endpoint.Append(".amazonaws.com");
http.AwsEndpoint = endpoint.GetAsString();
http.RequireSslCertVerify = true;
http.FollowRedirects = false;
//  A region redirect is not success. Correct the endpoint and signing region.
string bucketName = "your-bucket-name";
string objectKey = "examples/archive.bin";
Chilkat.HttpResponse response = new Chilkat.HttpResponse();
Chilkat.Crypt2 signer = new Chilkat.Crypt2();
signer.Charset = "utf-8";
signer.HashAlgorithm = "sha256";
signer.EncodingMode = "hexlower";
signer.MacAlgorithm = "hmac";
Chilkat.CkDateTime now = new Chilkat.CkDateTime();
Chilkat.StringBuilder timestamp = new Chilkat.StringBuilder();
Chilkat.StringBuilder canonical = new Chilkat.StringBuilder();
Chilkat.StringBuilder canonicalHeaders = new Chilkat.StringBuilder();
Chilkat.StringBuilder signedHeaders = new Chilkat.StringBuilder();
Chilkat.StringBuilder scope = new Chilkat.StringBuilder();
Chilkat.StringBuilder stringToSign = new Chilkat.StringBuilder();
Chilkat.StringBuilder signingKey = new Chilkat.StringBuilder();
Chilkat.StringBuilder authorization = new Chilkat.StringBuilder();
Chilkat.StringBuilder url = new Chilkat.StringBuilder();
Chilkat.StringBuilder query = new Chilkat.StringBuilder();
Chilkat.StringBuilder number = new Chilkat.StringBuilder();
Chilkat.StringBuilder host = new Chilkat.StringBuilder();
Chilkat.StringBuilder uri = new Chilkat.StringBuilder();
Chilkat.Xml xml = new Chilkat.Xml();
string amzDate;
string dateStamp;
string payloadHash;
string canonicalHash;
string derivedKey;
string signature;
int replaceCount;
host.Append(bucketName);
host.Append(".");
host.Append(endpoint.GetAsString());
//  Encode the original key exactly once, preserving S3 path separators.
uri.SetString(http.UrlEncode(objectKey));
replaceCount = uri.ReplaceNoCase("%2f","/");
if ((uri.StartsWith("/",true) == true) || (uri.Contains("/../",true) == true) || (uri.Contains("/./",true) == true)) {
    Debug.WriteLine("Use a key without a leading slash or dot path segments for these examples.");
    return;
}

uri.Prepend("/");
Chilkat.FileAccess files = new Chilkat.FileAccess();
string filePath = "qa_data/bin/archive.bin";
string fileSize = files.FileSizeStr(filePath);
if (files.LastMethodSuccess != true) {
    Debug.WriteLine("Could not read source file size.");
    return;
}

Chilkat.Crypt2 digest = new Chilkat.Crypt2();
digest.HashAlgorithm = "sha256";
digest.EncodingMode = "hexlower";
string sourceHash = digest.HashFileENC(filePath);
if (digest.LastMethodSuccess != true) {
    Debug.WriteLine("Could not hash source file.");
    return;
}

digest.EncodingMode = "base64";
string sourceChecksum = digest.HashFileENC(filePath);
if (digest.LastMethodSuccess != true) {
    Debug.WriteLine("Could not compute checksum.");
    return;
}

string cacheDir = "qa_output/s3-multipart";
string statePath = "qa_output/s3-multipart/state.json";
string pendingPath = "qa_output/s3-multipart/completion.json";
string receiptPath = "qa_output/s3-multipart/completed.json";
Chilkat.JsonObject state = new Chilkat.JsonObject();
state.Strict = true;
Chilkat.JsonObject pending = new Chilkat.JsonObject();
pending.Strict = true;
string uploadId;
string uploadToken;
string compositeChecksum;
success = files.OpenForRead(filePath);
if (success != true) {
    Debug.WriteLine("Could not open immutable source file.");
    return;
}

int partSize = 8388608;
int numParts = files.GetNumBlocks(partSize);
if ((numParts < 1) || (numParts > 10000)) {
    Debug.WriteLine("Use a nonempty source of at most 10,000 fixed 8 MiB parts.");
    return;
}

Chilkat.Hashtable remoteEtags = new Chilkat.Hashtable();
Chilkat.Hashtable remoteSizes = new Chilkat.Hashtable();
Chilkat.Hashtable remoteChecksums = new Chilkat.Hashtable();
Chilkat.Hashtable partNumbers = new Chilkat.Hashtable();
Chilkat.StringBuilder partNumberText = new Chilkat.StringBuilder();
success = files.DirEnsureExists(cacheDir);
if (success != true) {
    Debug.WriteLine("Could not create private checkpoint directory.");
    return;
}

Chilkat.DirTree entries = new Chilkat.DirTree();
entries.BaseDir = cacheDir;
entries.Recurse = false;
success = entries.BeginIterate();
if ((success == true) || (entries.DoneIterating != true)) {
    Debug.WriteLine("Start requires an empty checkpoint directory; use resume for an existing upload.");
    return;
}

Chilkat.Prng random = new Chilkat.Prng();
uploadToken = random.GenRandom(16,"hex");
if (random.LastMethodSuccess != true) {
    Debug.WriteLine("Could not create upload identity.");
    return;
}

query.Clear();
if (query.Length > 0) {
    query.Append("&");
}

query.Append("uploads=");
query.Append(http.UrlEncode(""));
http.ClearHeaders();
success = now.SetFromCurrentSystemTime();
if (success != true) {
    Debug.WriteLine("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);
payloadHash = signer.HashStringENC("");
if (signer.LastMethodSuccess != true) {
    Debug.WriteLine("Could not hash payload.");
    return;
}

canonicalHeaders.Clear();
signedHeaders.Clear();
if (signedHeaders.Length > 0) {
    signedHeaders.Append(";");
}

signedHeaders.Append("host");
canonicalHeaders.Append("host:");
canonicalHeaders.Append(host.GetAsString());
canonicalHeaders.Append("\n");
http.SetRequestHeader("host",host.GetAsString());
if (signedHeaders.Length > 0) {
    signedHeaders.Append(";");
}

signedHeaders.Append("x-amz-checksum-algorithm");
canonicalHeaders.Append("x-amz-checksum-algorithm:");
canonicalHeaders.Append("SHA256");
canonicalHeaders.Append("\n");
http.SetRequestHeader("x-amz-checksum-algorithm","SHA256");
if (signedHeaders.Length > 0) {
    signedHeaders.Append(";");
}

signedHeaders.Append("x-amz-checksum-type");
canonicalHeaders.Append("x-amz-checksum-type:");
canonicalHeaders.Append("COMPOSITE");
canonicalHeaders.Append("\n");
http.SetRequestHeader("x-amz-checksum-type","COMPOSITE");
if (signedHeaders.Length > 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.Length > 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 (signedHeaders.Length > 0) {
    signedHeaders.Append(";");
}

signedHeaders.Append("x-amz-meta-source-sha256");
canonicalHeaders.Append("x-amz-meta-source-sha256:");
canonicalHeaders.Append(sourceHash);
canonicalHeaders.Append("\n");
http.SetRequestHeader("x-amz-meta-source-sha256",sourceHash);
if (signedHeaders.Length > 0) {
    signedHeaders.Append(";");
}

signedHeaders.Append("x-amz-meta-upload-token");
canonicalHeaders.Append("x-amz-meta-upload-token:");
canonicalHeaders.Append(uploadToken);
canonicalHeaders.Append("\n");
http.SetRequestHeader("x-amz-meta-upload-token",uploadToken);
if (credentials.HasMember("session_token") == true) {
    if (signedHeaders.Length > 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("POST\n");
canonical.Append(uri.GetAsString());
canonical.Append("\n");
canonical.Append(query.GetAsString());
canonical.Append("\n");
canonical.Append(canonicalHeaders.GetAsString());
canonical.Append("\n");
canonical.Append(signedHeaders.GetAsString());
canonical.Append("\n");
canonical.Append(payloadHash);
canonicalHash = signer.HashStringENC(canonical.GetAsString());
if (signer.LastMethodSuccess != true) {
    Debug.WriteLine("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"));
success = signer.SetMacKeyString(signingKey.GetAsString());
if (success != true) {
    Debug.WriteLine("Could not set signing key.");
    return;
}

derivedKey = signer.MacStringENC(dateStamp);
if (signer.LastMethodSuccess != true) {
    Debug.WriteLine("Could not derive signing key.");
    return;
}

success = signer.SetMacKeyEncoded(derivedKey,"hex");
if (success != true) {
    Debug.WriteLine("Could not set signing key.");
    return;
}

derivedKey = signer.MacStringENC(region);
if (signer.LastMethodSuccess != true) {
    Debug.WriteLine("Could not derive signing key.");
    return;
}

success = signer.SetMacKeyEncoded(derivedKey,"hex");
if (success != true) {
    Debug.WriteLine("Could not set signing key.");
    return;
}

derivedKey = signer.MacStringENC("s3");
if (signer.LastMethodSuccess != true) {
    Debug.WriteLine("Could not derive signing key.");
    return;
}

success = signer.SetMacKeyEncoded(derivedKey,"hex");
if (success != true) {
    Debug.WriteLine("Could not set signing key.");
    return;
}

derivedKey = signer.MacStringENC("aws4_request");
if (signer.LastMethodSuccess != true) {
    Debug.WriteLine("Could not derive signing key.");
    return;
}

success = signer.SetMacKeyEncoded(derivedKey,"hex");
if (success != true) {
    Debug.WriteLine("Could not set signing key.");
    return;
}

signature = signer.MacStringENC(stringToSign.GetAsString());
if (signer.LastMethodSuccess != true) {
    Debug.WriteLine("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.Length > 0) {
    url.Append("?");
    url.Append(query.GetAsString());
}

success = http.HttpNoBody("POST",url.GetAsString(),response);
if ((success != true) || (response.StatusCode != 200)) {
    Debug.WriteLine("Request failed or returned unexpected HTTP status: " + Convert.ToString(response.StatusCode));
    //  Preserve progress. Inspect full diagnostics privately; do not log secrets.
    return;
}

success = xml.LoadXml(response.BodyStr);
if (success != true) {
    Debug.WriteLine("Invalid XML response.");
    return;
}

stringCompare.SetString(xml.Tag);
bool stringMatch4 = stringCompare.ContentsEqual("InitiateMultipartUploadResult",true);
if (stringMatch4 != true) {
    Debug.WriteLine("Unexpected XML result, possibly an embedded S3 error. Inspect privately.");
    return;
}

uploadId = xml.GetChildContent("UploadId");
stringCompare.SetString(uploadId);
bool stringMatch5 = stringCompare.ContentsEqual("",true);
if ((xml.LastMethodSuccess != true) || (stringMatch5 == true)) {
    Debug.WriteLine("Missing required UploadId.");
    return;
}

Debug.WriteLine("Created upload ID: " + uploadId);
//  Save the upload ID before sending parts. If saving fails, retain the printed ID.
success = state.UpdateString("schema","1");
if (success != true) {
    Debug.WriteLine("Could not save schema.");
    return;
}

success = state.UpdateString("bucket",bucketName);
if (success != true) {
    Debug.WriteLine("Could not save bucket.");
    return;
}

success = state.UpdateString("key",objectKey);
if (success != true) {
    Debug.WriteLine("Could not save key.");
    return;
}

success = state.UpdateString("region",region);
if (success != true) {
    Debug.WriteLine("Could not save region.");
    return;
}

success = state.UpdateString("filePath",filePath);
if (success != true) {
    Debug.WriteLine("Could not save filePath.");
    return;
}

success = state.UpdateString("fileSize",fileSize);
if (success != true) {
    Debug.WriteLine("Could not save fileSize.");
    return;
}

success = state.UpdateString("sourceHash",sourceHash);
if (success != true) {
    Debug.WriteLine("Could not save sourceHash.");
    return;
}

success = state.UpdateString("partSize","8388608");
if (success != true) {
    Debug.WriteLine("Could not save partSize.");
    return;
}

success = state.UpdateString("uploadId",uploadId);
if (success != true) {
    Debug.WriteLine("Could not save uploadId.");
    return;
}

success = state.UpdateString("uploadToken",uploadToken);
if (success != true) {
    Debug.WriteLine("Could not save uploadToken.");
    return;
}

success = state.WriteFile("qa_output/s3-multipart/state.json.tmp");
if (success != true) {
    Debug.WriteLine("Upload was initiated but checkpoint could not be saved; retain its ID.");
    return;
}

success = files.FileRename("qa_output/s3-multipart/state.json.tmp",statePath);
if (success != true) {
    Debug.WriteLine("Checkpoint rename failed; preserve the temporary checkpoint and upload ID.");
    return;
}

Chilkat.BinData part = new Chilkat.BinData();
Chilkat.BinData concatenatedDigests = new Chilkat.BinData();
Chilkat.Xml completion = new Chilkat.Xml();
completion.Tag = "CompleteMultipartUpload";
completion.AddAttribute("xmlns","http://s3.amazonaws.com/doc/2006-03-01/");
int partIndex = 0;
string partChecksum;
string partEtag;
string partHash;
string confirmed;
string sizeText;
while ((partIndex < numParts)) {
    part.Clear();
    success = files.ReadBlockBd(partIndex,partSize,part);
    if (success != true) {
        Debug.WriteLine("Could not read source part; preserve checkpoint.");
        return;
    }

    if ((part.NumBytes == 0) || ((partIndex < numParts - 1) && (part.NumBytes != partSize))) {
        Debug.WriteLine("Source changed or part read was incomplete.");
        return;
    }

    partChecksum = digest.HashBdENC(part);
    if (digest.LastMethodSuccess != true) {
        Debug.WriteLine("Could not checksum part.");
        return;
    }

    partHash = signer.HashBdENC(part);
    if (signer.LastMethodSuccess != true) {
        Debug.WriteLine("Could not hash part.");
        return;
    }

    success = concatenatedDigests.AppendEncoded(partChecksum,"base64");
    if (success != true) {
        Debug.WriteLine("Could not accumulate part digests.");
        return;
    }

    partNumberText.Clear();
    partNumberText.AppendInt(partIndex + 1);
    number.Clear();
    number.AppendInt(part.NumBytes);
    sizeText = number.GetAsString();
    string partNumberKey = partNumberText.GetAsString();
    bool reuse = false;
    partEtag = "";
    if (remoteChecksums.Contains(partNumberKey) == true) {
        stringCompare.SetString(remoteChecksums.LookupStr(partNumberKey));
        bool stringMatch6 = stringCompare.ContentsEqual(partChecksum,true);
        stringCompare.SetString(remoteSizes.LookupStr(partNumberKey));
        bool stringMatch7 = stringCompare.ContentsEqual(sizeText,true);
        if ((stringMatch6 == true) && (stringMatch7 == true)) {
            partEtag = remoteEtags.LookupStr(partNumberKey);
            stringCompare.SetString(partEtag);
            bool stringMatch8 = stringCompare.ContentsEqual("",true);
            if ((remoteEtags.LastMethodSuccess == true) && (stringMatch8 != true)) {
                reuse = true;
            }

        }

    }

    if (reuse != true) {
        query.Clear();
        if (query.Length > 0) {
            query.Append("&");
        }

        query.Append("partNumber=");
        query.Append(http.UrlEncode(partNumberText.GetAsString()));
        if (query.Length > 0) {
            query.Append("&");
        }

        query.Append("uploadId=");
        query.Append(http.UrlEncode(uploadId));
        http.ClearHeaders();
        success = now.SetFromCurrentSystemTime();
        if (success != true) {
            Debug.WriteLine("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);
        payloadHash = partHash;
        canonicalHeaders.Clear();
        signedHeaders.Clear();
        if (signedHeaders.Length > 0) {
            signedHeaders.Append(";");
        }

        signedHeaders.Append("host");
        canonicalHeaders.Append("host:");
        canonicalHeaders.Append(host.GetAsString());
        canonicalHeaders.Append("\n");
        http.SetRequestHeader("host",host.GetAsString());
        if (signedHeaders.Length > 0) {
            signedHeaders.Append(";");
        }

        signedHeaders.Append("x-amz-checksum-sha256");
        canonicalHeaders.Append("x-amz-checksum-sha256:");
        canonicalHeaders.Append(partChecksum);
        canonicalHeaders.Append("\n");
        http.SetRequestHeader("x-amz-checksum-sha256",partChecksum);
        if (signedHeaders.Length > 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.Length > 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") == true) {
            if (signedHeaders.Length > 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("PUT\n");
        canonical.Append(uri.GetAsString());
        canonical.Append("\n");
        canonical.Append(query.GetAsString());
        canonical.Append("\n");
        canonical.Append(canonicalHeaders.GetAsString());
        canonical.Append("\n");
        canonical.Append(signedHeaders.GetAsString());
        canonical.Append("\n");
        canonical.Append(payloadHash);
        canonicalHash = signer.HashStringENC(canonical.GetAsString());
        if (signer.LastMethodSuccess != true) {
            Debug.WriteLine("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"));
        success = signer.SetMacKeyString(signingKey.GetAsString());
        if (success != true) {
            Debug.WriteLine("Could not set signing key.");
            return;
        }

        derivedKey = signer.MacStringENC(dateStamp);
        if (signer.LastMethodSuccess != true) {
            Debug.WriteLine("Could not derive signing key.");
            return;
        }

        success = signer.SetMacKeyEncoded(derivedKey,"hex");
        if (success != true) {
            Debug.WriteLine("Could not set signing key.");
            return;
        }

        derivedKey = signer.MacStringENC(region);
        if (signer.LastMethodSuccess != true) {
            Debug.WriteLine("Could not derive signing key.");
            return;
        }

        success = signer.SetMacKeyEncoded(derivedKey,"hex");
        if (success != true) {
            Debug.WriteLine("Could not set signing key.");
            return;
        }

        derivedKey = signer.MacStringENC("s3");
        if (signer.LastMethodSuccess != true) {
            Debug.WriteLine("Could not derive signing key.");
            return;
        }

        success = signer.SetMacKeyEncoded(derivedKey,"hex");
        if (success != true) {
            Debug.WriteLine("Could not set signing key.");
            return;
        }

        derivedKey = signer.MacStringENC("aws4_request");
        if (signer.LastMethodSuccess != true) {
            Debug.WriteLine("Could not derive signing key.");
            return;
        }

        success = signer.SetMacKeyEncoded(derivedKey,"hex");
        if (success != true) {
            Debug.WriteLine("Could not set signing key.");
            return;
        }

        signature = signer.MacStringENC(stringToSign.GetAsString());
        if (signer.LastMethodSuccess != true) {
            Debug.WriteLine("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.Length > 0) {
            url.Append("?");
            url.Append(query.GetAsString());
        }

        success = http.HttpBd("PUT",url.GetAsString(),part,"application/octet-stream",response);
        if ((success != true) || (response.StatusCode != 200)) {
            Debug.WriteLine("Request failed or returned unexpected HTTP status: " + Convert.ToString(response.StatusCode));
            //  Preserve progress. Inspect full diagnostics privately; do not log secrets.
            return;
        }

        confirmed = response.GetHeaderField("x-amz-checksum-sha256");
        stringCompare.SetString(confirmed);
        bool stringMatch9 = stringCompare.ContentsEqual("",true);
        if ((response.LastMethodSuccess != true) || (stringMatch9 == true)) {
            Debug.WriteLine("Missing required response header x-amz-checksum-sha256.");
            return;
        }

        stringCompare.SetString(confirmed);
        bool stringMatch10 = stringCompare.ContentsEqual(partChecksum,true);
        if (stringMatch10 != true) {
            Debug.WriteLine("Part checksum mismatch; preserve checkpoint.");
            return;
        }

        partEtag = response.GetHeaderField("ETag");
        stringCompare.SetString(partEtag);
        bool stringMatch11 = stringCompare.ContentsEqual("",true);
        if ((response.LastMethodSuccess != true) || (stringMatch11 == true)) {
            Debug.WriteLine("Missing required response header ETag.");
            return;
        }

    }
    else {
        Debug.WriteLine("Reusing verified remote part: " + partNumberText.GetAsString());
    }

    completion.I = partIndex;
    completion.UpdateChildContent("Part[i]|PartNumber",partNumberText.GetAsString());
    completion.UpdateChildContent("Part[i]|ETag",partEtag);
    completion.UpdateChildContent("Part[i]|ChecksumSHA256",partChecksum);
    partIndex = partIndex + 1;
}

files.FileClose();
//  Recheck the entire immutable source before committing its parts.
string finalSourceHash = signer.HashFileENC(filePath);
stringCompare.SetString(finalSourceHash);
bool stringMatch12 = stringCompare.ContentsEqual(sourceHash,true);
if ((signer.LastMethodSuccess != true) || (stringMatch12 != true)) {
    Debug.WriteLine("Source changed; completion was not sent.");
    return;
}

compositeChecksum = digest.HashBdENC(concatenatedDigests);
if (digest.LastMethodSuccess != true) {
    Debug.WriteLine("Could not compute composite checksum.");
    return;
}

number.SetString(compositeChecksum);
number.Append("-");
number.AppendInt(numParts);
compositeChecksum = number.GetAsString();
success = pending.UpdateString("uploadId",uploadId);
if (success != true) {
    Debug.WriteLine("Could not save uploadId.");
    return;
}

success = pending.UpdateString("sourceHash",sourceHash);
if (success != true) {
    Debug.WriteLine("Could not save sourceHash.");
    return;
}

success = pending.UpdateString("uploadToken",uploadToken);
if (success != true) {
    Debug.WriteLine("Could not save uploadToken.");
    return;
}

success = pending.UpdateString("checksum",compositeChecksum);
if (success != true) {
    Debug.WriteLine("Could not save checksum.");
    return;
}

success = pending.WriteFile(pendingPath);
if (success != true) {
    Debug.WriteLine("Could not save completion recovery record.");
    return;
}

string requestBody = completion.GetXml();
query.Clear();
if (query.Length > 0) {
    query.Append("&");
}

query.Append("uploadId=");
query.Append(http.UrlEncode(uploadId));
http.ClearHeaders();
success = now.SetFromCurrentSystemTime();
if (success != true) {
    Debug.WriteLine("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);
payloadHash = signer.HashStringENC(requestBody);
if (signer.LastMethodSuccess != true) {
    Debug.WriteLine("Could not hash payload.");
    return;
}

canonicalHeaders.Clear();
signedHeaders.Clear();
if (signedHeaders.Length > 0) {
    signedHeaders.Append(";");
}

signedHeaders.Append("host");
canonicalHeaders.Append("host:");
canonicalHeaders.Append(host.GetAsString());
canonicalHeaders.Append("\n");
http.SetRequestHeader("host",host.GetAsString());
if (signedHeaders.Length > 0) {
    signedHeaders.Append(";");
}

signedHeaders.Append("x-amz-checksum-type");
canonicalHeaders.Append("x-amz-checksum-type:");
canonicalHeaders.Append("COMPOSITE");
canonicalHeaders.Append("\n");
http.SetRequestHeader("x-amz-checksum-type","COMPOSITE");
if (signedHeaders.Length > 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.Length > 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") == true) {
    if (signedHeaders.Length > 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("POST\n");
canonical.Append(uri.GetAsString());
canonical.Append("\n");
canonical.Append(query.GetAsString());
canonical.Append("\n");
canonical.Append(canonicalHeaders.GetAsString());
canonical.Append("\n");
canonical.Append(signedHeaders.GetAsString());
canonical.Append("\n");
canonical.Append(payloadHash);
canonicalHash = signer.HashStringENC(canonical.GetAsString());
if (signer.LastMethodSuccess != true) {
    Debug.WriteLine("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"));
success = signer.SetMacKeyString(signingKey.GetAsString());
if (success != true) {
    Debug.WriteLine("Could not set signing key.");
    return;
}

derivedKey = signer.MacStringENC(dateStamp);
if (signer.LastMethodSuccess != true) {
    Debug.WriteLine("Could not derive signing key.");
    return;
}

success = signer.SetMacKeyEncoded(derivedKey,"hex");
if (success != true) {
    Debug.WriteLine("Could not set signing key.");
    return;
}

derivedKey = signer.MacStringENC(region);
if (signer.LastMethodSuccess != true) {
    Debug.WriteLine("Could not derive signing key.");
    return;
}

success = signer.SetMacKeyEncoded(derivedKey,"hex");
if (success != true) {
    Debug.WriteLine("Could not set signing key.");
    return;
}

derivedKey = signer.MacStringENC("s3");
if (signer.LastMethodSuccess != true) {
    Debug.WriteLine("Could not derive signing key.");
    return;
}

success = signer.SetMacKeyEncoded(derivedKey,"hex");
if (success != true) {
    Debug.WriteLine("Could not set signing key.");
    return;
}

derivedKey = signer.MacStringENC("aws4_request");
if (signer.LastMethodSuccess != true) {
    Debug.WriteLine("Could not derive signing key.");
    return;
}

success = signer.SetMacKeyEncoded(derivedKey,"hex");
if (success != true) {
    Debug.WriteLine("Could not set signing key.");
    return;
}

signature = signer.MacStringENC(stringToSign.GetAsString());
if (signer.LastMethodSuccess != true) {
    Debug.WriteLine("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.Length > 0) {
    url.Append("?");
    url.Append(query.GetAsString());
}

success = http.HttpStr("POST",url.GetAsString(),requestBody,"utf-8","application/xml",response);
if ((success != true) || (response.StatusCode != 200)) {
    Debug.WriteLine("Request failed or returned unexpected HTTP status: " + Convert.ToString(response.StatusCode));
    //  Preserve progress. Inspect full diagnostics privately; do not log secrets.
    return;
}

success = xml.LoadXml(response.BodyStr);
if (success != true) {
    Debug.WriteLine("Invalid XML response.");
    return;
}

stringCompare.SetString(xml.Tag);
bool stringMatch13 = stringCompare.ContentsEqual("CompleteMultipartUploadResult",true);
if (stringMatch13 != true) {
    Debug.WriteLine("Unexpected XML result, possibly an embedded S3 error. Inspect privately.");
    return;
}

confirmed = xml.GetChildContent("ChecksumSHA256");
stringCompare.SetString(confirmed);
bool stringMatch14 = stringCompare.ContentsEqual("",true);
if ((xml.LastMethodSuccess != true) || (stringMatch14 == true)) {
    Debug.WriteLine("Missing required ChecksumSHA256.");
    return;
}

stringCompare.SetString(confirmed);
bool stringMatch15 = stringCompare.ContentsEqual(compositeChecksum,true);
if (stringMatch15 != true) {
    Debug.WriteLine("Completion checksum differs; preserve checkpoint and inspect object.");
    return;
}

success = state.UpdateString("compositeChecksum",compositeChecksum);
if (success != true) {
    Debug.WriteLine("Could not save compositeChecksum.");
    return;
}

success = state.WriteFile("qa_output/s3-multipart/completed.json.tmp");
if (success != true) {
    Debug.WriteLine("Completion succeeded but receipt could not be saved; preserve the checkpoint.");
    return;
}

success = files.FileRename("qa_output/s3-multipart/completed.json.tmp",receiptPath);
if (success != true) {
    Debug.WriteLine("Completion receipt remains at its temporary path.");
    return;
}

Debug.WriteLine("Multipart upload completed and verified.");