Dmytro Rostopira
Dmytro Rostopira

Reputation: 11155

Get SecKey from SecCertificate pre iOS 10.3

I need to get public key from certificate

I've found a way to do it on iOS 12+ and iOS 10.3+, but how can I do it on iOS 10.0+?

    func publicKey(for certificate: SecCertificate) -> SecKey? {
        if #available(iOS 12.0, *) {
            return SecCertificateCopyKey(certificate)
        } else if #available(iOS 10.3, *) {
            return SecCertificateCopyPublicKey(certificate)
        } else {
            // ???
            return nil
        }
    }

Upvotes: 3

Views: 1284

Answers (1)

Dmytro Rostopira
Dmytro Rostopira

Reputation: 11155

I've found solution

func publicKey(for certificate: SecCertificate) -> SecKey? {
    if #available(iOS 12.0, *) {
        return SecCertificateCopyKey(certificate)
    } else if #available(iOS 10.3, *) {
        return SecCertificateCopyPublicKey(certificate)
    } else {
        var possibleTrust: SecTrust?
        SecTrustCreateWithCertificates(certificate, SecPolicyCreateBasicX509(), &possibleTrust)
        guard let trust = possibleTrust else { return nil }
        var result: SecTrustResultType = .unspecified
        SecTrustEvaluate(trust, &result)
        return SecTrustCopyPublicKey(trust)
    }
}

Found here: https://github.com/daltoniam/Starscream/blob/a2ed45c0b2f996cb8c335c4f270ecc68c3bd4c0f/Sources/Starscream/SSLSecurity.swift#L214

Upvotes: 10

Related Questions