In this article https://blogs.windows.com/buildingapps/2015/10/13/create-more-secure-apps-with-less-effort-10-by-10/ they explain you how to securely connect to a server. They check the thumbprint to see that the cert is legitimate. But the certificates change over time and the hardcoded string I check against will be no longer valid.
That's why I want to extract the public key. Because I'm certain it's not gonna change from one certificate to other.
In this code:
private async Task DemoSSLRoot()
{
// Send a get request to Bing
HttpClient client = new HttpClient();
Uri bingUri = new Uri("https://www.bing.com");
HttpResponseMessage response = await client.GetAsync(bingUri);
// Get the list of certificates that were used to validate the server's identity
IReadOnlyList<Certificate> serverCertificates = response.RequestMessage.TransportInformation.ServerIntermediateCertificates;
// Perform validation
if (!ValidCertificates(serverCertificates))
{
// Close connection as chain is not valid
return;
}
PrintResults("Validation passed\n");
// Validation passed, continue with connection to service
}
private bool ValidCertificates(IReadOnlyList<Certificate> certs)
{
// In this example, we iterate through the certificates and check that the chain contains
// one specific certificate we are expecting
for (int i = 0; i < certs.Count; i++)
{
PrintResults("Cert# " + i + ": " + certs[i].Subject + "\n");
byte[] thumbprint = certs[i].GetHashValue();
// Check if the thumbprint matches whatever you are expecting
// d4 de 20 d0 5e 66 fc 53 fe 1a 50 88 2c 78 db 28 52 ca e4 74
byte[] expected = new byte[] { 212, 222, 32, 208, 94, 102, 252, 83, 254, 26, 80, 136, 44, 120, 219, 40, 82, 202, 228, 116 };
if (ThumbprintMatches(thumbprint, expected))
{
return true;
}
}
return false;
}
It's quite easy to access the thumbprint. But I need the public key. I was searching in internet and I found really crazy code to check that I was not able to make it work.
Can somebody tell me if there is an easy way to extract the public key from a Certificate in Windows 10?
Regards.
As Tomas said there was a method called GetPublicKey. It is not included in the APIs. Just noticed there was a nuget package called "System.Security.Cryptography.X509Certificates" where this method was available.
Thanks!