我对这个领域很新...我最近遇到了一个问题...我想检查来自服务器的SSL证书是否来自正确的服务器(我们自己的服务器)或者它来自任何恶意服务器......我怎样才能做到这一点?我正在使用NSURLConnection
委托方法connection:canAuthenticateAgainstProtectionSpace:
和connection:didReceiveAuthenticationChallenge:
。
答案 0 :(得分:3)
在连接委托中使用以下代码,并将YOUR HOST
字符串替换为您的真实主机。
- (void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge
{
if ([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust])
{
if ([@"YOUR HOST" isEqualToString:challenge.protectionSpace.host])
{
[challenge.sender useCredential:[NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust]
forAuthenticationChallenge:challenge];
}
}
[challenge.sender continueWithoutCredentialForAuthenticationChallenge:challenge];
}
答案 1 :(得分:0)
对于iOS5及更高版本,并且失败:
- (void)connection:(NSURLConnection *)connection willSendRequestForAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge
{
if ([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust])
{
if ([@"xip.comcast.net" isEqualToString:challenge.protectionSpace.host] ||
[@"xip-staging.cim.comcast.net" isEqualToString:challenge.protectionSpace.host])
{
[challenge.sender useCredential:[NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust]
forAuthenticationChallenge:challenge];
}
else
{
[challenge.sender cancelAuthenticationChallenge:challenge];
}
}
[challenge.sender continueWithoutCredentialForAuthenticationChallenge:challenge];
}