title: SSL Socket connection iOS
body: <p>I am trying to setup a secure connection to a java run SSLServerSocket.</p>
  
  <p>I have created my own root CA, and have signed the certificate that the Java SSLServerSocket using this certificate.</p>
  
  <p>I want to add this root certificate to my app so that any certificate signed by the root certificate will work.</p>
  
  <p>So far I have the secure connection working fine by setting the read and write stream properties to this:</p>
  
  <pre><code>NSDictionary *settings = [[NSDictionary alloc] initWithObjectsAndKeys:
  (id)kCFStreamSocketSecurityLevelNegotiatedSSL, kCFStreamPropertySocketSecurityLevel,
  [NSNumber numberWithBool:YES], kCFStreamSSLAllowsExpiredCertificates,
  [NSNumber numberWithBool:YES], kCFStreamSSLAllowsExpiredRoots,
  [NSNumber numberWithBool:NO], kCFStreamSSLValidatesCertificateChain,nil];
  </code></pre>
  
  <p>I add the certificate to the keychain like this:</p>
  
  <pre><code>-(void)addRootCert{
  NSString* rootCertPath = [[NSBundle mainBundle] pathForResource:@"rootCA" ofType:@"der"];
  NSData* rootCertData = [NSData dataWithContentsOfFile:rootCertPath];
  
  OSStatus err = noErr;
  SecCertificateRef rootCert = SecCertificateCreateWithData(kCFAllocatorDefault, (__bridge CFDataRef)rootCertData);
  NSDictionary* dict = [NSDictionary dictionaryWithObjectsAndKeys:(__bridge_transfer id)kSecClassCertificate, kSecClass, rootCert, kSecValueRef, nil];
  
  err = SecItemAdd((__bridge CFDictionaryRef) dict, NULL);
  if (err == noErr) {
      NSLog(@"Sucessfully added root certificate");
  }else if (err == errSecDuplicateItem){
      NSLog(@"Root certificate already exists");
  }else{
      NSLog(@"Root certificate add failed");
  }
  }
  </code></pre>
  
  <p>This is fine but I want to validate the certificate chain, so that my app only accepts certificates signed by my CA (or the default trusted ones)</p>
  
  <p>How can I do this?</p>
  
  <p>If I set <code>kCFStreamSSLValidatesCertificateChain</code> to yes, I get the error: <code>CFNetwork SSLHandshake failed (-9807)</code> but if it's no, it doesn't matter who signed the server certificate, it will connect regardless (I assume that's right?)</p>
  
  <p>Thanks!</p>