Public key from certificate in C # universal application platform

In this article https://blogs.windows.com/buildingapps/2015/10/13/create-more-secure-apps-with-less-effort-10-by-10/ they explain to you how to connect to the server securely . They check the fingerprint to make sure the certificate is legal. But the certificates change over time, and the hard-coded string that I check will be no longer valid.

That is why I want to extract the public key. Because I’m sure that it will not change from one certificate to another.

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 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; } 

Read more at https://blogs.windows.com/buildingapps/2015/10/13/create-more-secure-apps-with-less-effort-10-by-10/#1tFDZeMtskOkOrvd.99

Pretty easy to access fingerprint. But I need a public key. I searched on the Internet and I found really crazy code to verify that I could not get it to work.

Can someone tell me if there is an easy way to extract the public key from a certificate in Windows 10?

Sincerely.

+1
source share
2 answers

As Thomas said, there was a GetPublicKey method. It is not included in the API. I just noticed that there was a nuget package called "System.Security.Cryptography.X509Certificates" where this method was available.

Thanks!

+1
source

X509Certificate.GetPublicKey is available for the universal Windows platform.

You can use, for example:

 var publicKey = certs[i].GetPublicKey(); 

or

 byte[] publicKey = certs[i].GetPublicKey.EncodedKeyValue.RawData; 
+1
source

Source: https://habr.com/ru/post/1240128/


All Articles