检查SSL证书的标识



我对这个领域很陌生。。。我最近遇到了一个问题。。。我想检查来自服务器的SSL证书是否来自正确的服务器(我们自己的服务器),或者是否来自任何恶意服务器。。。我怎样才能做到这一点?我使用的是NSURLConnection委托方法connection:canAuthenticateAgainstProtectionSpace:connection:didReceiveAuthenticationChallenge:

在连接委托中使用以下代码,并用实际主机替换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];
}

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

最新更新