Sample code for 30+ languages & platforms
Swift 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 Swift Downloads

Swift

func chilkatTest() {
    var success: Bool = false

    let stringCompare = CkoStringBuilder()!
    //  Assumes Chilkat is unlocked. See Global Unlock Sample.
    //  Keep this credentials file outside public web content and source control.
    let credentials = CkoJsonObject()!
    credentials.strict = true
    success = credentials.loadFile(path: "qa_data/aws/kms.json")
    if success != true {
        print("Could not load private KMS configuration.")
        return
    }

    stringCompare.setString(value: credentials.string(of: "access_key"))
    var stringMatch1: Bool = stringCompare.contentsEqual(str: "", caseSensitive: true)
    if (credentials.jsonType(of: "access_key").intValue != 1) || (stringMatch1 == true) {
        print("Missing or invalid access_key.")
        return
    }

    stringCompare.setString(value: credentials.string(of: "secret_key"))
    var stringMatch2: Bool = stringCompare.contentsEqual(str: "", caseSensitive: true)
    if (credentials.jsonType(of: "secret_key").intValue != 1) || (stringMatch2 == true) {
        print("Missing or invalid secret_key.")
        return
    }

    var region: String? = "us-west-2"
    let endpoint = CkoStringBuilder()!
    endpoint.append(value: "kms.")
    endpoint.append(value: region)
    endpoint.append(value: ".amazonaws.com")
    let aws = CkoAuthAws()!
    aws.accessKey = credentials.string(of: "access_key")
    aws.secretKey = credentials.string(of: "secret_key")
    aws.region = region
    aws.serviceName = "kms"
    aws.signatureVersion = 4
    let rest = CkoRest()!
    rest.connectTimeoutMs = 20000
    rest.idleTimeoutMs = 60000
    rest.verboseLogging = false
    success = rest.setAuthAws(authProvider: aws)
    if success != true {
        print("Could not configure AWS signing.")
        return
    }

    if credentials.hasMember(jsonPath: "session_token") == true {
        stringCompare.setString(value: credentials.string(of: "session_token"))
        var stringMatch3: Bool = stringCompare.contentsEqual(str: "", caseSensitive: true)
        if (credentials.jsonType(of: "session_token").intValue != 1) || (stringMatch3 == true) {
            print("Missing or invalid session_token.")
            return
        }

    }

    let connection = CkoSocket()!
    connection.requireSslCertVerify = true
    connection.maxReadIdleMs = 60000
    connection.maxSendIdleMs = 60000
    success = connection.connect(hostname: endpoint.getAsString(), port: 443, ssl: true, maxWaitMs: 20000)
    if success != true {
        print("TLS connection failed; inspect diagnostics privately.")
        return
    }

    success = rest.useConnection(connection: connection, autoReconnect: true)
    if success != true {
        print("Could not attach TLS connection.")
        return
    }

    //  Keep connection alive while Rest uses it.
    let body = CkoJsonObject()!
    let result = CkoJsonObject()!
    result.strict = true
    var responseJson: String?
    let seenMarkers = CkoHashtable()!
    let keys = CkoJsonArray()!
    let keyEntry = CkoJsonObject()!
    var marker: String? = ""
    var page: Int = 0
    var index: Int
    var more: Bool = true
    while (more == true) {
        if page == 10000 {
            print("Page bound reached; key enumeration is incomplete.")
            return
        }

        page = page + 1
        body.clear()
        success = body.updateInt(jsonPath: "Limit", value: 1000)
        if success != true {
            print("Could not set page size.")
            return
        }

        stringCompare.setString(value: marker)
        var stringMatch4: Bool = stringCompare.contentsEqual(str: "", caseSensitive: true)
        if stringMatch4 != true {
            success = body.updateString(jsonPath: "Marker", value: marker)
            if success != true {
                print("Could not set Marker.")
                return
            }

        }

        success = rest.clearAllQueryParams()
        if success != true {
            print("Could not clear previous query parameters.")
            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(jsonPath: "session_token") == true {
            success = rest.addQueryParam(name: "X-Amz-Security-Token", value: credentials.string(of: "session_token"))
            if success != true {
                print("Could not set session token.")
                return
            }

        }

        success = rest.addHeader(name: "X-Amz-Target", value: "TrentService.ListKeys")
        if success != true {
            print("Could not set operation.")
            return
        }

        success = rest.addHeader(name: "Content-Type", value: "application/x-amz-json-1.1")
        if success != true {
            print("Could not set content type.")
            return
        }

        responseJson = rest.fullRequestString(httpVerb: "POST", uriPath: "/", bodyText: body.emit())
        if rest.lastMethodSuccess != true {
            print("KMS request did not complete; inspect diagnostics privately. Reconcile any write before retrying.")
            return
        }

        if rest.responseStatusCode.intValue != 200 {
            print("KMS HTTP status: \(rest.responseStatusCode.intValue)")
            success = result.load(json: responseJson)
            if success == true {
                if result.jsonType(of: "__type").intValue == 1 {
                    print("AWS error code: \(result.string(of: "__type")!)")
                }

            }

            print("AWS request ID: \(rest.responseHdr(byName: "x-amzn-RequestId")!)")
            //  Do not print full bodies, headers, credentials, key material, or tokens.
            return
        }

        success = result.load(json: responseJson)
        if success != true {
            print("Expected a well-formed JSON response.")
            return
        }

        if (result.jsonType(of: "Keys").intValue != 4) || (result.jsonType(of: "Truncated").intValue != 5) {
            print("Invalid ListKeys response.")
            return
        }

        success = result.arrayOf2(jsonPath: "Keys", jarr: keys)
        if success != true {
            print("Could not read Keys array.")
            return
        }

        index = 0
        while (index < keys.size.intValue) {
            success = keys.objectAt2(index: index, jsonObj: keyEntry)
            if success != true {
                print("Invalid key entry.")
                return
            }

            stringCompare.setString(value: keyEntry.string(of: "KeyId"))
            var stringMatch5: Bool = stringCompare.contentsEqual(str: "", caseSensitive: true)
            if (keyEntry.jsonType(of: "KeyId").intValue != 1) || (stringMatch5 == true) {
                print("Missing or invalid KeyId.")
                return
            }

            stringCompare.setString(value: keyEntry.string(of: "KeyArn"))
            var stringMatch6: Bool = stringCompare.contentsEqual(str: "", caseSensitive: true)
            if (keyEntry.jsonType(of: "KeyArn").intValue != 1) || (stringMatch6 == true) {
                print("Missing or invalid KeyArn.")
                return
            }

            print("Key ID: \(keyEntry.string(of: "KeyId")!)")
            print("Key ARN: \(keyEntry.string(of: "KeyArn")!)")
            index = index + 1
        }

        more = result.bool(of: "Truncated")
        if more == true {
            stringCompare.setString(value: result.string(of: "NextMarker"))
            var stringMatch7: Bool = stringCompare.contentsEqual(str: "", caseSensitive: true)
            if (result.jsonType(of: "NextMarker").intValue != 1) || (stringMatch7 == true) {
                print("Missing or invalid NextMarker.")
                return
            }

            marker = result.string(of: "NextMarker")
            if seenMarkers.contains(key: marker) == true {
                print("Repeated marker; key enumeration is incomplete.")
                return
            }

            success = seenMarkers.addStr(key: marker, value: "seen")
            if success != true {
                print("Could not track pagination.")
                return
            }

        }

    }

    print("Key enumeration complete.")

}