Search code examples
c#x509certificatex509certificate2

X509 store can not find certificate by SerialNumber


I need to get a X509 Certificate by Serial Number, I have the serial number and I am looping through them and i see the serial number in the collection I need but it is never found.

Here is my debug code just ot make sure I am seeing the proper serial numbers:

X509Store store = new X509Store(StoreName.My, StoreLocation.LocalMachine);
            store.Open(OpenFlags.ReadOnly);

            foreach (X509Certificate2 cert in store.Certificates)
            {
                System.Web.HttpContext.Current.Response.Write (cert.SerialNumber + "=" + oauthCertificateFindValue + "<br/>");
                if (cert.SerialNumber == oauthCertificateFindValue)
                {
                    System.Web.HttpContext.Current.Response.Write("<br/>FOUND FOUND FOUND<br/>");
                }
            }

Here is the output from this code:

0091ED5F0CAED6AD52‎‎=0091ED5F0CAED6AD52
3D3233116A894CB244DB359DF99E7862=0091ED5F0CAED6AD52

Clearly the first one I loop though matches the serial number but the if always fails and what I really need to work based on this serial number also fails:

   X509Certificate2Collection certificateCollection = store.Certificates.Find(x509FindType, oauthCertificateFindValue, false);

   if (certificateCollection.Count == 0)
                {
                    throw new ApplicationException(string.Format("An OAuth certificate matching the X509FindType '{0}' and Value '{1}' cannot be found in the local certificate store.", oauthCertificateFindType, oauthCertificateFindValue));
                }

     return certificateCollection[0];

What am I doing wrong here?


Solution

  • It would appear that there are two invisible characters in the certificate serial number of the certificate you're trying to find, which is why they aren't matching. You should be able to confirm this if you change the output from your foreach loop to:

    System.Web.HttpContext.Current.Response.Write (string.Format("{0} (Length: {1}) = {2} (Length: {3})<br/>", cert.SerialNumber, cert.SerialNumber.Length oauthCertificateFindValue, oauthCertificateFindValue.Length);
    

    You'll most likely see that the values look the same, but their lengths differ (indicating the presence of these invisible characters).

    You will need to update your search value to match the certificate's serial number including the invisible characters.