如何查找某个特定证书

这是昨天课堂上的一个例子。

image

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
using System.Threading;
using System.Security.Cryptography.X509Certificates;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            //查找特定证书
            X509Store store = new X509Store(StoreLocation.CurrentUser);
            store.Open(OpenFlags.ReadOnly);


            string serialNumber = "b101720bccd997a14e64ff649571e20e".ToUpper();

            //1.第一种查找:遍历
            X509Certificate2 cert = null;
            foreach (var item in store.Certificates)
            {
                if (item.SerialNumber == serialNumber)
                {
                    cert = item; 
                    break;
                }
            }
            if (cert != null)
                Console.WriteLine(cert.Subject);


            //2.第二种查找: 利用Find方法
            X509Certificate2 cert1 = null;
            var found = store.Certificates.Find(X509FindType.FindBySerialNumber, serialNumber, false);
            if (found != null && found.Count>0)
            {
                cert1 = found[0];
                Console.WriteLine(cert1.Subject);
            }
 
                         
                         


            store.Close();
            
            

            

            Console.Read();
        }


    }

  
}
posted @ 2010-03-21 19:02  陈希章  阅读(1435)  评论(0编辑  收藏  举报