将SSL证书添加到iOS中的https请求中?

时间:2013-02-08 06:34:13

标签: objective-c nsurlconnection ssl-certificate

对不起冗长的问题。到目前为止,我使用以下方法来信任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];

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

0 个答案:

没有答案