Authentication Challenge with multiple in-house certificate authorities in iOS with Swift

Posted by on March 28, 2016

In one of my recent projects there was a requirement for a certificate and public key pinning. The API performs its operation from servers with certificates signed by an in-house certificate authority (self-signed too of course).

But there are mulitple CA, and clients servers can have different CA, so a hard-coding approach was not the best. So the idea is to validate the certificate to ensure that is was signed by any of the provided trusted CA.

In this example we are going to implement the protocol NSURLSessionDelegate specifically the function which handles server certificate validation

So lets see the code

public func URLSession(session: NSURLSession, didReceiveChallenge challenge: NSURLAuthenticationChallenge, completionHandler: (NSURLSessionAuthChallengeDisposition, NSURLCredential?) -> Void) {
        if challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust {

            let trust = challenge.protectionSpace.serverTrust
            let rootCaCerts = {
                (data) -> CFData? in
                return CFDataCreate(kCFAllocatorDefault, UnsafePointer(data.bytes), data.length)
                }.filter({$0 != nil}).map() { ref -> CFTypeRef in
                    return SecCertificateCreateWithData(kCFAllocatorDefault, ref!)!
            let certArrayRef : CFArrayRef = CFBridgingRetain(rootCaCerts as NSArray) as! CFArrayRef
            SecTrustSetAnchorCertificates(trust!, certArrayRef)
            SecTrustSetAnchorCertificatesOnly(trust!, true) // if "true" then also allows certificates signed with one of the system available root certificates.
            var trustResult: SecTrustResultType = 0
            SecTrustEvaluate(trust!, &trustResult)
            if (Int(trustResult) == kSecTrustResultUnspecified ||
                Int(trustResult) == kSecTrustResultProceed) {
                    //Trust the server certificate cause its signed with one of the allowed in-house CA
                    let credential = NSURLCredential(forTrust: challenge.protectionSpace.serverTrust!)
                    challenge.sender!.useCredential(credential, forAuthenticationChallenge: challenge)
                    completionHandler(NSURLSessionAuthChallengeDisposition.UseCredential, credential)
            } else {
                print("Invalid server certificate.") //this also happens with expired certificates
                completionHandler(NSURLSessionAuthChallengeDisposition.CancelAuthenticationChallenge, nil)

        } else {
            print("Unexpected authentication method");
            completionHandler(NSURLSessionAuthChallengeDisposition.CancelAuthenticationChallenge, nil)


So, trust or die xD

rootCACertificatesData its an NSData array with the CA certificates file content …. DER encoded certificates added to the project.

So insted of a list with files names, lets find all the “DER” files and load them into an array:

	let enumerator = NSFileManager.defaultManager().enumeratorAtPath(NSBundle.mainBundle().bundlePath)
    while let filePath = enumerator?.nextObject() as? String {
    	if NSURL(fileURLWithPath: filePath).pathExtension == "der" {
        	if let data = NSData(contentsOfURL:(NSBundle.mainBundle().bundleURL.URLByAppendingPathComponent(filePath))) {

New Job and a time for a career reinvention

Posted by on August 30, 2015

Hello everyone,

I know this is not usual post but i want to let you know something very exiting (for me):

I got a new job!

With more than 8 years working in the Hospitality Industry and in the same company as a Software Engineer i thought it was the time for a career change.

Time for new projects and new challenges.

I have been involved in numerous large-scale software releases providing me with a good hands-on experience creating and implementing software achitectures, also the ability to troubleshoot and solve problems in a timely and accurate manner.

As a software engineer, and more recently,

I have:

  • Build enterprise backend services/architecture for high load, high traffic, high availability processes for the Hospitality-Tourism industry, to help Individual and Chains of Properties(Hotels,Restaurants,SPAs,etc) to sell their inventory almost in “real time”, including their rates, enhancements,services, packages, promotions and deals through existing channels.

  • Build a distributed client-server architecture for an Auto-Trade, a Trading system on top of the Award Winning Platform Ninja Trader.

  • Build mobile software for the majors platforms: Android, IOs, Window Phone and HTML5 webapps.

I think that i’m well-seasoned about services/architecture for high load, high traffic, high availability processes (that’s my main area of interest).

So, i have a lot of confidence about my skills on this industry(Hospitality),

But after that long time, and with the job change desicion in mind, some “fears” appeared.

You might not call it fear. But let’s face it. That’s what stops us from making the move out of a “miserable” job, or starting over in a new field no matter how right the time is to do just that.

It’s paralyzing

Some of those fears are:

  • Fear of the unknown
  • Fear of failure
  • Fear of not complying with other people’s expectations
  • Fear of making a bad career change choice
  • Fear of economic stability (having a family to maintain puts more preasure ¬¬)

To be honest.

Right now, i’m a full time Java Enterprise Application Developer.

My job, almost all consist in developing backend services, and

I’m switching to a Mobile career.

Yes, i will continue as a Software Engineer, but on the Mobile side mainly, developing apps and mobile services for Android, iOS, Windows Phone and others.

Rigth time

I don’t know about the future, but i think is and they got me in the rigth time.

Yes, i’m switching, i’m giving my career and oportunity.

I’m really excited about this new job i think is a great opportunity.

I am going into a new adventure with the guys at

They convinced me with : “Come with us and you will be happy”.

The guys at Fewlaps are Master Craftsmen in the development of mobile applications.

I am very happy to become a part of the company and i will work for a great development with my complete knowledge and skills.

Some shit for your javascript: The Module Pattern

Posted by on July 18, 2015

The Module Pattern was originally defined as a way to have software modules in a programming language with incomplete direct support for the concept.

This pattern in JavaScript is used to mimic the classes concept and focuses on public and private encapsulation in such a way that we’re able to include both public/private methods and variables inside a single object.

The Module Pattern is, the most commonly used design pattern and widely accepted, you can find it in a number of large projects such as jQuery, Dojo, ExtJS, AngularJS and YUI.

To implement this pattern we will use another one know as the Immediately-invoked function expression

What? Well, this one:

(function () {
  // the code here is executed once in its own scope

It declares a function, which then calls itself immediately.

So, lets watch a sample of the Module pattern:

var MyFancyModule = (function () {

  var privateMethodOne 		= function () {};
  var privateMethodTwo 		= function () {};
  var privateMethodThree 	= function () {};
  return {
    publicMethodOne: function () {
      // You can call `privateMethodX()` you know...
    publicMethodtwo: function () {

    publicMethodThree: function () {



Now you can get an idea on how to organize your shitty code.

The Python Tutorial 2.7 - unofficial book now available

Posted by on July 7, 2015

Python is a programming language that lets you work more quickly and integrate your systems more effectively. You can learn to use Python and see almost immediate gains in productivity and lower maintenance costs.

The Python Tutorial 2.7 - unofficial is based on a work available at

This book is just a compilation and the purpose is to provide the Python documentation in multiple formats, because the web is not the only place for reading xD

This release includes three convenient formats:

  • PDF (for Mac or PC)
  • EPUB (for iPad, iPhone, and other ebook readers)
  • MOBI (for Kindle)

Now go and get your copy for free at

Stop knocking a nail into wood using a saw and use the right language for the job

Posted by on December 17, 2014

Choosing a programming language uniquely suited to solving a particular problem can lead to productivity gains and better quality software.

We are always chasing those improvements, because, when the language fits the problem, programming becomes more direct and code becomes simpler and easier to maintain. A pleasure, because there is not an unnecessary friction.

But, the major issue appears when you try to link solutions from different languages.

To solve this, we have Apache Thrift

Apache Thrift solves problems associated with building applications which collaborate across language boundaries. In addition to normalizing data for cross language communications, Apache Thrift also provides a complete remoting framework making it trivial to build cross language networked services.

So, what exactly is Apache Thrift?

Apache Thrift is an open source cross-language serialization and RPC framework. With support for over 15 programming languages, Apache Thrift can play an important role in a range of distributed application development environments. As a serialization platform Apache Thrift enables efficient cross language storage and retrieval of a wide range of data structures. As an RPC framework, Apache Thrift enables rapid development of complete polyglot services in a few lines of code.

Polyglot services? Yes!

You can build services that work efficiently and seamlessly between C++, Java, Python, PHP, Ruby, Erlang, Perl, Haskell, C#, Cocoa, JavaScript, Node.js, Smalltalk, OCaml and Delphi and other languages.

Apache Thrift allows you to define data types and service interfaces in a simple definition file. Taking that file as input, the compiler generates code to be used to easily build RPC clients and servers that communicate seamlessly across programming languages. Instead of writing a load of boilerplate code to serialize and transport your objects and invoke remote methods, you can get right down to business. Thrift definition example file:

service Calculator extends shared.SharedService {

   void ping(),

   i32 add(1:i32 num1, 2:i32 num2),

   i32 calculate(1:i32 logid, 2:Work w) throws (1:InvalidOperation ouch),

   oneway void zip()


Having the Thrift definition file you can now generate the client and server side.

So, is time for you to go for a deep exploration on how Apache Thrift works so you can choose your hammer.