在canAuthenticateAgainstProtectionSpace中检查一个公钥

我被要求在canAuthenticateAgainstProtectionSpaceNSURLConnection的委托callback)中检查公钥,

这是我迄今为止:

 - (BOOL)connection:(NSURLConnection *)connection canAuthenticateAgainstProtectionSpace:(NSURLProtectionSpace *)protectionSpace { SecKeyRef publicKey = SecTrustCopyPublicKey([protectionSpace serverTrust]); NSLog(@"%@",SecTrustCopyPublicKey([protectionSpace serverTrust])); return YES; } 

我怎样才能比较公钥与已知的价值?

NSLog产生: <SecKeyRef: 0x687c000>这是不会有用的。

如果有人关心,解决方法是用包中保存的证书检查证书字节的字节。

 - (BOOL)connection:(NSURLConnection *)connection canAuthenticateAgainstProtectionSpace:(NSURLProtectionSpace *)protectionSpace { SecTrustRef trust = [protectionSpace serverTrust]; SecCertificateRef certificate = SecTrustGetCertificateAtIndex(trust, 0); NSData* ServerCertificateData = (NSData*) SecCertificateCopyData(certificate); // Check if the certificate returned from the server is identical to the saved certificate in // the main bundle BOOL areCertificatesEqual = ([ServerCertificateData isEqualToData:[MyClass getCertificate]]); [ServerCertificateData release]; if (!areCertificatesEqual) { NSLog(@"Bad Certificate, canceling request"); [connection cancel]; } // If the certificates are not equal we should not talk to the server; return areCertificatesEqual; } 

请注意,SecCertificateCopyData以“DER”forms返回证书,即“可分辨编码规则”。 所以你需要以这种forms在你的应用程序中join证书,而不是以pem或其他格式。 要使用openssl将证书转换为DER,请使用以下命令:openssl x509 -in server.crt -out server.der -outform DER