从技术上讲,当我认识的某个人需要在Swift中实现时,他使用了以下Objective-C实现来获取NSURLCredential对象到连接;基于包含在PKCS12密钥库中的私钥和X509证书对。
抱歉,我没有访问包含Swift解决方案的源代码。我知道的只是NSURLCredential被返回给Swift并直接在那里的http URL连接中使用。虽然它类似于这个,但不完全相同。
我不是iOS开发人员,所以无法帮助您完成“桥接到Swift”的部分。
- (void)getMessageWithURL:(NSString *)url {
NSURL *URL = [NSURL URLWithString:url];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:URL];
[request setHTTPMethod:@"GET"];
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
[connection self];
}
- (void)postMessageWithURL:(NSString *)url withContent:(NSString *)content {
NSData *postData = [content dataUsingEncoding:NSUTF8StringEncoding];
NSString *postLength = [NSString stringWithFormat:@"%d", [postData length]];
NSURL *myURL = [NSURL URLWithString:url];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:myURL cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:60];
[request setHTTPMethod:@"POST"];
[request setValue:postLength forHTTPHeaderField:@"Content-Length"];
[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[request setHTTPBody:postData];
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
[connection self];
}
- (BOOL)connection:(NSURLConnection *)connection canAuthenticateAgainstProtectionSpace:(NSURLProtectionSpace *)protectionSpace {
return [protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust];
}
- (void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge {
NSLog(@"didReceiveAuthenticationChallenge");
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
responseData = [[NSMutableData alloc] init];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
[responseData appendData:data];
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
NSLog(@"Unable to fetch data");
NSLog(@"%@", error);
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
NSLog(@"Succeeded! Received %lu bytes of data", (unsigned long)[responseData
length]);
NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
NSLog(@"%@", responseString);
[bridge callHandler:handlerName data:responseString];
}
- (void)connection:(NSURLConnection *)connection willSendRequestForAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = paths[0];
NSData *p12data = [CertificateManager getP12Data];
if (!p12data) {
return;
NSAssert(p12data, @"Couldn't load p12 file...");
}
CFStringRef password = CFSTR("password");
const void *keys[] = {kSecImportExportPassphrase};
const void *values[] = {password};
CFDictionaryRef optionsDictionary = CFDictionaryCreate(NULL, keys, values, 1, NULL, NULL);
CFArrayRef p12Items;
OSStatus result = SecPKCS12Import((__bridge CFDataRef) p12data, optionsDictionary, &p12Items);
if (result == noErr) {
CFDictionaryRef identityDict = CFArrayGetValueAtIndex(p12Items, 0);
SecIdentityRef identityApp = (SecIdentityRef) CFDictionaryGetValue(identityDict, kSecImportItemIdentity);
SecCertificateRef certRef;
SecIdentityCopyCertificate(identityApp, &certRef);
SecCertificateRef certArray[1] = {certRef};
CFArrayRef myCerts = CFArrayCreate(NULL, (void *) certArray, 1, NULL);
CFRelease(certRef);
NSURLCredential *credential = [NSURLCredential credentialWithIdentity:identityApp certificates:nil persistence:NSURLCredentialPersistenceNone];
CFRelease(myCerts);
[[challenge sender] useCredential:credential forAuthenticationChallenge:challenge];
}
else {
NSLog(@"Invalid certificate or password");
NSError *error = [NSError errorWithDomain:NSOSStatusErrorDomain code:result userInfo:nil];
return;
}
}
编辑:哈哈,很有趣,当奖励还在时你们没有投票,现在却投了两票。*咕哝*
无论如何,要使用上述内容,您只需要从Swift中访问它。
func connection(connection: NSURLConnection, willSendRequestForAuthenticationChallenge challenge: NSURLAuthenticationChallenge) {
if let p12Data = UserManager.currentP12,
let credential = CertificateManager.getCredentialsForP12(p12Data) as? NSURLCredential {
challenge.sender.useCredential(credential, forAuthenticationChallenge: challenge)
} else {
UIApplication.sharedApplication().networkActivityIndicatorVisible = false
}
}
使用这个的方法是这样的。
+ (id)getCredentialsForP12:(NSData *)p12 {
NSData* p12data = p12;
const void *keys[] = {kSecImportExportPassphrase};
const void *values[] = {CFSTR("thePassword")};
CFDictionaryRef optionsDictionary = CFDictionaryCreate(NULL, keys, values, 1, NULL, NULL);
CFArrayRef p12Items;
OSStatus result = SecPKCS12Import((__bridge CFDataRef) p12data, optionsDictionary, &p12Items);
if (result == noErr) {
CFDictionaryRef identityDict = CFArrayGetValueAtIndex(p12Items, 0);
SecIdentityRef identityApp = (SecIdentityRef) CFDictionaryGetValue(identityDict, kSecImportItemIdentity);
SecCertificateRef certRef;
SecIdentityCopyCertificate(identityApp, &certRef);
SecCertificateRef certArray[1] = {certRef};
CFArrayRef myCerts = CFArrayCreate(NULL, (void *) certArray, 1, NULL);
CFRelease(certRef);
NSURLCredential *credential = [NSURLCredential credentialWithIdentity:identityApp certificates:nil persistence:NSURLCredentialPersistenceNone];
CFRelease(myCerts);
return credential;
}
else {
NSLog(@"Invalid certificate or password");
UIAlertView* av = [[UIAlertView alloc] initWithTitle:@"Error" message:@"Invalid cert or pass" delegate:nil cancelButtonTitle:@"ok" otherButtonTitles: nil];
[av show];
NSError *error = [NSError errorWithDomain:NSOSStatusErrorDomain code:result userInfo:nil];
return nil;
}
编辑:上面的内容有一个Swift版本,但它太混乱了,我们宁愿不使用它。
var p12items : Unmanaged<CFArrayRef>?
let index: CFIndex = 1
let password: CFString = "password"
let key = kSecImportExportPassphrase.takeRetainedValue() as String
var values = [unsafeAddressOf(password)]
var keys = [unsafeAddressOf(key)]
var keyCallbacks = kCFTypeDictionaryKeyCallBacks
var valueCallbacks = kCFTypeDictionaryValueCallBacks
let length: CFIndex = p12Data.length
let p12CfData: CFData = CFDataCreate(kCFAllocatorDefault, UnsafePointer<UInt8>(p12Data.bytes), length)
let options = CFDictionaryCreate(kCFAllocatorDefault, &keys, &values, index, &keyCallbacks, &valueCallbacks)
let result = SecPKCS12Import(p12CfData, options, &p12items)
if result == noErr {
let idIndex: CFIndex = 0
var items = p12items?.takeRetainedValue()
var identityDict = CFArrayGetValueAtIndex(items!, idIndex)
var key = kSecImportItemIdentity.takeRetainedValue() as String
var keyAddress = unsafeAddressOf(key)
var identityApp: SecIdentityRef = CFDictionaryGetValue(identityDict, keyAddress)
var certRef : Unmanaged<SecCertificateRef>?
SecIdentityCopyCertificate(identityApp, &certRef)
var cert: SecCertificateRef = certRef!.takeRetainedValue()
var certArray = [unsafeAddressOf(cert)]
var arrayCallback = kCFTypeArrayCallBacks
var myCerts: CFArrayRef = CFArrayCreate(kCFAllocatorDefault, &certArray, index, &arrayCallback);
let credential: NSURLCredential = NSURLCredential(identity: identityApp, certificates: [AnyObject](), persistence: NSURLCredentialPersistence.None)