How to verify a website certificate in Cocoa Touch?

天大地大妈咪最大 提交于 2019-12-04 06:43:04

NSURLConnection will give you an error (NSURLErrorDomain) if you attempt to connect to a server with an invalid certificate (e.g. it's self signed, out of date, has the wrong host etc.). So you don't actually need to do any verification yourself, because it's all handled for you.

If you really want/need to display an SSL certificate summary in your UI, you'll need to drop down a layer from NSURLConnection and use low-level CFNetwork API instead. Once you have a CFReadStreamRef that's in the kCFStreamEventEndEncountered state, you should be able to do the following (assuming your stream handle is called readStream):

NSArray* certificates = [(NSArray*)CFReadStreamCopyProperty(readStream, kCFStreamPropertySSLPeerCertificates) autorelease]; 
if ([certificates count] > 0) { 
  SecCertificateRef certificate = (SecCertificateRef)[certificates objectAtIndex:0]; 
  NSString* description = [(NSString*)SecCertificateCopySubjectSummary(certificate) autorelease]; 
  NSData* data = [(NSData*)SecCertificateCopyData(certificate) autorelease]; 
}

You'll need to decode the information held in data if you want to access the various properties of the certificate, but the summary held in description might be enough for your purposes.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!