Skip to content

Instantly share code, notes, and snippets.

@pavlovmilen
Created June 1, 2018 15:25
Show Gist options
  • Save pavlovmilen/8a4594e13821fd80c7825236c7d70ada to your computer and use it in GitHub Desktop.
Save pavlovmilen/8a4594e13821fd80c7825236c7d70ada to your computer and use it in GitHub Desktop.
Get SHA1 for Public key of SSL Cert Xamarin.iOS
private byte[] rsa2048Asn1Header = new byte[] {0x30, 0x82, 0x01, 0x22, 0x30, 0x0d, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86,
0xf7, 0x0d, 0x01, 0x01, 0x01, 0x05, 0x00, 0x03, 0x82, 0x01, 0x0f, 0x00};
public override void DidReceiveChallenge(NSUrlSession session, NSUrlAuthenticationChallenge challenge, Action<NSUrlSessionAuthChallengeDisposition, NSUrlCredential> completionHandler)
{
//Sample implementation using SHA1Managed
var secServerChain = challenge.ProtectionSpace.ServerSecTrust;
int certCount = challenge.ProtectionSpace.ServerSecTrust.Count;
var certData = secServerChain[i];
var policy = SecPolicy.CreateBasicX509Policy();
var secTrust = new SecTrust(certData, policy);
//get public key
var publicKey = secTrust.GetPublicKey().GetExternalRepresentation();
var publicKeyBytes = new byte[publicKey.Length];
System.Runtime.InteropServices.Marshal.Copy(publicKey.Bytes, publicKeyBytes, 0, Convert.ToInt32(publicKey.Length));
//adding rsa2048Asn1 Header
var header = NSData.FromArray(rsa2048Asn1Header);
var headerBytes = new byte[header.Length];
System.Runtime.InteropServices.Marshal.Copy(header.Bytes, headerBytes, 0, Convert.ToInt32(header.Length));
//combine rsa2048Asn1 header and public key into one item
var allBytes = new byte[headerBytes.Length + publicKeyBytes.Length];
Buffer.BlockCopy(headerBytes, 0, allBytes, 0, headerBytes.Length);
Buffer.BlockCopy(publicKeyBytes, 0, allBytes, headerBytes.Length, publicKeyBytes.Length);
string sha1forPublicKey;
using (var sha1 = new SHA1Managed())
{
var asnEncodedData = new AsnEncodedData(allBytes);
var hash = sha1.ComputeHash(asnEncodedData.RawData);
sha1forPublicKey = Convert.ToBase64String(hash);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment