I have a PEM file of the ISRG Root X1 certificate which I downloaded from https://letsencrypt.org/certificates/
and I’m trying to implement certificate pinning in my iOS app. I’m specifically interested in public key pinning and I’m targeting iOS 12 and above.
I have two main questions:
-
How can I generate a SHA256 hex string from the PEM file?
-
Once I have the SHA256 hex string, how can I implement root certificate public key pinning in Swift using URLSession, without relying on any external libraries?
I would greatly appreciate any assistance or resources that could shed light on this matter. Thank you in advance!
— Edited
According to what I found on StackOverflow and other sources, the SHA-256 hex string I generated using OpenSSL differs from the one I obtained in the code during TLS connections.
Command used:
openssl rsa -pubin -inform PEM -outform DER -in public_key.pem | openssl enc -base64
Question – why it is different is it expected?
2
Answers
I usually have a slightly different approach that i will share to see if it helps.
In a terminal i simply run this command:
Since it seems you already have the PEM file, you can run this command:
You have to include the certificate file with extension CER in your project.
Implementation of certificate pinning
Initialise your URLSession with delegate
Then you simply implement this function:
This will allow you to have multiple certificates installed, it can be usefully when one is about to expire but you already have the newer one available, so when one expires, the other one will still be validated.
For you first point i.e.
How to generate SHA256 hex string from PEM file
Method 1:
Get public key via terminal command-
Step 1: If you have the pem file with you please use the below openSSL command to get the public key.
Here, please do make sure your PEM file is in correct format which contains the private key.
Step 2: Now, use below command to extract/read the public key from outputPublicKey.pem file
Method 2:
Direct method
Step 1: Open Qualys SSL Labs
Step 2: Enter your domain hostname from which you want to extract the public key e.g. https://www.google.com/ and press submit button
Step 3: In the next screen you will get your SHA256 public key, see reference image below
===================================================================
For you second point i.e.
Implement root certificate public key pinning?
Now, if you are using url session then use URL session delegate method i.e.
// User defined variables
// MARK: URL session delegate:
Find below the logic which I basically used:
Helper function to convert server certificate to SHA256
If you are using Alamofire, then pass the domain path in the evaluators data in your alamofire session like below
Now use this session while calling your alamofire network request.
Hope, I will be able to help you here.
Thanks and regards.