X509Store Certificates.Find FindByThumbprint

2.1k views Asked by At

I have a problem when I use store.Certificates.Find. I am using Windows server 2008 R2 with NET 3.5. The cert is installed by

public static void AddCertificate(X509Certificate2 cert, StoreName name = StoreName.My, StoreLocation location = StoreLocation.LocalMachine)
    {
        var store = new X509Store(name, location);
        store.Open(OpenFlags.ReadWrite);
        store.Add(cert);
        store.Close();
    }

After that, find the certificate by

string certThumbprint = "XXXX";
var certificates = store.Certificates.Find(X509FindType.FindByThumbprint, commandLineArgs.CertificateThumbprint, true);

if (certificates.Count == 0)
  {
    throw new ArgumentException("No certificate found with given thumbprint.");
  }

The exception should not be thrown at all, yet it seems to be thrown sometimes. It throws exceptions about 5 times per 100 runs.

I have googled and found the "invisible first character" issue, but in my case, the thumbprint is indeed hardcoded. I am not reading the thumbprint from anywhere. The exactly codes run on windows server 2012 with NET.4.5 have never given me any problems. This only applies to windows server with NET.3.5. I am wondering why the results are so inconsistent only on WS2008R2?

2

There are 2 answers

0
Stoyan Uzunov On

I think that the problem might be that your user dont have permisions for the certificate

Try this

  1. Download and install: Windows HTTP Services Certificate Configuration Tool (WinHttpCertCfg.exe) http://www.microsoft.com/en-us/download/details.aspx?id=19801
  2. And run: WinHttpCertCfg.exe -g -c LOCAL_MACHINE\Store -s "IssuedToName" -a "AccountName"
0
pepo On

Please verify that the certificate is indeed in LocalMachine\My store where you inserted it. I assume that you will find the certificate in the store, but when you doubleclick it you will see, that is is not trusted. My assumption is that the certificate chain was not build up to a trusted root CA.

Now, modify your code to search for certificate (I've changed the last parameter to false)

var certificates = store.Certificates.Find(X509FindType.FindByThumbprint, commandLineArgs.CertificateThumbprint, false);

or (IMHO better) make the imported certificate trusted by importing CA certificates to appropriate stores (Root, Intermediate authorities).