Xamarin ios, SSL pinning : Public key hash does not match

Amol Sarmalkar 1 Reputation point
2021-01-29T15:53:12.833+00:00

Hi,

We are trying to implement SSL pinning in our Xamarin.ios app.

POC : As a proof of concept, we calculated public key hash of https://www.google.co.uk . We used openssl s_client -servername www.google.co.uk -connect www.google.co.uk:443 | openssl x509 -pubkey -noout | openssl pkey -pubin -outform der | openssl dgst -sha256 -binary | openssl enc -base64 command in terminal to get hash of public key (SHA256) .
We pinned this hash of public key for https://www.google.co.uk in our app inside our app and tried comparing it at runtime.

Then using NSURLSession we tried fetching data of https://www.google.co.uk .
Inside DidReceiveChallenge we calculate hash of public key using following code :
SecKey key = challenge.ProtectionSpace.ServerSecTrust.GetKey();
NSError error = new NSError();
NSData keyData = key.GetExternalRepresentation(out error);
string str = sha256(keyData);

That hash calculating function body is as below :

public string sha256(NSData data)
{
using (SHA256 mySHA256 = SHA256.Create())
{
byte[] bytes = data.ToArray();
byte[] hashvalue = mySHA256.ComputeHash(bytes);
NSData d = NSData.FromArray(hashvalue);
return d.GetBase64EncodedString(NSDataBase64EncodingOptions.SixtyFourCharacterLineLength);
}
}

But the hash returned by sha256 function written above does not match with the hash calculated using terminal command.

Are we doing something wrong in hash calculation.?

We referred this article for this approach : https://medium.com/flawless-app-stories/ssl-pinning-254fa8ca2109 This article uses Swift code.

Xamarin
Xamarin
A Microsoft open-source app platform for building Android and iOS apps with .NET and C#.
5,301 questions
0 comments No comments
{count} votes