在ios5中阻止自签名的ssl证书

时间:2011-12-19 17:06:18

标签: ios ssl https ios5

我使用执行基本HTTP身份验证的代码,请参阅下文。这在IOS 5中运行良好。但现在我们将协议更改为https,我们使用了伪造的自签名证书。它也有效!这似乎不安全。有人知道你是否需要在这种方法中做些什么来阻止某些证书被接受?

- (void)connection:(NSURLConnection *)connection willSendRequestForAuthenticationChallenge:
       (NSURLAuthenticationChallenge *)challenge {

if ([challenge previousFailureCount] <= maxRetryCount ) {
    NSURLCredential *newCredential =
    [NSURLCredential
     credentialWithUser: userName
     password:password
     persistence:NSURLCredentialPersistenceForSession];

    [[challenge sender]
     useCredential:newCredential
     forAuthenticationChallenge:challenge];

   }
   else
   {
     NSLog(@"Failure count %d",[challenge previousFailureCount]);
   }
}

1 个答案:

答案 0 :(得分:1)

看起来我自己找到了答案。这会阻止无效的证书。 使用有效证书登录时仍需测试它是否有效。

- (void)connection:(NSURLConnection *)connection willSendRequestForAuthenticationChallenge:
       (NSURLAuthenticationChallenge *)challenge {

   if ([[[challenge protectionSpace] authenticationMethod] isEqualToString:@"NSURLAuthenticationMethodServerTrust"]) {
      [[challenge sender] performDefaultHandlingForAuthenticationChallenge:challenge];
   }
   else {
      if ([challenge previousFailureCount] <= maxRetryCount ) {
        NSURLCredential *newCredential =
        [NSURLCredential
         credentialWithUser: userName
         password:password
         persistence:NSURLCredentialPersistenceForSession];

        [[challenge sender]
         useCredential:newCredential
         forAuthenticationChallenge:challenge];

       }
       else
       {
         NSLog(@"Failure count %d",[challenge previousFailureCount]);
       }
   }
}