I\'m having a problem when I use the method X509Store.Certificates.Find
public static X509Certificate2 FromStore(StoreName storeName,
I suppose that you have copy-pasted the thumbprint from the Windows certificate information dialog box into your code (or to a config file if this is a simplified example). Annoyingly, the first character in the thumbprint textbox is the invisible Unicode "left-to-right-mark" control character. Try selecting the opening string quote and the first character of the thumbprint, deleting them (which will also get rid of the invisible character in-between), and retyping them by hand.
I was subjected to this odd behaviour myself today, and it took me over an hour to figure it out. The way I finally saw it was by using the debugger to check the lengths and hash codes of findValue
and of the Thumbprint
of the certificate object, which turned out to be different. This led me to inspect the character arrays of those strings in the debugger, where the invisible character showed up.
I fell victim to this. Not only was there a Unicode "left-to-right" character in the Windows console snap-in display of the thumbprint, but it also had lowercase hex characters, with spaces between every two characters. The output of CertUtil also had lowercase characters, and spaces. To get a match, I had to specify the findValue as a string which has been transformed to
After long analysis, Here is what worked for me.
This works like a charm.
This tripped me up too, I wrote this function to clean the thumbprint when copied and pasted from MMC:
public string CleanThumbprint(string mmcThumbprint)
{
//replace spaces, non word chars and convert to uppercase
return Regex.Replace(mmcThumbprint, @"\s|\W", "").ToUpper();
}
...
var myThumbprint = CleanThumbprint("b3 ab 84 e5 1e e5 e4 75 e7 a5 3e 27 8c 87 9d 2f 05 02 27 56");
var myCertificate = certificates.Find(X509FindType.FindByThumbprint, myThumbprint, true)[0];
Just to let you know what the invisible character is, I see the thumbprint in the mmc being: 75 3a ...
Then I copy and paste it in my vim, I see the following:
<200e>75 3a ...
So after you get rid of the first char "<200e>" and the extra spaces, you'll be fine.
I ran into this same thing. I couldn't find this answer anywhere in here so I'll post it. It seems for me the X509Store find function just was flat not working. I verified this by a simple for loop and retrieving the cert manually.
X509Store store = new X509Store(StoreName.Root,StoreLocation.LocalMachine);
store.Open(OpenFlags.ReadOnly);
X509Certificate cert = new X509Certificate();
for (int i = 0; i < store.Certificates.Count; i++)
{
if (store.Certificates[i].SerialNumber == "XXXX")
{
cert = store.Certificates[i];
}
}