Before I begin, this is not a duplicate of this QA ( How to find certificate by its thumbprint in C# ) - the thumbprint string I'm using is 40 characters long and does not contain any hidden characters copied from MMC.
Here's the code I'm using:
String thumbprint = "c112345678904655585e8c8244af5d3f2630498b".ToUpperInvariant();
assert( thumbprint.Length == 40 );
X509Store store = new X509Store(StoreName.My, StoreLocation.CurrentUser);
store.Open(OpenFlags.ReadOnly);
X509Certificate2Collection matches = store.Certificates.Find(X509.FindType.FindBySerialNumber, thumbprint, validOnly: false );
assert( matches.Count == 1 ); // this fails, the count is == 0.
But when I interrogate the certificates manually, it's fine:
assert( store.Certificates.Count == 1 ); // there is only 1 cert in the store
X509Certificate2 cert = store.Certificates[0];
assert( cert.Thumbprint == thumbprint ); // this passes
What could cause this? Why would Find
not return a certificate when there's an exact match?
This MSDN Blog post describes the same, though provides no explanation: https://blogs.msdn.microsoft.com/avkashchauhan/2011/11/19/what-to-do-when-your-code-could-not-find-the-certificate-in-azure-vm/