Seckey from public key string from server in Swift

For mac:

let pubKey = "-----BEGIN PUBLIC KEY-----MIICIjANBgAgK.......InbFk1FkucQqruMyUCAwEAAQ==-----END PUBLIC KEY-----"
let pubKeyData = pubKey.dataUsingEncoding(NSASCIIStringEncoding)
var error: Unmanaged<CFErrorRef>?
let secKey = SecKeyCreateFromData(NSDictionary(), pubKeyData!, &error)

Where pubKey is a string representation of your public key. If you don't know your public key, you can infer it from your private key with the following command:

openssl rsa -in server.key -pubout  > mykey.pub

Where server.key is the file containing -----BEGIN RSA PRIVATE KEY----- as the first line.

For iOS:

It's a bit more complicate. You need a der file. It's a binary representation of your certificate. If you need to convert an existing certificate, you can do so with the following command:

 openssl x509 -outform der -in file.crt|pem -out mycert.der

The .crt or .pem file contains -----BEGIN CERTIFICATE----- as the first line.

Put the der file in your bundle and do:

let certificateData = NSData(contentsOfURL:NSBundle.mainBundle().URLForResource("mycert", withExtension: "der")!)

let certificate = SecCertificateCreateWithData(nil, certificateData!)

var trust: SecTrustRef?

let policy = SecPolicyCreateBasicX509()
let status = SecTrustCreateWithCertificates(certificate!, policy, &trust)

if status == errSecSuccess {
    let key = SecTrustCopyPublicKey(trust!)!;
}

Yatta ! Key now contains a SecKey representation of your public key. Happy Pinning.