如何验证Cocoa Touch中的网站证书? [英] How to verify a website certificate in Cocoa Touch?

查看:152
本文介绍了如何验证Cocoa Touch中的网站证书?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前使用NSURLConnection打开与网络服务器的https连接。一切工作,因为它应该,我能够检索我后面的页面内容。该证书由VeriSign颁发,我假设NSURLConnection在一定程度上验证证书的真实性有一些工作?如果我通过移动safari连接到同一网站,它将从证书中提取,并在导航栏中显示(网站的)组织。是否有可能在Cocoa Touch中提取这些相同的细节,因为我也想将它们呈现给用户?此外,验证服务器的主机名对该证书是否足够合理,足以假设网站是合法的?

I currently open an https connection to a web server using NSURLConnection. Everything works as it should and I am able to retrieve the page content I am after. The certificate is issued by VeriSign and I assume NSURLConnection does some work to verify the authenticity of the certificate to some extent? If I connected to the same website through mobile safari it would extract from the certificate, and display the Organization (of the website) in the navigation bar. Is it possibly to extract these same details in Cocoa Touch as I too would like to present them to the user? Also would verifying the server’s host name against that certificate be reasonable enough to assume website is legitimate?

推荐答案

NSURLConnection 会给您一个错误> NSURLErrorDomain ),如果您尝试连接到具有无效证书的服务器(例如它是自签名的,过期的,具有错误的主机等)。所以你实际上不需要自己做任何验证,因为它都是为你处理的。

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.

如果你真的想/需要在你的UI中显示SSL证书摘要,您需要从 NSURLConnection 中下拉一层并改用低级 CFNetwork API。一旦你有一个 CFReadStreamRef kCFStreamEventEndEnarded 状态,你应该能够做以下(假设你的流句柄(NSArray * $ readStream ):

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]; 
}

您需要解码 data 如果您想访问证书的各种属性,但 description 中包含的摘要可能足以满足您的需要。

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.

这篇关于如何验证Cocoa Touch中的网站证书?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆