If you need to know how to extract this information from a certificate in your iOS code, here you have one way to do this.
First add the security infrastructure.
#import <Security/Security.h>
Add openssl libraries. You can download them from https://github.com/st3fan/ios-openssl
#import <openssl/x509.h>
The NSURLConnectionDelegate protocol allows you to decide whether the connection should respond to the security space. In short, this is when you can see the certificate coming from the server and decide to allow the connection to continue or to cancel. Here you want to compare the public key of the certificates with the one you bound. Now the question is, how do you get such a public key? Take a look at the following code:
First get a certificate in X509 format (for this you need ssl libraries)
const unsigned char *certificateDataBytes = (const unsigned char *)[serverCertificateData bytes]; X509 *certificateX509 = d2i_X509(NULL, &certificateDataBytes, [serverCertificateData length]);
Now we will prepare for reading the public key data
ASN1_BIT_STRING *pubKey2 = X509_get0_pubkey_bitstr(certificateX509); NSString *publicKeyString = [[NSString alloc] init];
At this point, you can iterate over the string pubKey2 and extract the bytes in HEX format into a string with the following loop
for (int i = 0; i < pubKey2->length; i++) { NSString *aString = [NSString stringWithFormat:@"%02x", pubKey2->data[i]]; publicKeyString = [publicKeyString stringByAppendingString:aString]; }
Print the public key to see it
NSLog(@"%@", publicKeyString);
Full code
- (BOOL)connection:(NSURLConnection *)connection canAuthenticateAgainstProtectionSpace:(NSURLProtectionSpace *)protectionSpace { const unsigned char *certificateDataBytes = (const unsigned char *)[serverCertificateData bytes]; X509 *certificateX509 = d2i_X509(NULL, &certificateDataBytes, [serverCertificateData length]); ASN1_BIT_STRING *pubKey2 = X509_get0_pubkey_bitstr(certificateX509); NSString *publicKeyString = [[NSString alloc] init]; for (int i = 0; i < pubKey2->length; i++) { NSString *aString = [NSString stringWithFormat:@"%02x", pubKey2->data[i]]; publicKeyString = [publicKeyString stringByAppendingString:aString]; } if ([publicKeyString isEqual:myPinnedPublicKeyString]){ NSLog(@"YES THEY ARE EQUAL, PROCEED"); return YES; }else{ NSLog(@"Security Breach"); [connection cancel]; return NO; } }