Sample code for 30+ languages & platforms
Swift

Export a Private Key as Traditional PEM

See more Private Key Examples

Demonstrates the Chilkat PrivateKey.GetPkcs1Pem method, which exports the key as unencrypted PEM, preferring the traditional algorithm-specific representation when one exists (for example -----BEGIN RSA PRIVATE KEY-----). It takes no arguments.

Note: The file paths are relative to the application's current working directory. Absolute paths may also be used. Supply the paths appropriate to your own environment.

Background: Before PKCS #8 unified key storage, each algorithm had its own PEM format — RSA PRIVATE KEY, EC PRIVATE KEY, and so on. Some older tools still expect that traditional form, and this method produces it. When you have the choice, PKCS #8 (GetPkcs8Pem) is the more interoperable modern option; use this for compatibility with software that requires the legacy layout.

Chilkat Swift Downloads

Swift

func chilkatTest() {
    var success: Bool = false

    //  Load a private key to export.
    let privKey = CkoPrivateKey()!
    success = privKey.loadPemFile(path: "qa_data/private.pem")
    if success == false {
        print("\(privKey.lastErrorText!)")
        return
    }

    //  Export as unencrypted PEM, preferring the traditional algorithm-specific representation when
    //  one exists (for example "-----BEGIN RSA PRIVATE KEY-----").
    var pem: String? = privKey.getPkcs1Pem()
    if privKey.lastMethodSuccess == false {
        print("\(privKey.lastErrorText!)")
        return
    }

    print("\(pem!)")

}