4

In my iPhone app I would like to connect with my SSL server socket (in Java). I have my own certificate. I'm trying to add it into my app, but I have no idea how to do it.

Without SSL, the communication works:

@interface ViewController ()

@end

@implementation ViewController
@synthesize openResponse;
@synthesize general; 
@synthesize response = _response;

- (void)viewDidLoad
{
 [super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}

- (void)viewDidUnload
{ 
[self setOpenResponse:nil];
[self setGeneral:nil];
[super viewDidUnload];
// Release any retained subviews of the main view.
}

 - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
}

- (IBAction)open:(id)sender {
    [self initNetworkCommunication];


Byte sendBuffer[4];
sendBuffer[0]=0x6b;
sendBuffer[1]=0x6f;
sendBuffer[2]=0x6c;
sendBuffer[3]=0x61;

[outputStream write:sendBuffer maxLength:4];
 }


- (void)initNetworkCommunication{

CFReadStreamRef readStream;
CFWriteStreamRef writeStream;
CFStreamCreatePairWithSocketToHost(NULL, (CFStringRef)@"mypage.com", 4444, &readStream, &writeStream);
inputStream = (__bridge NSInputStream *)readStream;
outputStream = (__bridge NSOutputStream *) writeStream;
[inputStream setDelegate:self];
[outputStream setDelegate:self];
[inputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
[outputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
[inputStream open];
[outputStream open];

}

- (void)stream:(NSStream *)theStream handleEvent:(NSStreamEvent)streamEvent
{
 switch (streamEvent) {

    case NSStreamEventOpenCompleted: {
        NSLog(@"Stream opened");

        break;
    }

    case NSStreamEventHasBytesAvailable: {
        NSLog(@"Data!");

        if (theStream == inputStream) {

            uint8_t buffer[1024];
            int len;

            while ([inputStream hasBytesAvailable]) {
                len = [inputStream read:buffer maxLength:sizeof(buffer)];
                if (len > 0) {

                    NSString *output = [[NSString alloc] initWithBytes:buffer length:len encoding:NSASCIIStringEncoding];

                    if (nil != output) {
                        NSLog(@"server said: %@", output);
                        self.response = output;
                        NSString *responseData =[[NSString alloc] initWithFormat:@"El servidor dice: %@",self.response];
                        self.openResponse.text = responseData;
                    }
                }
            }
        }
        break;

        break;
    }


    case NSStreamEventErrorOccurred: {
        NSLog(@"Can not connect to the host!");

        break;
    }
    case NSStreamEventEndEncountered: {
        NSLog(@"End encountered");

        break;
    }
    default:
        NSLog(@"Unknown event");
        break;
}
}

@end

How can I add my cert to this code?

Erwin Brandstetter
  • 605,456
  • 145
  • 1,078
  • 1,228
user1256477
  • 10,763
  • 7
  • 38
  • 62
  • Might want to look at this. http://stackoverflow.com/questions/933331/how-to-use-nsurlconnection-to-connect-with-ssl-for-an-untrusted-cert – John Riselvato May 21 '12 at 15:28

2 Answers2

4

I am solving the same problem as this issue too. probably, this URL and my code are help you. but my code is not sure.

  1. URL : NSStream SSL on used socket

  2. code

NSData *pkcs12data = [[NSData alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"EGNF9784" ofType:@"pfx"]];
CFDataRef inPKCS12Data = (CFDataRef)pkcs12data;

CFStringRef password = CFSTR("enblinkPass");
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);        
[pkcs12data release];

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);

NSMutableDictionary *settings = [NSMutableDictionary dictionaryWithCapacity:3];

[settings setObject:[NSNumber numberWithBool:YES] forKey:(NSString *)kCFStreamSSLAllowsExpiredRoots];

[settings setObject:[NSNumber numberWithBool:YES] forKey:(NSString *)kCFStreamSSLAllowsExpiredCertificates];

[settings setObject:[NSNumber numberWithBool:YES] forKey:(NSString *)kCFStreamSSLAllowsAnyRoot];

[settings setObject:[NSNumber numberWithBool:NO] forKey:(NSString *)kCFStreamSSLValidatesCertificateChain];

[settings setObject:[NSString stringWithFormat:@"%@:%hu",host,port] forKey:(NSString *)kCFStreamSSLPeerName];

[settings setObject:(NSString *)kCFStreamSocketSecurityLevelNegotiatedSSL forKey:(NSString*)kCFStreamSSLLevel];

[settings setObject:(NSString *)kCFStreamSocketSecurityLevelNegotiatedSSL forKey:(NSString*)kCFStreamPropertySocketSecurityLevel];

[settings setObject:(id)myCerts forKey:(NSString *)kCFStreamSSLCertificates];

[settings setObject:[NSNumber numberWithBool:YES] forKey:(NSString *)kCFStreamSSLIsServer];
Community
  • 1
  • 1
0

Yes it might make sense to look at this post if you are talking HTTP (as appears to be indicated by your host name, "my page.com"): How to use NSURLConnection to connect with SSL for an untrusted cert? Using the NSURLClass would dramatically simplify your overall design.

Community
  • 1
  • 1
Cliff
  • 10,586
  • 7
  • 61
  • 102
  • no, it's not HTTP, it just a TCP socket, as you can see the port is 4444 instead of 80 – user1256477 May 21 '12 at 15:49
  • The port is independent of the protocol. I was really inferring that you probably could use HTTP unless your specific requirements mandated otherwise. Rolling your own protocol can be tricky. – Cliff May 21 '12 at 17:19