C# - every time SSL cert is reissued it requires to change serial number in application

358 views Asked by At

I am using the below code to configure SSL cert in C# web API. The issue is I am finding the SSL cert using the serial number and every time when the SSL cert is reissued by Infra I have to update the cert serial number in the application config. Is there any cert property that remains the same after reissue?

X509Store store = new X509Store(StoreLocation.LocalMachine);
store.Open(OpenFlags.ReadOnly);    
X509Certificate2Collection certificates = store.Certificates.Find(
                                                X509FindType.FindBySerialNumber,
                                                sslCertificateSerialNumber,
                                                false);

'sslCertificateSerialNumber' is coming from the config file

1

There are 1 answers

2
Amir On BEST ANSWER

You can use findBySubjectName it's more useful. If you have multiple subjects you can act like this:

        X509Store store = new X509Store(StoreName.TrustedPeople, StoreLocation.LocalMachine);
        store.Open(OpenFlags.ReadOnly | OpenFlags.OpenExistingOnly);
        X509Certificate2Collection collection = (X509Certificate2Collection)store.Certificates;
        foreach (X509Certificate2 x509 in collection)
        {
            if (x509.Thumbprint == "5550541D10488D148BCAC0D289DED441609849FF")
            {
                client.ClientCredentials.ClientCertificate.SetCertificate(
                 x509.SubjectName.Name, store.Location, StoreName.TrustedPeople);
            }
        }