这是昨天课堂上一个问题,如何读取到计算机上所有证书的信息呢?我们首先来看一下到底有哪些证书
下面的代码可以通过三个循环找到所有的证书
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)
{
//读取所有的证书
string[] storeName = Enum.GetNames(typeof(StoreName));
string[] storeLocation = Enum.GetNames(typeof(StoreLocation));
foreach (var location in storeLocation)
{
foreach (var name in storeName)
{
X509Store store = new X509Store(
(StoreName)Enum.Parse(typeof(StoreName), name),
(StoreLocation)Enum.Parse(typeof(StoreLocation), location));
store.Open(OpenFlags.ReadOnly);
Console.WriteLine("当前证书区域:{0},子区域是:{1}", location, name);
foreach (var cert in store.Certificates)
{
Console.WriteLine(cert.Subject);
}
store.Close();
Console.WriteLine();
}
}
Console.Read();
}
}
}