How to access the most recent cerificate among 2 certificates with same common name in c#

585 Views Asked by At

How to access the most recent certificate or the certificate that will expire later among 2 certificates which has the same common name from the windows certificates store in c#. I am using X509Store.Certificates.Find to get the certs, but it returns me a list of certs, and they have the same CN name, but I want the latest.

PS: i dont want to access it via thumbprint because I have to change it every time the cert expires

1

There are 1 best solutions below

1
ClmCpt On

The following funtion will accept an array of certificates and return the one that expires last. It does so by creating an ordered list of certificates in descending order, based on the expiration date.

The function makes no assumption about the validity status of each certificate.

public Certificate getLongestLastingCertificate(Certificate[] certs)
{
    Certificate longetsLastingCert = null;
    if (certs != null)
    {
        if (certs.Count > 0)
        {
            longetsLastingCert  = certs.OrderByDescending(o => o.GetExpirationDate()).First();
        }
    }
    return longetsLastingCert;
}