我的应用中存在很大问题。 我有java实现,但我需要通过使用Security.framework NSURLSession为iOS应用程序做同样的事情,我不知道如何。如果你帮助我会很棒。
爪哇:
// get our trusted CA from resources
CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
int caResId = context.getResources().getIdentifier("cert_ca", "raw", context.getPackageName());
X509Certificate cert = (X509Certificate)certificateFactory.generateCertificate(context.getResources().openRawResource(caResId));
String alias = cert.getSubjectX500Principal().getName();
// create empty trust store with only our CA
KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
trustStore.load(null);
trustStore.setCertificateEntry(alias, cert);
// create TrustManagers based on our trust store
TrustManagerFactory tmf = TrustManagerFactory.getInstance("X509");
tmf.init(trustStore);
TrustManager[] trustManagers = tmf.getTrustManagers();
// get our client certificate from resources
KeyStore keyStore = KeyStore.getInstance("PKCS12");
String pass = context.getResources().getString(R.string.pass);
int clientResId = context.getResources().getIdentifier("cert_client", "raw", context.getPackageName());
keyStore.load(context.getResources().openRawResource(clientResId), pass.toCharArray());
// create KeyManagers based on our key store
KeyManagerFactory kmf = KeyManagerFactory.getInstance("X509");
kmf.init(keyStore, pass.toCharArray());
KeyManager[] keyManagers = kmf.getKeyManagers();
// create SSL context
SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(keyManagers, trustManagers, null);
URL requestedUrl = new URL(url);
HttpsURLConnection urlConnection = (HttpsURLConnection)requestedUrl.openConnection();
urlConnection.setSSLSocketFactory(sslContext.getSocketFactory());
urlConnection.setRequestMethod("GET");
urlConnection.setConnectTimeout(1500); // ?
urlConnection.setReadTimeout(1500); // ?
int responseCode = urlConnection.getResponseCode();
String responseMessage = urlConnection.getResponseMessage();
urlConnection.disconnect();
通过以下代码解决它(对某人有帮助):
-(void)URLSession:(NSURLSession *)session didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition, NSURLCredential *))completionHandler{
if ([self shouldTrustProtectionSpace:challenge.protectionSpace]) {
[challenge.sender useCredential:[NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust] forAuthenticationChallenge:challenge];
} else {
NSString *path = [[NSBundle mainBundle] pathForResource:@"mobile_client (1)" ofType:@"pfx"];
NSData *p12data = [NSData dataWithContentsOfFile:path];
CFDataRef inP12data = (__bridge CFDataRef)p12data;
SecIdentityRef myIdentity;
SecTrustRef myTrust;
extractIdentityAndTrust(inP12data, &myIdentity, &myTrust);
SecCertificateRef myCertificate;
SecIdentityCopyCertificate(myIdentity, &myCertificate);
const void *certs[] = { myCertificate };
CFArrayRef certsArray = CFArrayCreate(NULL, certs, 1, NULL);
NSURLCredential *credential = [NSURLCredential credentialWithIdentity:myIdentity certificates:(__bridge NSArray*)certsArray persistence:NSURLCredentialPersistenceForSession];
[[challenge sender] useCredential:credential forAuthenticationChallenge:challenge];
completionHandler(NSURLSessionAuthChallengeUseCredential, credential);
}
}
OSStatus extractIdentityAndTrust(CFDataRef inP12data, SecIdentityRef *identity, SecTrustRef *trust)
{
OSStatus securityError = errSecSuccess;
CFStringRef password = CFSTR("123");
const void *keys[] = { kSecImportExportPassphrase };
const void *values[] = { password };
CFDictionaryRef options = CFDictionaryCreate(NULL, keys, values, 1, NULL, NULL);
CFArrayRef items = CFArrayCreate(NULL, 0, 0, NULL);
securityError = SecPKCS12Import(inP12data, options, &items);
if (securityError == 0) {
CFDictionaryRef myIdentityAndTrust = CFArrayGetValueAtIndex(items, 0);
const void *tempIdentity = NULL;
tempIdentity = CFDictionaryGetValue(myIdentityAndTrust, kSecImportItemIdentity);
*identity = (SecIdentityRef)tempIdentity;
const void *tempTrust = NULL;
tempTrust = CFDictionaryGetValue(myIdentityAndTrust, kSecImportItemTrust);
*trust = (SecTrustRef)tempTrust;
}
if (options) {
CFRelease(options);
}
return securityError;
}
- (BOOL)shouldTrustProtectionSpace:(NSURLProtectionSpace *)protectionSpace {
// Load up the bundled certificate.
NSString *certPath = [[NSBundle mainBundle] pathForResource:@"mobile_ca" ofType:@"der"];
NSData *certData = [[NSData alloc] initWithContentsOfFile:certPath];
SecCertificateRef cert = SecCertificateCreateWithData(NULL, (__bridge CFDataRef)(certData));
SecTrustRef serverTrust = protectionSpace.serverTrust;
CFArrayRef certArrayRef = CFArrayCreate(NULL, (void *)&cert, 1, NULL);
SecTrustSetAnchorCertificates(serverTrust, certArrayRef);
SecTrustResultType trustResult;
SecTrustEvaluate(serverTrust, &trustResult);
return trustResult == kSecTrustResultUnspecified;}