2012-02-07 59 views
2

我是這個領域的新手......我最近遇到了一個問題......我想檢查來自服務器的SSL證書是否來自正確的服務器(我們自己的服務器),或者它來自任何惡意服務器......我如何實現這一目標?我使用NSURLConnection代表方法connection:canAuthenticateAgainstProtectionSpace:connection:didReceiveAuthenticationChallenge:檢查SSL證書的身份

回答

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