get ssl certificate in .net
For this to work your project will need a reference to System.Security
:
using System.Security;using System.Security.Cryptography;using System.Security.Cryptography.X509Certificates;//Do webrequest to get info on secure siteHttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://mail.google.com");HttpWebResponse response = (HttpWebResponse)request.GetResponse();response.Close();//retrieve the ssl cert and assign it to an X509Certificate objectX509Certificate cert = request.ServicePoint.Certificate;//convert the X509Certificate to an X509Certificate2 object by passing it into the constructorX509Certificate2 cert2 = new X509Certificate2(cert);string cn = cert2.GetIssuerName();string cedate = cert2.GetExpirationDateString();string cpub = cert2.GetPublicKeyString();//display the cert dialog boxX509Certificate2UI.DisplayCertificate(cert2);
.Net Core 2.1
You can use HttpClientHandler and ServerCertificateCustomValidationCallback Property. (This class is available in .net 4.7.1 and above also).
var handler = new HttpClientHandler{ UseDefaultCredentials = true, ServerCertificateCustomValidationCallback = (sender, cert, chain, error) => { /// Access cert object. return true; } }; using (HttpClient client = new HttpClient(handler)) { using (HttpResponseMessage response = await client.GetAsync("https://mail.google.com")) { using (HttpContent content = response.Content) { } } }
@cdev's solution didn't work for me on .NET Core 2.1. It seems HttpWebRequest
is not completely supported on .NET Core.
Here is the function I'm using on .NET Core to get any server's X509 certificate:
// using System;// using System.Net.Http;// using System.Security.Cryptography.X509Certificates;// using System.Threading.Tasks;static async Task<X509Certificate2> GetServerCertificateAsync(string url){ X509Certificate2 certificate = null; var httpClientHandler = new HttpClientHandler { ServerCertificateCustomValidationCallback = (_, cert, __, ___) => { certificate = new X509Certificate2(cert.GetRawCertData()); return true; } }; var httpClient = new HttpClient(httpClientHandler); await httpClient.SendAsync(new HttpRequestMessage(HttpMethod.Head, url)); return certificate ?? throw new NullReferenceException();}