How to obtain information from an SSL Certificate via C#?

Asked

Viewed 2,007 times

7

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

  • Where is the certificate? Give more information than you are trying to do. Do any of these pages help you? http://www.a2zmenu.com/blogs/csharp/how-to-fetch-certificate-details-from-c-sharp-code.aspx and http://stackoverflow.com/q/2690082/221800. If this is the case, I can prepare a response.

  • @bigown is a cerified https that sits on a server on which I refer him to on my IIS website.

  • @mustache I put as answer solved. It was kind of a merge of his, the gypsy and the reference I put.

3 answers

9

In accordance with the page that I put in the comment and the documentation you can get all information instantiating a certificate object X509:

using static System.Console;
using System.Text;
using System.Security.Cryptography.X509Certificates;

public class Program {
    public static void Main() {
        var texto = @"Certificate:
-----BEGIN CERTIFICATE-----
MIIGJzCCBA+gAwIBAgIBATANBgkqhkiG9w0BAQUFADCBsjELMAkGA1UEBhMCRlIx
DzANBgNVBAgMBkFsc2FjZTETMBEGA1UEBwwKU3RyYXNib3VyZzEYMBYGA1UECgwP
d3d3LmZyZWVsYW4ub3JnMRAwDgYDVQQLDAdmcmVlbGFuMS0wKwYDVQQDDCRGcmVl
bGFuIFNhbXBsZSBDZXJ0aWZpY2F0ZSBBdXRob3JpdHkxIjAgBgkqhkiG9w0BCQEW
E2NvbnRhY3RAZnJlZWxhbi5vcmcwHhcNMTIwNDI3MTAzMTE4WhcNMjIwNDI1MTAz
MTE4WjB+MQswCQYDVQQGEwJGUjEPMA0GA1UECAwGQWxzYWNlMRgwFgYDVQQKDA93
d3cuZnJlZWxhbi5vcmcxEDAOBgNVBAsMB2ZyZWVsYW4xDjAMBgNVBAMMBWFsaWNl
MSIwIAYJKoZIhvcNAQkBFhNjb250YWN0QGZyZWVsYW4ub3JnMIICIjANBgkqhkiG
9w0BAQEFAAOCAg8AMIICCgKCAgEA3W29+ID6194bH6ejLrIC4hb2Ugo8v6ZC+Mrc
k2dNYMNPjcOKABvxxEtBamnSaeU/IY7FC/giN622LEtV/3oDcrua0+yWuVafyxmZ
yTKUb4/GUgafRQPf/ei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JtNyggFzmtTuV02nkUj1bYYYC5f0L
ADr6s0XMyaNk8twlWYlYDZ5uKDpVRVBfiGcq0uJIzIvemhuTrofh8pBQQNkPRDFT
Rq1iTo1Ihhl3/Fl1kXk1WR3jTjNb4jHX7lIoXwpwp767HAPKGhjQ9cFbnHMEtkro
RlJYdtRq5mccDtwT0GFyoJLLBZdHHMHJz0F9H7FNk2tTQQMhK5MVYwg+LIaee586
CQVqfbscp7evlgjLW98H+5zylRHAgoH2G79aHljNKMp9BOuq6SnEglEsiWGVtu2l
hnx8SB3sVJZHeer8f/UQQwqbAO+Kdy70NmbSaqaVtp8jOxLiidWkwSyRTsuU6D8i
DiH5uEqBXExjrj0FslxcVKdVj5glVcSmkLwZKbEU1OKwleT/iXFhvooWhQ==
-----END CERTIFICATE-----
";
        var x509 = new X509Certificate2(Encoding.ASCII.GetBytes(texto));
        byte[] rawData = x509.RawData;
        WriteLine($"Content Type: {X509Certificate2.GetCertContentType(rawData)}");
        WriteLine($"Serial Number: {x509.SerialNumber}");
        WriteLine($"Friendly Name: {x509.FriendlyName}");
        WriteLine($"Certificate Verified?: {x509.Verify()}");
        WriteLine($"Simple Name: {x509.GetNameInfo(X509NameType.SimpleName, true)}");
        WriteLine($"Signature Algorithm Name: {x509.SignatureAlgorithm.FriendlyName}");
        WriteLine($"Public Key: {x509.PublicKey.Key.ToXmlString(false)}");
        WriteLine($"Certificate Archived?: {x509.Archived}");
        WriteLine($"Subject: {x509.Subject}");
        WriteLine($"Issuer: {x509.Issuer}");
        WriteLine($"Version: {x509.Version}");
        WriteLine($"Valid Date: {x509.NotBefore}");
        WriteLine($"Expiry Date: {x509.NotAfter}");
        WriteLine($"Thumbprint: {x509.Thumbprint}");
        WriteLine($"Serial Number: {x509.SerialNumber}");
        WriteLine($"Friendly Name: {x509.PublicKey.Oid.FriendlyName}");
        WriteLine($"Public Key Format: {x509.PublicKey.EncodedKeyValue.Format(true)}");
        WriteLine($"Raw Data Length: {x509.RawData.Length}");
        WriteLine($"Certificate to string: {x509.ToString(true)}");
    }
}

Behold working in the ideone. And in the .NET Fiddle. Also put on the Github for future reference.

In addition to the properties the documentation shows various methods that can obtain this same information, such as the GetExpirationDateString() to take what you exemplified.

There are several ways to get the information as demonstrated. As it is probably not just the date you will need, there are several examples, you will use what and the way it is most convenient for you.

8

Thus:

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

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

Here you can see all possible information to be returned. Basically, the expiration date is obtained like this:

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

If you want, you can use the class 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;

2


I was able to solve it this way:

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.