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

AWS KMS: Import a PFX Private Key into a New Signing Key

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.

This convenience-method example configures an access-key/secret-key pair. It explicitly rejects a supplied session_token instead of silently omitting it: token support for this helper configuration has not been established here. Prefer temporary role credentials in production using a documented token-capable integration. The separate Rest examples support a session token. No credentials or private key material are printed.

Loads the certificate's private key from qa_data/pfx/myCertAndKey.pfx using string field pfx_password from the private configuration. Supports RSA 2048/3072/4096 and NIST P-256/P-384/P-521 in this sample. Keep a protected backup of the original material: KMS cannot export it. RSA material must satisfy AWS's current key-material requirements. Tags are visible metadata; do not put passwords or sensitive certificate identity data in them.

The UploadToCloud convenience method creates a new external-origin KMS key and imports the private key, with KeyUsage=SIGN_VERIFY. Rerunning can create additional keys and charges. On failure, inspect KMS/CloudTrail before deciding whether to retry or clean up a pending key. Required permissions include kms:CreateKey, kms:TagResource, kms:GetParametersForImport, and kms:ImportKeyMaterial, subject to IAM and key policy. The certificate itself stays local. Record the returned KeyId; inspect DescribeKey for state and expiration policy. Use the explicit low-level example when you need control of an existing destination key and import settings.

AWS ImportKeyMaterial 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"
    //  These convenience-method examples use an access-key/secret-key pair.
    //  Do not silently discard the token belonging to temporary credentials.
    if credentials.hasMember(jsonPath: "session_token") == true {
        print("This convenience-method sample does not configure temporary credentials. Use a documented token-capable signing/import integration.")
        return
    }

    //  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 stringMatch3: Bool = stringCompare.contentsEqual(str: "RSA", caseSensitive: true)
    if stringMatch3 == 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 stringMatch4: Bool = stringCompare.contentsEqual(str: "EC", caseSensitive: true)
    if stringMatch4 == true {
        stringCompare.setString(value: keyInfo.string(of: "crv"))
        var stringMatch5: Bool = stringCompare.contentsEqual(str: "P-256", caseSensitive: true)
        if stringMatch5 == true {
            keySpec = "ECC_NIST_P256"
        }

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

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

    }

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

    let options = CkoJsonObject()!
    success = options.updateString(jsonPath: "service", value: "aws-kms")
    if success != true {
        print("Could not set service.")
        return
    }

    success = options.updateString(jsonPath: "auth.access_key", value: credentials.string(of: "access_key"))
    if success != true {
        print("Could not set auth.access_key.")
        return
    }

    success = options.updateString(jsonPath: "auth.secret_key", value: credentials.string(of: "secret_key"))
    if success != true {
        print("Could not set auth.secret_key.")
        return
    }

    success = options.updateString(jsonPath: "auth.region", value: region)
    if success != true {
        print("Could not set auth.region.")
        return
    }

    success = options.updateString(jsonPath: "description", value: "Imported certificate signing key")
    if success != true {
        print("Could not set description.")
        return
    }

    success = options.updateString(jsonPath: "tags[0].key", value: "Purpose")
    if success != true {
        print("Could not set tags[0].key.")
        return
    }

    success = options.updateString(jsonPath: "tags[0].value", value: "DocumentSigning")
    if success != true {
        print("Could not set tags[0].value.")
        return
    }

    success = options.updateString(jsonPath: "keyUsage", value: "SIGN_VERIFY")
    if success != true {
        print("Could not set keyUsage.")
        return
    }

    let imported = CkoJsonObject()!
    //  Creates a NEW KMS key. Do not blindly rerun after an uncertain failure.
    success = privKey.upload(toCloud: options, jsonOut: imported)
    if success != true {
        print("Import failed or its outcome is uncertain. Check KMS/CloudTrail before retrying; inspect diagnostics privately.")
        return
    }

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

    print("Imported KMS key ID: \(imported.string(of: "KeyId")!)")
    //  Save this identifier securely for subsequent signing and lifecycle management.

}