Sample code for 30+ languages & platforms
Swift

Enumerate Private Keys in a PFX

See more PFX/P12 Examples

Demonstrates Pfx.PrivateKeyAt, which copies the private key at a zero-based index into a PrivateKey object. The example enumerates all private keys in the PFX.

The file path is relative to the application's current working directory. An absolute path may also be used. Supply the path appropriate to your own environment.

Background. Valid indexes are less than NumPrivateKeys. Each retrieved key is an independent copy that can be inspected or used separately.

Chilkat Swift Downloads

Swift

func chilkatTest() {
    var success: Bool = false

    let pfx = CkoPfx()!

    //  The file path is relative to the application's current working directory.  An absolute path
    //  may also be used.  Supply the path appropriate to your own environment.
    //  The PFX password should come from a secure source rather than being hard-coded.
    var password: String? = "myPfxPassword"
    success = pfx.loadFile(path: "qa_data/identity.pfx", password: password)
    if success == false {
        print("\(pfx.lastErrorText!)")
        return
    }

    //  Enumerate the private keys in the PFX by zero-based index.  Valid indexes are less than
    //  NumPrivateKeys.
    var numKeys: Int = pfx.numPrivateKeys.intValue
    let privKey = CkoPrivateKey()!
    var i: Int
    for i = 0; i <= numKeys - 1; i++ {
        success = pfx.privateKey(at: i, privKey: privKey)
        if success == false {
            print("\(pfx.lastErrorText!)")
            return
        }

        print("Private key \(i): \(privKey.keyType!) (\(privKey.bitLength.intValue) bits)")
    }


}