Sample code for 30+ languages & platforms
Swift

Load PEM Public/Private Key into RSA Object

See more RSA Examples

Demonstrates how to load a PEM key into the Chilkat RSA object.

Chilkat Swift Downloads

Swift

func chilkatTest() {
    var success: Bool = false

    // This example assumes the Chilkat API to have been previously unlocked.
    // See Global Unlock Sample for sample code.

    let rsa = CkoRsa()!

    // First demonstrate importing a PEM public key:
    var publicKeyPem: String? = "PEM public-key data goes here"
    let pubkey = CkoPublicKey()!

    success = pubkey.load(fromString: publicKeyPem)
    if success == false {
        print("\(pubkey.lastErrorText!)")
        return
    }

    success = rsa.usePublicKey(pubKey: pubkey)
    if success == false {
        print("\(rsa.lastErrorText!)")
        return
    }

    // Demonstrate importing a PEM private key:
    var privateKeyPem: String? = "PEM private-key data goes here"
    let privkey = CkoPrivateKey()!

    // If the private key PEM is protected with a password, then 
    // call LoadEncryptedPem.  Otherwise call LoadPem.
    success = privkey.loadPem(str: privateKeyPem)
    if success == false {
        print("\(privkey.lastErrorText!)")
        return
    }

    success = rsa.usePrivateKey(privKey: privkey)
    if success == false {
        print("\(rsa.lastErrorText!)")
        return
    }

    print("OK!")

}