Reputation: 51
I run a Java server which accepts Socket or SSLSocket connections (different ports). On the client side I use in my iPhone app the GCDAsyncSocket to connect to the server. Which works fine if I use the insecure version (no SSL).
Now I try to connect using SSL. How to do this? I have absolutely no idea where to start. My questions:
1) What kind of certificates do I need? An Android app works fine with the same server using a .bks certificate
2) How do I import a certificate into my app? I want it to distribute later via AppStore. Do I have to place certificate files inside of some directory of the app?
3) Where do I load the certificates in the code? Is there a method something like - (void)loadCertificate { NSString *myCertificate = @"client.bks"; ... }
4) Which parameters do I have to set to activate the SSL in the GCDAsyncSocket, smth like BOOL useSSL = true; ...
5) Assuming the questions 1-4 are answered. What now? How to initiate a connection to the server? Which constructor with which parameters to use?
In case someone asks "why using SSLSocket and not...". Because the server is already there and it works this way with the Android app very well.
Thank you for your help!
Upvotes: 3
Views: 5155
Reputation: 959
This is an old question but I hope it will help someone else.
And finally there is a sample application in CocoaAsyncSocket folder called ConnectTest, you should check it first.
NSMutableDictionary *sslSettings = [[NSMutableDictionary alloc] init];
NSData *pkcs12data = [[NSData alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"client" ofType:@"bks"]];
CFDataRef inPKCS12Data = (CFDataRef)CFBridgingRetain(pkcs12data);
CFStringRef password = CFSTR("YOUR PASSWORD");
const void *keys[] = { kSecImportExportPassphrase };
const void *values[] = { password };
CFDictionaryRef options = CFDictionaryCreate(NULL, keys, values, 1, NULL, NULL);
CFArrayRef items = CFArrayCreate(NULL, 0, 0, NULL);
OSStatus securityError = SecPKCS12Import(inPKCS12Data, options, &items);
CFRelease(options);
CFRelease(password);
if(securityError == errSecSuccess)
NSLog(@"Success opening p12 certificate.");
CFDictionaryRef identityDict = CFArrayGetValueAtIndex(items, 0);
SecIdentityRef myIdent = (SecIdentityRef)CFDictionaryGetValue(identityDict,
kSecImportItemIdentity);
SecIdentityRef certArray[1] = { myIdent };
CFArrayRef myCerts = CFArrayCreate(NULL, (void *)certArray, 1, NULL);
[sslSettings setObject:(id)CFBridgingRelease(myCerts) forKey:(NSString *)kCFStreamSSLCertificates];
[sslSettings setObject:NSStreamSocketSecurityLevelNegotiatedSSL forKey:(NSString *)kCFStreamSSLLevel];
[sslSettings setObject:(id)kCFBooleanTrue forKey:(NSString *)kCFStreamSSLAllowsAnyRoot];
[sslSettings setObject:@"CONNECTION ADDRESS" forKey:(NSString *)kCFStreamSSLPeerName];
[sock startTLS:sslSettings];
Upvotes: 7