How to get information from a SSL certificate via C #?

7

How to get information (expiration date for example) from an SSL certificate via C #?

    
asked by anonymous 25.03.2015 / 21:14

3 answers

2

I was able to resolve it as follows:

public static void CheckCertificateExpiration(string[] args) 
    {
        foreach (string servername in args)
        {
            Console.WriteLine("\n\nFetching SSL cert for {0}\n", servername);
            TcpClient client = new TcpClient(servername, 443);
            SslStream sslStream = new SslStream(client.GetStream(), false, callback, null);

            try
            {
                sslStream.AuthenticateAsClient(servername);
            }
            catch (AuthenticationException ex)
            {
                Console.WriteLine("Exception: {0}", ex.Message);
                if (ex.InnerException != null)
                {
                    Console.WriteLine("Inner exception: {0}", ex.InnerException.Message);
                }
                Console.WriteLine("Authentication failed - closing the connection.");
            }

            client.Close();
        }
    }

    static RemoteCertificateValidationCallback callback = delegate(object sender, X509Certificate cert, X509Chain chain, SslPolicyErrors sslError)
    {
        X509Certificate2 x509 = new X509Certificate2(cert);

        // Print to console information contained in the certificate.
        Console.WriteLine("Subject: {0}", x509.Subject);
        Console.WriteLine("Issuer: {0}", x509.Issuer);
        Console.WriteLine("Version: {0}", x509.Version);
        Console.WriteLine("Valid Date: {0}", x509.NotBefore);
        Console.WriteLine("Expiry Date: {0}", x509.NotAfter);
        Console.WriteLine("Thumbprint: {0}", x509.Thumbprint);
        Console.WriteLine("Serial Number: {0}", x509.SerialNumber);
        Console.WriteLine("Friendly Name: {0}", x509.PublicKey.Oid.FriendlyName);
        Console.WriteLine("Public Key Format: {0}", x509.PublicKey.EncodedKeyValue.Format(true));
        Console.WriteLine("Raw Data Length: {0}", x509.RawData.Length);

        if (sslError != SslPolicyErrors.None)
        {
            Console.WriteLine("Certificate error: " + sslError);
        }

        return false;
    };

Reference

    
26.03.2015 / 14:16
8

According to page which I put in the comment and documentation you can get all information by instantiating an X509 certificate object:

var x509 = new X509Certificate2("caminhoCompletoDoCertificadoAqui");
byte[] rawData = x509.RawData;
Console.WriteLine("Content Type: {0}", X509Certificate2.GetCertContentType(rawData));
Console.WriteLine("Serial Number: {0}", x509.SerialNumber);
Console.WriteLine("Friendly Name: {0}", x509.FriendlyName);
Console.WriteLine("Certificate Verified?: {0}", x509.Verify());
Console.WriteLine("Simple Name: {0}", x509.GetNameInfo(X509NameType.SimpleName, true));
Console.WriteLine("Signature Algorithm Name: {0}", x509.SignatureAlgorithm.FriendlyName);
Console.WriteLine("Private Key: {0}", x509.PrivateKey.ToXmlString(false));
Console.WriteLine("Public Key: {0}", x509.PublicKey.Key.ToXmlString(false));
Console.WriteLine("Certificate Archived?: {0}", x509.Archived);
Console.WriteLine("Subject: {1}", x509.Subject);
Console.WriteLine("Issuer: {1}", x509.Issuer);
Console.WriteLine("Version: {1}", x509.Version);
Console.WriteLine("Valid Date: {1}", x509.NotBefore);
Console.WriteLine("Expiry Date: {1}", x509.NotAfter);
Console.WriteLine("Thumbprint: {1}", x509.Thumbprint);
Console.WriteLine("Serial Number: {1}", x509.SerialNumber);
Console.WriteLine("Friendly Name: {1}", x509.PublicKey.Oid.FriendlyName);
Console.WriteLine("Public Key Format: {1}", x509.PublicKey.EncodedKeyValue.Format(true));
Console.WriteLine("Raw Data Length: {1}", x509.RawData.Length);
Console.WriteLine("Certificate to string: {1}", x509.ToString(true));

In addition to the properties the documentation shows several methods that can get this same information, such as GetExpirationDateString() to get what you have sampled.

Here are several ways to get the information as demonstrated. As it's probably not just the date you're going to need, there are several examples, you'll use what's in the way that's most convenient for you.

See working on dotNetFiddle .

    
26.03.2015 / 01:21
7

So:

var certificate = new X509Certificate("C:\Caminho\Do\Arquivo", "senhadocertificado");

An SSL certificate is a certificate of type X509. It is also the same type of certificate used for digital card signatures (e-CPF, OAB, etc.) or token.

Here you can see all information that can be returned . Basically, the expiration date is as follows:

var dataDeValidade = Convert.ToDateTime(certificate.GetExpirationDateString());

If you want, you can use the X509Certificate2 .

If the certificate is on a remote site, it can be obtained like this:

var request = (HttpWebRequest)WebRequest.Create("https://sitequesedesejaacessar");
var response = (HttpWebResponse)request.GetResponse();
response.Close();
X509Certificate cert = request.ServicePoint.Certificate;
    
25.03.2015 / 21:56