I have a problem with an MVC web application that calls another service using a private certificate.
The certificate is in my personal keystore against the current computer. I used winhttpcertcfg to grant certificate permissions to the application pool identifier of my web application. The key is loaded in the following way:
internal bool SetCertificateFromCertStore(string subjectName) { X509Store store = null; try { store = new X509Store(StoreName.My, StoreLocation.LocalMachine); store.Open(OpenFlags.ReadOnly); X509Certificate2Collection certs = store.Certificates.Find(X509FindType.FindBySubjectName, subjectName, true); if (certs.Count != 1) { store.Close(); store = new X509Store(StoreName.My, StoreLocation.CurrentUser); store.Open(OpenFlags.ReadOnly); certs = store.Certificates.Find(X509FindType.FindBySubjectName, subjectName, true); if (certs.Count != 1) { throw new Exception("Unable to find Certificate"); } } _certificate = certs[0]; return true; } finally { if (store != null) { store.Close(); } } }
This code worked every time until a couple of weeks ago (April 12), when at 5:05 pm I noticed the first instance in ELMAH from the "Unable to find certificate" exception. Checking the application log, the system still works with almost all requests, and this error occurs only several times per hour for some requests.
I read about similar issues that offer to implement code similar to the code that I already use (request from several stores). Is there any known issue with the Windows certificate store? Perhaps a problem with the lock? Is there any other way to handle this or something obvious that I'm doing wrong here?
Any help you can offer will be appreciated, as I couldn’t try!
source share