Search code examples
.netcertificatex509

Certificate is missing from X509Store.Certificates collection


I'm testing out the following code on my PC:

private static void Main(string[] args)
{
    X509Store x509Store = new X509Store(StoreName.My, StoreLocation.LocalMachine);

    x509Store.Open(OpenFlags.ReadOnly);

    foreach (var x509StoreCertificate in x509Store.Certificates)
    {
        Console.WriteLine(x509StoreCertificate.Thumbprint);
    }

    x509Store.Close();

    Console.WriteLine("Finished.");
    Console.ReadLine();
}

When I analysed the list of thumbprints that were displayed in the console, I noticed that there is a cert which I imported today that is not appearing in the list.

That cert I imported was done in the following manner:

  • Open MMC and add the Certificates snap-in.
  • I opened the snap-in at the Computer account level,
  • In both the Personal and Trusted Root Certification Authorities I imported the .pfx certificate file.

After doing the above, I can see the cert in the certificates list for both the areas I mentioned. In fact, when I run the following Powershell script:

cls
Set-Location Cert:\LocalMachine
dir -Recurse | where {$_.Thumbprint -ne $null -and $_.Thumbprint.ToLower() -eq "‎‎thumbprint omitted"}

It finds the two locations of the cert, with Directory: Microsoft.PowerShell.Security\Certificate::LocalMachine\My being one of them.

So it's not clear to me why the C# console app is not listing this cert in the Certificates collection.

I may have just missed something obvious, but any help would be appreciated.


Solution

  • Urgh :(

    Turns out I had copied the thumbprint from the cert properties dialog, which meant it had „ at the start of the string, which I could not see initially. After removing that segment from the front of the thumbprint, my code found the cert without a hitch.