Secure Sockets Layer Handling in iOS

Secure Sockets Layer  – SSL is the standard for encrypting and authenticating messages and identifying users and servers.

iOS mainly Supports SSL with built in commonly trusted root certificate authorities. It means, if certificate was released by a trusted CA installed on iOS and certificate was not revoked (Certificates can be revoked by OCSP – Online certificate Status Protocol ) , the connection is established very easily.

Problem Statement

If you want to buy something from Amazon server and you connect to a server that your DNS server says is and send them your order with your credit card details. There may be number of failures :-

  •  You might not connect to actual Amazon server which looks like Amazon, say
  •  Someone might be watching packets of your order so they can steal your card details.
  •  Someone change your order details in sender packets.
  •  There may be chance of “Man in the Middle Attack” ( Setting the connection’s proxy server to     his own server on the attacked device then attacker is able to monitor the communication via     the proxy server).


In iOS we have mainly two options to solve above problem statement : –

  1. Add server’s  certificate to the App’s sandbox keychain .
  2. Perform Validation Manually.

For both options you need to include a DER – encoded X.509 public certificate in your app OR you may choose to have it on the server and take it via URL scheme in iOS at run time. If your server’s certificate is part of a chain of existing root certificate authority, you should install the root certificate rather than your server’s certificate.

NSBundle *bundle = [NSBundle bundleForClass:[self class]];

NSData *iosTrustedCertDerData =

[NSData dataWithContentsOfFile:[bundle pathForResource:@"ios-trusted-cert"


SecCertificateRef certificate =


(CFDataRef) iosTrustedCertDerData);

1. Add server’s certificate to Keychain :-  We can add a certificate to our app’s keychain. This is mainly appropriate when we want iOS to trust certificate for every new socket which creates in application.

- (void) useKeychain: (SecCertificateRef) certificate {

OSStatus err =

SecItemAdd((CFDictionaryRef) [NSDictionary dictionaryWithObjectsAndKeys:

(id) kSecClassCertificate, kSecClass,

certificate, kSecValueRef,



if ((err == noErr) || // success!

(err == errSecDuplicateItem)) { // the cert was already added.  Success!

// create your socket normally.

// This is oversimplified.  Refer to the CFNetwork Guide for more details.

CFReadStreamRef readStream;

CFWriteStreamRef writeStream;











} else {

// handle the error.  There is probably something wrong with your cert.



2. Perform Validation Manually :- If our requirement is only to verify the certificate for the socket which we are creating and for no other sockets in our app. then we can verify our trust in the vert manually. firstly we disable its certificate chain validation in its SSL settings. After that in five simple steps we can evaluate this process.

  • Create a client SSL policy with the hostname of the server.
  • Take out actual certificate from a chain of certificates.
  • Create a trust object from it.
  • Set the anchor certificates, which are the certificates you trust.
  • By comparing anchor certificate and trust object ,we can evaluate the trust object and discover whether the server can be trusted or not.

Self Generated certificates in iOS 

It’s a universal problem in iOS that for Self generated certificates app will generates the result error message “Error Domain=NSURLErrorDomain Code=-1202 “The certificate for this server is invalid..”. To bypass the built-in SSL digital certificate authentication, you need to add the following NSURLConnection delegates.The delegates in short will accept the so called invalid certificate as genuine certificate.

-(BOOL)connection:(NSURLConnection *)connection              canAuthenticateAgainstProtectionSpace:(NSURLProtectionSpace *)protectionSpace {          return [protectionSpace.authenticationMethod      isEqualToString:NSURLAuthenticationMethodServerTrust];

-(void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge {

[challenge.sender useCredential:[NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust] forAuthenticationChallenge:challenge];

[challenge.sender continueWithoutCredentialForAuthenticationChallenge:challenge];


How can we create .DER file  – For creating .der you must have a working installation of the OpenSSL software in your mac. And use the openSSL command to convert between formats as follows :-                                                                                                                                           To convert a certificate from PEM to DER:                                                                                         x509 -in input.crt -inform PEM –out output.crt -outform DER

How much differ SSL handling in iOS from other mobile platforms – In iOS every application have it’s own sandbox keychain which have the chain of root certificates. So if we install a certificate in app then it will be specific only to this app rather than other mobile platform as android install certificate in OS, so it will be accessible to other than that app for which we are installing that certificate.

About Arpit kulshrestha

Arpit K Kulshrestha Graduated in Computer Science with HONORS Degree in 2012. He is on mission to develop or to be a part of great mobile application which can enhance user experience and able to explore the world. 6 + Years of Apple Mobile Application Development Experience with a strong focus on Building Enterprise, Social Networking Applications and working with Objective-C, Xcode, Storyboard & Instruments. Working knowledge of Core iOS frameworks and skilled in debugging. He has developed apps using SOAP, REST, JSON and XML based Web Services. He is interested to pursue a career in Mobile Applications Development field and he is certain that his skills and work experience prepared him well for such role.
 He has been a specialist in Multimedia & Networking based iOS applications in these years. Have a good in depth knowledge in Network Programming models like TCP/IP. Have done several rich multimedia (Videos & Images) processing & manipulating applications in the same. 
He is accustomed to successfully juggling multiple projects and have an excellent track record of forging strong relationships with client. He work equally well in team-oriented and self-directed environments and find the challenges of the start-up setting stimulating. Specialties:- Map kit , Core Location , UIKit , Core Data , SQLite , Google API's , Facebook API's ,Cocoa 2D, Core Motion, Event Kit.
This entry was posted in iOS Development and tagged , , , , , , . Bookmark the permalink.

2 Responses to Secure Sockets Layer Handling in iOS

  1. Adriana says:

    You post very interesting articles here. Your page deserves much more visitors.
    It can go viral if you give it initial boost, i know useful tool that
    can help you, just search in google: svetsern traffic tips

  2. Gday! I’m about to begin my own blog and was wondering if you know where the best place to buy a blog url is?
    I’m not even sure if that’s what its called? (I’m new to this) I’m referring to
    Exactly how do I go about acquiring one of these for the website I’m creating?


Leave a Reply to Orange County Cancel reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s