简体   繁体   中英

ios: Public Key SSL Pinning Returns Nil

I have saved the public key of my SSL certificate into my xcode project as .crt, and am trying to use Alamofire to connect to my website through https. The part that keeps failing is using SecCertificateCreateWithData, that returns nil as show below:

 func configureAlamoFireSSLPinningWithCertificateData() {

    let cert = "nameOfCert"
    let pathToCert = NSBundle.mainBundle().pathForResource(cert, ofType: "crt")
    let certificateData:NSData = NSData(contentsOfFile: pathToCert!)!
    let localCertificate = SecCertificateCreateWithData(nil, certificateData)!  //RETURNS NIL

    self.serverTrustPolicy = ServerTrustPolicy.PinCertificates(
        certificates: [localCertificate],
        // Choose to validate the complete certificate chain, not only the certificate itself
        validateCertificateChain: true,
        // Check that the certificate mathches the host who provided it
        validateHost: true
    )

    self.serverTrustPolicies = [
        "nameOfTrustedServer": self.serverTrustPolicy!
    ]
    self.afManager = Manager(
        configuration: NSURLSessionConfiguration.defaultSessionConfiguration(),
        serverTrustPolicyManager: ServerTrustPolicyManager(policies: serverTrustPolicies)
    )
}

I've looked at the certificate in the project and everything seems to be fine, and I can also print certificateData and get a correctly formatted result.

Is the problem that I only have the public key saved and not the entire certificate? I would like to avoid doing that for obvious security reasons, but I cannot seem to figure out why It returns nil when trying to create the Sec Certificate.

Thanks in advance!

Finally figured it out, the issue was in my certificate even though it appeared to be correct. I fixed it by re-saving it as a .cer through openssl and this fixed it. Weirdly when I tried to re-save it as .cer in sublime or notepad it did not work even though Xcode displayed them identically, until I printed the NSData from each and it showed them to be different.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM