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

AWS KMS: Import a PFX Signing Key with a 30-Day Expiration

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.

Where a key is required, set string key_id to its fixed key ARN in the configured region. Additional named fields and input files are described below. Keep output files private when they contain plaintext or policies. The code does not automatically retry mutations, refresh credentials, or create output directories. A successful request can precede propagation of a state change. Discard sensitive objects promptly; clearing one buffer does not erase copies held in strings, JSON, or runtime memory.

Uses the same checked RSA/AES wrapping flow as the existing low-level import example. Provide pfx_password and key_id and the private qa_data/pfx/myCertAndKey.pfx. Requires an EXTERNAL PendingImport signing key matching the PFX key specification. Material expires 30 days from execution (distinct from the wrapping-token lifetime). Expiration disables cryptographic use until the same material is reimported. Retain a protected original backup. Hybrid wrapping is unavailable in China Regions.

API actions used: kms:DescribeKey, kms:GetParametersForImport, kms:ImportKeyMaterial. IAM permissions and key policies must allow the actual resources; grant and multi-Region workflows can need permissions in more than one region/account.

DescribeKey | GetParametersForImport | ImportKeyMaterial

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?
    //  pfx_password is a string; an empty string is allowed for an unprotected PFX.
    if credentials.jsonType(of: "pfx_password").intValue != 1 {
        print("Missing or invalid pfx_password.")
        return
    }

    let cert = CkoCert()!
    success = cert.loadPfxFile(path: "qa_data/pfx/myCertAndKey.pfx", password: credentials.string(of: "pfx_password"))
    if success != true {
        print("Could not load PFX; inspect diagnostics privately.")
        return
    }

    let privKey = CkoPrivateKey()!
    success = cert.getPrivateKey(privKey: privKey)
    if success != true {
        print("PFX does not contain a usable private key.")
        return
    }

    //  Only inspect the PUBLIC JWK to identify a supported key type and curve.
    let sourcePublic = CkoPublicKey()!
    success = privKey.toPublicKey(pubKey: sourcePublic)
    if success != true {
        print("Could not get the public key.")
        return
    }

    var publicJwk: String? = sourcePublic.getJwk()
    if sourcePublic.lastMethodSuccess != true {
        print("Could not inspect public key type.")
        return
    }

    let keyInfo = CkoJsonObject()!
    keyInfo.strict = true
    success = keyInfo.load(json: publicJwk)
    if success != true {
        print("Could not parse public key description.")
        return
    }

    var keySpec: String? = ""
    stringCompare.setString(value: keyInfo.string(of: "kty"))
    var stringMatch4: Bool = stringCompare.contentsEqual(str: "RSA", caseSensitive: true)
    if stringMatch4 == true {
        if privKey.bitLength.intValue == 2048 {
            keySpec = "RSA_2048"
        }

        if privKey.bitLength.intValue == 3072 {
            keySpec = "RSA_3072"
        }

        if privKey.bitLength.intValue == 4096 {
            keySpec = "RSA_4096"
        }

    }

    stringCompare.setString(value: keyInfo.string(of: "kty"))
    var stringMatch5: Bool = stringCompare.contentsEqual(str: "EC", caseSensitive: true)
    if stringMatch5 == true {
        stringCompare.setString(value: keyInfo.string(of: "crv"))
        var stringMatch6: Bool = stringCompare.contentsEqual(str: "P-256", caseSensitive: true)
        if stringMatch6 == true {
            keySpec = "ECC_NIST_P256"
        }

        stringCompare.setString(value: keyInfo.string(of: "crv"))
        var stringMatch7: Bool = stringCompare.contentsEqual(str: "P-384", caseSensitive: true)
        if stringMatch7 == true {
            keySpec = "ECC_NIST_P384"
        }

        stringCompare.setString(value: keyInfo.string(of: "crv"))
        var stringMatch8: Bool = stringCompare.contentsEqual(str: "P-521", caseSensitive: true)
        if stringMatch8 == true {
            keySpec = "ECC_NIST_P521"
        }

    }

    stringCompare.setString(value: keySpec)
    var stringMatch9: Bool = stringCompare.contentsEqual(str: "", caseSensitive: true)
    if stringMatch9 == true {
        print("Use RSA 2048/3072/4096 or a NIST P-256/P-384/P-521 EC private key.")
        return
    }

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

    var keyId: String? = credentials.string(of: "key_id")
    success = body.updateString(jsonPath: "KeyId", value: keyId)
    if success != true {
        print("Could not set KeyId.")
        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.DescribeKey")
    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
    }

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

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

    stringCompare.setString(value: result.string(of: "KeyMetadata.Origin"))
    var stringMatch13: Bool = stringCompare.contentsEqual(str: "EXTERNAL", caseSensitive: true)
    if stringMatch13 != true {
        print("Destination must have EXTERNAL origin.")
        return
    }

    stringCompare.setString(value: result.string(of: "KeyMetadata.KeyState"))
    var stringMatch14: Bool = stringCompare.contentsEqual(str: "PendingImport", caseSensitive: true)
    if stringMatch14 != true {
        print("This initial-import sample requires PendingImport; it does not replace existing material.")
        return
    }

    stringCompare.setString(value: result.string(of: "KeyMetadata.KeyUsage"))
    var stringMatch15: Bool = stringCompare.contentsEqual(str: "SIGN_VERIFY", caseSensitive: true)
    if stringMatch15 != true {
        print("Destination must have SIGN_VERIFY usage.")
        return
    }

    stringCompare.setString(value: result.string(of: "KeyMetadata.KeySpec"))
    var stringMatch16: Bool = stringCompare.contentsEqual(str: keySpec, caseSensitive: true)
    if stringMatch16 != true {
        print("PFX private key does not match the destination KeySpec.")
        return
    }

    //  Pin subsequent requests to the resolved ARN, not a mutable alias.
    keyId = result.string(of: "KeyMetadata.Arn")
    body.clear()
    success = body.updateString(jsonPath: "KeyId", value: keyId)
    if success != true {
        print("Could not set KeyId.")
        return
    }

    success = body.updateString(jsonPath: "WrappingAlgorithm", value: "RSA_AES_KEY_WRAP_SHA_256")
    if success != true {
        print("Could not set WrappingAlgorithm.")
        return
    }

    success = body.updateString(jsonPath: "WrappingKeySpec", value: "RSA_4096")
    if success != true {
        print("Could not set WrappingKeySpec.")
        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.GetParametersForImport")
    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
    }

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

    stringCompare.setString(value: result.string(of: "KeyId"))
    var stringMatch18: Bool = stringCompare.contentsEqual(str: keyId, caseSensitive: true)
    if stringMatch18 != true {
        print("Import parameters belong to another key.")
        return
    }

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

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

    if result.jsonType(of: "ParametersValidTo").intValue != 2 {
        print("Missing import-parameter expiration.")
        return
    }

    let now = CkoDateTime()!
    let expires = CkoDateTime()!
    success = now.setFromCurrentSystemTime()
    if success != true {
        print("Could not read current time.")
        return
    }

    success = result.date(of: "ParametersValidTo", dateTime: expires)
    if success != true {
        print("Invalid import-parameter expiration.")
        return
    }

    if expires.diffSeconds(dateTimeArg: now).intValue <= 0 {
        print("Import parameters have expired; obtain a fresh token and wrapping key together.")
        return
    }

    var importToken: String? = result.string(of: "ImportToken")
    let wrappingKey = CkoPublicKey()!
    success = wrappingKey.loadBase64(keyStr: result.string(of: "PublicKey"))
    if success != true {
        print("Could not load the RSA wrapping key.")
        return
    }

    if wrappingKey.keySize.intValue != 4096 {
        print("Expected the requested 4096-bit RSA wrapping key.")
        return
    }

    //  Export PKCS#8 DER in memory only; never print or write unencrypted key material.
    var pkcs8Base64: String? = privKey.getPkcs8ENC(encoding: "base64")
    if privKey.lastMethodSuccess != true {
        print("Could not encode the private key as PKCS#8.")
        return
    }

    let prng = CkoPrng()!
    //  A fresh 32-byte (256-bit) AES key, not a 32-bit key.
    var aesKeyBase64: String? = prng.genRandom(numBytes: 32, encoding: "base64")
    if prng.lastMethodSuccess != true {
        print("Could not generate wrapping key.")
        return
    }

    let crypt = CkoCrypt2()!
    var wrappedPrivateKey: String? = crypt.aesKeyWrap(withPadding: aesKeyBase64, keyData: pkcs8Base64, encoding: "base64")
    if crypt.lastMethodSuccess != true {
        print("AES key wrapping failed.")
        return
    }

    let wrappedAesKey = CkoBinData()!
    success = wrappedAesKey.appendEncoded(encData: aesKeyBase64, encoding: "base64")
    if success != true {
        print("Could not decode AES key.")
        return
    }

    let rsa = CkoRsa()!
    success = rsa.usePublicKey(pubKey: wrappingKey)
    if success != true {
        print("Could not select the RSA wrapping key.")
        return
    }

    rsa.pkcsPadding = false
    rsa.oaepHash = "sha256"
    rsa.oaepMgfHash = "sha256"
    success = rsa.encryptBd(bd: wrappedAesKey, usePrivateKey: false)
    if success != true {
        print("RSA-OAEP AES-key wrapping failed.")
        return
    }

    //  Wire order is RSA-wrapped AES key FIRST, followed by AES-wrapped PKCS#8.
    let encryptedMaterial = CkoBinData()!
    success = encryptedMaterial.appendBd(binData: wrappedAesKey)
    if success != true {
        print("Could not assemble encrypted material.")
        return
    }

    success = encryptedMaterial.appendEncoded(encData: wrappedPrivateKey, encoding: "base64")
    if success != true {
        print("Could not append wrapped private key.")
        return
    }

    body.clear()
    success = body.updateString(jsonPath: "KeyId", value: keyId)
    if success != true {
        print("Could not set KeyId.")
        return
    }

    success = body.updateString(jsonPath: "ImportToken", value: importToken)
    if success != true {
        print("Could not set ImportToken.")
        return
    }

    success = body.updateString(jsonPath: "EncryptedKeyMaterial", value: encryptedMaterial.getEncoded(encoding: "base64"))
    if success != true {
        print("Could not set EncryptedKeyMaterial.")
        return
    }

    let validTo = CkoDateTime()!
    success = validTo.setFromCurrentSystemTime()
    if success != true {
        print("Could not set expiration time.")
        return
    }

    success = validTo.addDays(numDays: 30)
    if success != true {
        print("Could not compute expiration.")
        return
    }

    success = body.updateNumber(jsonPath: "ValidTo", numericStr: validTo.get(asUnixTimeStr: false))
    if success != true {
        print("Could not set material expiration.")
        return
    }

    success = body.updateString(jsonPath: "ExpirationModel", value: "KEY_MATERIAL_EXPIRES")
    if success != true {
        print("Could not set ExpirationModel.")
        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.ImportKeyMaterial")
    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
    }

    //  HTTP 200 indicates acceptance; response content can be empty.
    print("Key material import accepted for: \(keyId!)")
    print("Use DescribeKey to confirm Enabled before signing; KMS is eventually consistent.")
    //  This does not securely erase copies of sensitive strings from managed memory.
    print("Example completed.")

}