user166013
user166013

Reputation: 1503

how to obtain SSL certificate information of a remote server in c#

i have to develop an application in c# to obtain SSL certificate information like expiry date, issued by, etc based on the DNS (say *.google.com) I provide so that if expiry date is near I can proactively handle it. If i provide the DNS as *.google.com then i need to obtain the details of SSL ceritificate information of that domain.

I tried following http://awesomeideas.net/page/Cert-Expiry-Check.aspx, but i feel it is for certificates stored in local system. i also tried using HttpWebRequest to obtain the details of SSL certificate, but it required me to enter a valid URI which in my case is not availble. i just have DNS name

below is the code i used to obtain information using HttpWebRequest. but it required me to enter valid URI of type https://*.domain.com

Uri uri = new Uri(DNSEntry); 
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri); 
request.Method = WebRequestMethods.Http.Get; 
HttpWebResponse response = (HttpWebResponse)request.GetResponse(); 
X509Certificate cert1 = request.ServicePoint.Certificate; 
X509Certificate2 cert = new X509Certificate2(cert1); 
DateTime dtCertExpiry = Convert.ToDateTime(cert.NotAfter.ToString());

Upvotes: 8

Views: 10454

Answers (1)

user166013
user166013

Reputation: 1503

i tried using the following it is working fine :

string strDNSEntry is the DNS for which you need the SSL

public X509Certificate2 DownloadSslCertificate(string strDNSEntry)
{

    X509Certificate2 cert = null;
    using (TcpClient client = new TcpClient())
    {
        //ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3;           
        client.Connect(strDNSEntry, 443);

        SslStream ssl = new SslStream(client.GetStream(), false, new RemoteCertificateValidationCallback(ValidateServerCertificate), null);
        try
        {
            ssl.AuthenticateAsClient(strDNSEntry);
        }
        catch (AuthenticationException e)
        {
            log.Debug(e.Message);
            ssl.Close();
            client.Close();
            return cert;
        }
        catch (Exception e)
        {
            log.Debug(e.Message);
            ssl.Close();
            client.Close();
            return cert;
        }
        cert = new X509Certificate2(ssl.RemoteCertificate);
        ssl.Close();
        client.Close();
        return cert;
    }
}


public static bool ValidateServerCertificate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
{
    if (sslPolicyErrors == SslPolicyErrors.None)
        return true;

    Console.WriteLine("Certificate error: {0}", sslPolicyErrors);

    // Do not allow this client to communicate with unauthenticated servers. 
    return false;
}

Upvotes: 11

Related Questions