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

Amazon S3: Upload with SSE-KMS and Verify Encryption

See more S3 - REST Examples

Supply a KMS key ARN in the same region as the bucket. PUT requests SSE-KMS and stores a full-object SHA-256 checksum for use by the checksum-verification example. HEAD checks the algorithm and key ARN using the returned version ID when available and the written ETag. Write-only encryption headers are removed before HEAD. This is server-side encryption; plaintext is sent over HTTPS and S3 encrypts it at rest.

Requires s3:PutObject, kms:GenerateDataKey, and permission to read the resulting object metadata. Subsequent downloads can need kms:Decrypt; IAM and KMS key policies must both permit the operation. Use the full key ARN to avoid alias/account ambiguity. Encryption does not make an object public or replace access control. The selected key can overwrite an unversioned object or create a new version. KMS requests can incur charges.

For general purpose S3 buckets, using regional HTTPS endpoints and AWS Signature Version 4. Directory buckets (S3 Express), access points, Outposts, and other AWS partitions need their own endpoint/authentication rules. Use a bucket name without dots for these virtual-hosted TLS examples; see the path-style example for dotted names.

Provide current IAM credentials in a private qa_data/aws/s3.json file with string fields access_key, secret_key, and session_token for temporary credentials. Prefer short-lived role credentials. This file is explicitly loaded; these examples do not discover profiles or refresh credentials. Keep it outside public content and source control. The session token is included in the signed request. TLS certificate verification is enabled on the Socket used by Rest.

Transport success and HTTP success are different. Keep full diagnostics private; signed requests and presigned URLs can contain credentials or grant access. For retryable reads use bounded backoff with jitter. Before retrying a write with an uncertain outcome, check the resource state. Keep keys, upload IDs, version IDs, ETags, and large sizes as strings.

AWS PutObject reference

Chilkat Unicode C++ Downloads

Unicode C++
#include <CkStringBuilderW.h>
#include <CkJsonObjectW.h>
#include <CkAuthAwsW.h>
#include <CkRestW.h>
#include <CkSocketW.h>
#include <CkXmlW.h>
#include <CkCrypt2W.h>

void ChilkatSample(void)
    {
    bool success = false;

    //  StringBuilder compares text by value in every generated language.
    CkStringBuilderW textCompare;
    //  Assumes Chilkat is unlocked. See Global Unlock Sample.
    success = false;
    //  Private configuration, not a file in public web content or source control.
    //  Load current IAM credentials authorized for the S3 operation.
    CkJsonObjectW credentials;
    credentials.put_Strict(true);
    success = credentials.LoadFile(L"qa_data/aws/s3.json");
    if (success != true) {
        wprintf(L"Could not load private AWS credentials.\n");
        return;
    }

    textCompare.Clear();
    textCompare.SetString(credentials.stringOf(L"access_key"));
    bool sameText1 = textCompare.ContentsEqual(L"",true);
    if ((credentials.JsonTypeOf(L"access_key") != 1) || (sameText1 == true)) {
        wprintf(L"Missing or invalid access_key.\n");
        return;
    }

    textCompare.Clear();
    textCompare.SetString(credentials.stringOf(L"secret_key"));
    bool sameText2 = textCompare.ContentsEqual(L"",true);
    if ((credentials.JsonTypeOf(L"secret_key") != 1) || (sameText2 == true)) {
        wprintf(L"Missing or invalid secret_key.\n");
        return;
    }

    //  General purpose bucket in the commercial AWS partition.
    const wchar_t *region = L"us-west-2";
    const wchar_t *bucketName = L"amzn-s3-demo-bucket";
    CkStringBuilderW endpoint;
    success = endpoint.Append(bucketName);
    if (success != true) {
        wprintf(L"Could not build text.\n");
        return;
    }

    success = endpoint.Append(L".");
    if (success != true) {
        wprintf(L"Could not build text.\n");
        return;
    }

    success = endpoint.Append(L"s3.");
    if (success != true) {
        wprintf(L"Could not build text.\n");
        return;
    }

    success = endpoint.Append(region);
    if (success != true) {
        wprintf(L"Could not build text.\n");
        return;
    }

    success = endpoint.Append(L".amazonaws.com");
    if (success != true) {
        wprintf(L"Could not build text.\n");
        return;
    }

    CkAuthAwsW aws;
    aws.put_AccessKey(credentials.stringOf(L"access_key"));
    aws.put_SecretKey(credentials.stringOf(L"secret_key"));
    aws.put_Region(region);
    aws.put_ServiceName(L"s3");
    aws.put_SignatureVersion(4);
    CkRestW rest;
    rest.put_ConnectTimeoutMs(20000);
    rest.put_IdleTimeoutMs(60000);
    success = rest.SetAuthAws(aws);
    if (success != true) {
        wprintf(L"Could not configure AWS signing.\n");
        return;
    }

    //  Temporary credentials require this token in every signed query.
    //  Keep request URLs private. Do not clear this parameter between requests.
    if (credentials.HasMember(L"session_token") == true) {
        if (credentials.JsonTypeOf(L"session_token") != 1) {
            wprintf(L"session_token must be a string.\n");
            return;
        }

        textCompare.Clear();
        textCompare.SetString(credentials.stringOf(L"session_token"));
        bool sameText3 = textCompare.ContentsEqual(L"",true);
        if (sameText3 != true) {
            success = rest.AddQueryParam(L"X-Amz-Security-Token",credentials.stringOf(L"session_token"));
            if (success != true) {
                wprintf(L"Could not prepare the request.\n");
                return;
            }

        }

    }

    //  Connect to the SAME hostname used for TLS verification and request signing.
    CkSocketW connection;
    connection.put_RequireSslCertVerify(true);
    connection.put_MaxReadIdleMs(60000);
    connection.put_MaxSendIdleMs(60000);
    success = connection.Connect(endpoint.getAsString(),443,true,20000);
    if (success != true) {
        wprintf(L"TLS connection failed; inspect diagnostics privately.\n");
        return;
    }

    success = rest.UseConnection(connection,true);
    if (success != true) {
        wprintf(L"Could not attach the TLS connection.\n");
        return;
    }

    CkXmlW xml;
    xml.put_Strict(true);
    //  Supply an unencoded object key, not a URL. Preserve slashes in the key.
    const wchar_t *objectKey = L"documents/example.txt";
    CkStringBuilderW objectPath;
    success = objectPath.Append(objectKey);
    if (success != true) {
        wprintf(L"Could not build text.\n");
        return;
    }

    success = objectPath.Encode(L"url_rfc3986",L"utf-8");
    if (success != true) {
        wprintf(L"Could not encode the object key.\n");
        return;
    }

    int restoredSlashes = objectPath.Replace(L"%2F",L"/");
    success = objectPath.Prepend(L"/");
    if (success != true) {
        wprintf(L"Could not prepare the request.\n");
        return;
    }

    const wchar_t *kmsKeyArn = L"arn:aws:kms:us-west-2:123456789012:key/11111111-2222-3333-4444-555555555555";
    success = rest.AddHeader(L"x-amz-server-side-encryption",L"aws:kms");
    if (success != true) {
        wprintf(L"Could not prepare the request.\n");
        return;
    }

    success = rest.AddHeader(L"x-amz-server-side-encryption-aws-kms-key-id",kmsKeyArn);
    if (success != true) {
        wprintf(L"Could not prepare the request.\n");
        return;
    }

    success = rest.AddHeader(L"Content-Type",L"text/plain; charset=utf-8");
    if (success != true) {
        wprintf(L"Could not prepare the request.\n");
        return;
    }

    const wchar_t *requestBody = L"Encrypted at rest by S3.\n";
    CkCrypt2W digest;
    digest.put_Charset(L"utf-8");
    digest.put_HashAlgorithm(L"sha256");
    digest.put_EncodingMode(L"base64");
    const wchar_t *checksumBase64 = digest.hashStringENC(requestBody);
    if (digest.get_LastMethodSuccess() != true) {
        wprintf(L"Could not calculate the content checksum.\n");
        return;
    }

    success = rest.AddHeader(L"x-amz-checksum-sha256",checksumBase64);
    if (success != true) {
        wprintf(L"Could not prepare the request.\n");
        return;
    }

    const wchar_t *responseBody = rest.fullRequestString(L"PUT",objectPath.getAsString(),requestBody);
    if (rest.get_LastMethodSuccess() != true) {
        wprintf(L"Request did not complete; inspect diagnostics privately.\n");
        return;
    }

    if (rest.get_ResponseStatusCode() != 200) {
        wprintf(L"S3 HTTP status: %d\n",rest.get_ResponseStatusCode());
        success = xml.LoadXml(responseBody);
        textCompare.Clear();
        textCompare.SetString(xml.tag());
        bool sameText4 = textCompare.ContentsEqual(L"Error",true);
        if ((success == true) && (sameText4 == true)) {
            wprintf(L"S3 error code: %s\n",xml.getChildContent(L"Code"));
        }

        //  Keep signed headers, credentials, URLs, and full diagnostics private.
        //  A timeout may leave a write's outcome uncertain. Check before retrying.
        return;
    }

    const wchar_t *writtenEtag = rest.responseHdrByName(L"ETag");
    textCompare.Clear();
    textCompare.SetString(writtenEtag);
    bool sameText5 = textCompare.ContentsEqual(L"",true);
    if ((rest.get_LastMethodSuccess() != true) || (sameText5 == true)) {
        wprintf(L"Missing response header: ETag\n");
        return;
    }

    const wchar_t *writtenVersion = rest.responseHdrByName(L"x-amz-version-id");
    if (rest.get_LastMethodSuccess() != true) {
        writtenVersion = L"";
    }

    success = rest.RemoveHeader(L"x-amz-server-side-encryption");
    if (success != true) {
        wprintf(L"Could not prepare the request.\n");
        return;
    }

    success = rest.RemoveHeader(L"x-amz-server-side-encryption-aws-kms-key-id");
    if (success != true) {
        wprintf(L"Could not prepare the request.\n");
        return;
    }

    success = rest.RemoveHeader(L"x-amz-checksum-sha256");
    if (success != true) {
        wprintf(L"Could not prepare the request.\n");
        return;
    }

    success = rest.RemoveHeader(L"Content-Type");
    if (success != true) {
        wprintf(L"Could not prepare the request.\n");
        return;
    }

    textCompare.Clear();
    textCompare.SetString(writtenVersion);
    bool sameText6 = textCompare.ContentsEqual(L"",true);
    if (sameText6 != true) {
        success = rest.AddQueryParam(L"versionId",writtenVersion);
        if (success != true) {
            wprintf(L"Could not prepare the request.\n");
            return;
        }

    }

    //  Also protect the mutable null version and unversioned objects with the ETag.
    success = rest.AddHeader(L"If-Match",writtenEtag);
    if (success != true) {
        wprintf(L"Could not prepare the request.\n");
        return;
    }

    success = rest.SendReqNoBody(L"HEAD",objectPath.getAsString());
    if (success != true) {
        wprintf(L"Could not send HEAD request.\n");
        return;
    }

    int statusCode = rest.ReadResponseHeader();
    if (statusCode < 0) {
        wprintf(L"Could not read the response header.\n");
        return;
    }

    if (statusCode != 200) {
        wprintf(L"HEAD did not return HTTP 200. A 403 is not proof that an object is missing.\n");
        return;
    }

    //  HEAD has no response body; do not call a body-reading method.
    const wchar_t *encryption = rest.responseHdrByName(L"x-amz-server-side-encryption");
    textCompare.Clear();
    textCompare.SetString(encryption);
    bool sameText7 = textCompare.ContentsEqual(L"",true);
    if ((rest.get_LastMethodSuccess() != true) || (sameText7 == true)) {
        wprintf(L"Missing response header: x-amz-server-side-encryption\n");
        return;
    }

    const wchar_t *actualKey = rest.responseHdrByName(L"x-amz-server-side-encryption-aws-kms-key-id");
    textCompare.Clear();
    textCompare.SetString(actualKey);
    bool sameText8 = textCompare.ContentsEqual(L"",true);
    if ((rest.get_LastMethodSuccess() != true) || (sameText8 == true)) {
        wprintf(L"Missing response header: x-amz-server-side-encryption-aws-kms-key-id\n");
        return;
    }

    textCompare.Clear();
    textCompare.SetString(encryption);
    bool sameText9 = textCompare.ContentsEqual(L"aws:kms",true);
    textCompare.Clear();
    textCompare.SetString(actualKey);
    bool sameText10 = textCompare.ContentsEqual(kmsKeyArn,true);
    if ((sameText9 != true) || (sameText10 != true)) {
        wprintf(L"Upload returned success, but encryption metadata did not match the requested KMS key.\n");
        return;
    }

    wprintf(L"Upload and SSE-KMS encryption metadata verified.\n");
    }