Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
791 views
in Technique[技术] by (71.8m points)

x509certificate - How to find certificate by its thumbprint in C#

I am using this code to find the certificate by its thumbprint. certificate exists in certificate manager in personal certificate store but this code is not finding that certificate.

Please tell me where I'm doing wrong in it.

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            string certThumbPrint = "??fe14593dd66b2406c5269d742d04b6e1ab03adb1";
            X509Store certStore = new X509Store(StoreName.My, StoreLocation.CurrentUser);
            // Try to open the store.

            certStore.Open(OpenFlags.ReadOnly);
            // Find the certificate that matches the thumbprint.
            X509Certificate2Collection certCollection = certStore.Certificates.Find(
                X509FindType.FindByThumbprint, certThumbPrint, false);
            certStore.Close();

            // Check to see if our certificate was added to the collection. If no, 
            // throw an error, if yes, create a certificate using it.
            if (0 == certCollection.Count)
            {
                Console.WriteLine("Error: No certificate found containing thumbprint " );
            }
            Console.ReadLine();
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Just stumbled over this question when Googling for the same issue, and found the answer here: if, like me, you obtained your "source" thumbprint from MMC by highlighting the thumbprint and copying it to the clipboard, you've almost certainly caught an invisible character at the start of the screen, so:

string certThumbPrint = "??fe14593dd66b2406c5269d742d04b6e1ab03adb1";

is actually

string certThumbPrint = "??INVISIBLECHARACTERfe14593dd66b2406c5269d742d04b6e1ab03adb1";

If you delete this invisible character (you can tell it's there when you press backspace or delete beside it and nothing seems to happen), or just retype the thumbprint by hand, your code should work fine. Now if only Visual Studio had a "show invisible characters" option ...


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...