2

对不起,冗长的问题。到目前为止,我使用以下方法来信任 HTTPS 连接的证书,它工作正常。

- (BOOL)connection:(NSURLConnection *)connection canAuthenticateAgainstProtectionSpace:(NSURLProtectionSpace *)protectionSpace {
  return [protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust];
}


- (void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge {
  if ([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust])
    if ([trustedHosts containsObject:challenge.protectionSpace.host])
      [challenge.sender useCredential:[NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust] forAuthenticationChallenge:challenge];

  [challenge.sender continueWithoutCredentialForAuthenticationChallenge:challenge];
}

但是对服务器的每个请求至少需要 10 到 15 秒才能调用这些委托方法。客户将其作为缺陷提出,因此我尝试将证书 .der 保留在捆绑包中,并尝试随请求发送证书、信任、策略对象。我使用下面的代码从 .der 检索证书。

NSString *thePath = [[NSBundle mainBundle]
                     pathForResource:@"Mycertificate" ofType:@"der"];
NSData *certData = [[NSData alloc]
                    initWithContentsOfFile:thePath];

CFDataRef myCertData = (__bridge CFDataRef)certData;                 // 1

SecCertificateRef myCert;
myCert = SecCertificateCreateWithData(NULL, myCertData);    // 2
SecPolicyRef myPolicy = SecPolicyCreateBasicX509();         // 3

SecCertificateRef certArray[1] = { myCert };
CFArrayRef myCerts = CFArrayCreate(
                                   NULL, (void *)certArray,
                                   1, NULL);
SecTrustRef myTrust;

OSStatus status = SecTrustCreateWithCertificates(
                                                 myCerts,
                                                 myPolicy,
                                                 &myTrust);  // 4

SecTrustResultType trustResult;
if (status == noErr) {
    status = SecTrustEvaluate(myTrust, &trustResult);       // 5
    [request setClientCertificates:[NSArray arrayWithObject:(id)CFBridgingRelease(myCert)]];
}
//...
NSLog(@"myTrust  %@", myTrust);
// 6
if (trustResult == kSecTrustResultRecoverableTrustFailure) {
    // ...;
}
// ...
if (myPolicy)
    CFRelease(myPolicy);

myCerts 包含我的所有证书对象,myTrust 包含我的受信任对象,myPolicy 包含我的 Policy 对象。我正在向服务器发送如下请求

NSURL *url = [NSURL URLWithString:@"https://....."];

NSMutableURLRequest *request = [self setURLRequestWithData:requestParam andURL:url];

_theConnection = [[NSURLConnection alloc] initWithRequest:request delegate:self];

我不知道如何使用此请求设置证书、信任和策略对象。请在这个问题上帮助我。如何以请求应始终信任服务器证书的方式向服务器发送请求。?? 提前致谢。

4

0 回答 0