To improve the security of my application and protect the user from MITM attacks, I am trying to bind SSL with my self-signed certificate, following the contents of this post .
So, I use the following code to compare the certificate that I get from the server with the one that was added to the application.
- (void)connection:(NSURLConnection *)connection willSendRequestForAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge { SecTrustRef serverTrust = challenge.protectionSpace.serverTrust; SecCertificateRef certificate = SecTrustGetCertificateAtIndex(serverTrust, 0); NSData *remoteCertificateData = CFBridgingRelease(SecCertificateCopyData(certificate)); NSLog(@"Remote Certificate Data Length: %d",[remoteCertificateData length]); NSString *cerPath = [[NSBundle mainBundle] pathForResource:@"apache" ofType:@"crt"]; NSData *localCertData = [NSData dataWithContentsOfFile:cerPath]; NSLog(@"Local Certificate Data Length: %d",[localCertData length]); if ([remoteCertificateData isEqualToData:localCertData]) { NSURLCredential *credential = [NSURLCredential credentialForTrust:serverTrust]; [[challenge sender] useCredential:credential forAuthenticationChallenge:challenge]; } else { [[challenge sender] cancelAuthenticationChallenge:challenge]; } }
The only thing that is different from my code and one of the blog posts I linked is the name and extension (.cer to.crt) for the resource representing my certificate, and two added NSLogs that will be useful later to show what is the problem.
In fact, when this code is executed, I get this output:
2013-05-22 16:08:53.331 HTTPS Test[5379:c07] Remote Certificate Data Length: 880 2013-05-22 16:09:01.346 HTTPS Test[5379:c07] Local Certificate Data Length: 1249
Obviously, the comparison between local and remote certificates fails because the data length is different, and therefore it also fails.
Why is this happening and how can I solve this problem?
source share