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

AWS KMS: List All Keys with Pagination

See more AWS KMS Examples

Uses the current AWS KMS API. Configure the region and keep credentials in private qa_data/aws/kms.json, with nonempty string fields access_key and secret_key. The examples do not obtain or refresh credentials. Keep diagnostics private; they may contain credentials or sensitive key data. Create the output directory before running file-writing examples.

Uses the AWS JSON 1.1 protocol with TrentService targets, service kms, HTTPS certificate verification, and Signature Version 4. When using temporary credentials, also provide a nonempty session_token; this Rest example includes it in the signed query on each request. Never log that URL. The endpoint shown is for the commercial AWS partition; use the appropriate endpoint for other partitions. Failures stop the sample; production retry policies should use bounded backoff with jitter and reconcile uncertain writes.

Lists keys in the caller's account and selected region, following Truncated and NextMarker even when an intermediate page is empty. Limit is 1–1000 (default 100); this sample requests 1000. It detects repeated markers and stops at 10,000 pages with an incomplete result message. Results are not an atomic snapshot. ListKeys returns IDs and ARNs, not key status, aliases, or a KeyCount field. Use DescribeKey for metadata. Requires kms:ListKeys on Resource *.

AWS ListKeys reference

Chilkat Unicode C++ Downloads

Unicode C++
#include <CkStringBuilderW.h>
#include <CkJsonObjectW.h>
#include <CkAuthAwsW.h>
#include <CkRestW.h>
#include <CkSocketW.h>
#include <CkHashtableW.h>
#include <CkJsonArrayW.h>

void ChilkatSample(void)
    {
    bool success = false;

    CkStringBuilderW stringCompare;
    //  Assumes Chilkat is unlocked. See Global Unlock Sample.
    //  Keep this credentials file outside public web content and source control.
    CkJsonObjectW credentials;
    credentials.put_Strict(true);
    success = credentials.LoadFile(L"qa_data/aws/kms.json");
    if (success != true) {
        wprintf(L"Could not load private KMS configuration.\n");
        return;
    }

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

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

    const wchar_t *region = L"us-west-2";
    CkStringBuilderW endpoint;
    endpoint.Append(L"kms.");
    endpoint.Append(region);
    endpoint.Append(L".amazonaws.com");
    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"kms");
    aws.put_SignatureVersion(4);
    CkRestW rest;
    rest.put_ConnectTimeoutMs(20000);
    rest.put_IdleTimeoutMs(60000);
    rest.put_VerboseLogging(false);
    success = rest.SetAuthAws(aws);
    if (success != true) {
        wprintf(L"Could not configure AWS signing.\n");
        return;
    }

    if (credentials.HasMember(L"session_token") == true) {
        stringCompare.SetString(credentials.stringOf(L"session_token"));
        bool stringMatch3 = stringCompare.ContentsEqual(L"",true);
        if ((credentials.JsonTypeOf(L"session_token") != 1) || (stringMatch3 == true)) {
            wprintf(L"Missing or invalid session_token.\n");
            return;
        }

    }

    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 TLS connection.\n");
        return;
    }

    //  Keep connection alive while Rest uses it.
    CkJsonObjectW body;
    CkJsonObjectW result;
    result.put_Strict(true);
    const wchar_t *responseJson = 0;
    CkHashtableW seenMarkers;
    CkJsonArrayW keys;
    CkJsonObjectW keyEntry;
    const wchar_t *marker = L"";
    int page = 0;
    int index;
    bool more = true;
    while ((more == true)) {
        if (page == 10000) {
            wprintf(L"Page bound reached; key enumeration is incomplete.\n");
            return;
        }

        page = page + 1;
        body.Clear();
        success = body.UpdateInt(L"Limit",1000);
        if (success != true) {
            wprintf(L"Could not set page size.\n");
            return;
        }

        stringCompare.SetString(marker);
        bool stringMatch4 = stringCompare.ContentsEqual(L"",true);
        if (stringMatch4 != true) {
            success = body.UpdateString(L"Marker",marker);
            if (success != true) {
                wprintf(L"Could not set Marker.\n");
                return;
            }

        }

        success = rest.ClearAllQueryParams();
        if (success != true) {
            wprintf(L"Could not clear previous query parameters.\n");
            return;
        }

        //  Keep the JSON operation body separate from authentication parameters.
        //  Include STS credentials in the signed query; never log the request URL.
        if (credentials.HasMember(L"session_token") == true) {
            success = rest.AddQueryParam(L"X-Amz-Security-Token",credentials.stringOf(L"session_token"));
            if (success != true) {
                wprintf(L"Could not set session token.\n");
                return;
            }

        }

        success = rest.AddHeader(L"X-Amz-Target",L"TrentService.ListKeys");
        if (success != true) {
            wprintf(L"Could not set operation.\n");
            return;
        }

        success = rest.AddHeader(L"Content-Type",L"application/x-amz-json-1.1");
        if (success != true) {
            wprintf(L"Could not set content type.\n");
            return;
        }

        responseJson = rest.fullRequestString(L"POST",L"/",body.emit());
        if (rest.get_LastMethodSuccess() != true) {
            wprintf(L"KMS request did not complete; inspect diagnostics privately. Reconcile any write before retrying.\n");
            return;
        }

        if (rest.get_ResponseStatusCode() != 200) {
            wprintf(L"KMS HTTP status: %d\n",rest.get_ResponseStatusCode());
            success = result.Load(responseJson);
            if (success == true) {
                if (result.JsonTypeOf(L"__type") == 1) {
                    wprintf(L"AWS error code: %s\n",result.stringOf(L"__type"));
                }

            }

            wprintf(L"AWS request ID: %s\n",rest.responseHdrByName(L"x-amzn-RequestId"));
            //  Do not print full bodies, headers, credentials, key material, or tokens.
            return;
        }

        success = result.Load(responseJson);
        if (success != true) {
            wprintf(L"Expected a well-formed JSON response.\n");
            return;
        }

        if ((result.JsonTypeOf(L"Keys") != 4) || (result.JsonTypeOf(L"Truncated") != 5)) {
            wprintf(L"Invalid ListKeys response.\n");
            return;
        }

        success = result.ArrayOf2(L"Keys",keys);
        if (success != true) {
            wprintf(L"Could not read Keys array.\n");
            return;
        }

        index = 0;
        while ((index < keys.get_Size())) {
            success = keys.ObjectAt2(index,keyEntry);
            if (success != true) {
                wprintf(L"Invalid key entry.\n");
                return;
            }

            stringCompare.SetString(keyEntry.stringOf(L"KeyId"));
            bool stringMatch5 = stringCompare.ContentsEqual(L"",true);
            if ((keyEntry.JsonTypeOf(L"KeyId") != 1) || (stringMatch5 == true)) {
                wprintf(L"Missing or invalid KeyId.\n");
                return;
            }

            stringCompare.SetString(keyEntry.stringOf(L"KeyArn"));
            bool stringMatch6 = stringCompare.ContentsEqual(L"",true);
            if ((keyEntry.JsonTypeOf(L"KeyArn") != 1) || (stringMatch6 == true)) {
                wprintf(L"Missing or invalid KeyArn.\n");
                return;
            }

            wprintf(L"Key ID: %s\n",keyEntry.stringOf(L"KeyId"));
            wprintf(L"Key ARN: %s\n",keyEntry.stringOf(L"KeyArn"));
            index = index + 1;
        }

        more = result.BoolOf(L"Truncated");
        if (more == true) {
            stringCompare.SetString(result.stringOf(L"NextMarker"));
            bool stringMatch7 = stringCompare.ContentsEqual(L"",true);
            if ((result.JsonTypeOf(L"NextMarker") != 1) || (stringMatch7 == true)) {
                wprintf(L"Missing or invalid NextMarker.\n");
                return;
            }

            marker = result.stringOf(L"NextMarker");
            if (seenMarkers.Contains(marker) == true) {
                wprintf(L"Repeated marker; key enumeration is incomplete.\n");
                return;
            }

            success = seenMarkers.AddStr(marker,L"seen");
            if (success != true) {
                wprintf(L"Could not track pagination.\n");
                return;
            }

        }

    }

    wprintf(L"Key enumeration complete.\n");
    }