我可以用C#列出本地安装的数字证书吗?

时间:2013-08-09 09:58:54

标签: c# .net code-signing digital-certificate

我一直在努力寻找获取当前安装在本地计算机上的数字证书信息的方法 - 任何可以获得X509Certificate2类集合的方法。

我能够找到this question,它解释了如何从.pfx文件中获取它。

知道如何为已安装的证书执行此操作吗?

2 个答案:

答案 0 :(得分:7)

作为初学者,您可以查看this code

using System;
using System.Security.Cryptography.X509Certificates;

namespace Encryption
   {
   class CertificateTest
      {
      static void Main()
         {
         X509Store store = new X509Store(StoreName.Root,
            StoreLocation.LocalMachine);
         store.Open(OpenFlags.ReadOnly);
         Console.WriteLine("Friendly Name\t\t\t\t\t Expiration date");
         foreach (X509Certificate2 certificate in store.Certificates)
            {
            Console.WriteLine("{0}\t{1}", certificate.FriendlyName,
               certificate.NotAfter);
            }
         store.Close();
         }
      }
   }

网上有更多高级样本。将System.Security.Cryptography.X509Certificates视为关键字。

以下代码列出了您自己的证书及其属性。

static void o(string s, params object[] args)
{
    Console.WriteLine(s, args);
}

static void CertList()
{
    X509Store store = new X509Store(StoreName.My,  StoreLocation.CurrentUser);
    store.Open(OpenFlags.ReadOnly);
    foreach (X509Certificate2 certificate in store.Certificates)
    {
        o("");
        o("Friendly Name: {0}", certificate.FriendlyName);
        o("Simple Name:   {0}", 
           certificate.GetNameInfo(X509NameType.SimpleName, true));
        o("Issuer:        {0}", certificate.Issuer);
        o("Expiration:    {0}", certificate.NotAfter);

        //  http://msdn.microsoft.com/en-us/library/system.security.cryptography.x509certificates.x509keyusageextension.aspx
        foreach (X509Extension extension in certificate.Extensions)
        {
            o(" {0}  ({1})", extension.Oid.FriendlyName, extension.Oid.Value);

            if (extension.Oid.Value == "2.5.29.15")
            //  if (extension.Oid.FriendlyName == "Key Usage")
            {
                X509KeyUsageExtension ext = (X509KeyUsageExtension)extension;
                o("Key usages:          {0}", ext.KeyUsages);
            }
            else if (extension.Oid.Value == "2.5.29.37")
            //  if (extension.Oid.FriendlyName == "Extended Key Usage")
            {
                X509EnhancedKeyUsageExtension ext =
                                   (X509EnhancedKeyUsageExtension)extension;
                o("Extended Key usages: {0}", ext.EnhancedKeyUsages);
            }
        }
    }
    store.Close();
}

例程列出了使用VBA创建的系统上的Microsoft Office 2010 SELFCERT.EXE安全证书。但是我无法识别这些证书的任何特殊属性/属性来过滤它们,

答案 1 :(得分:3)

对我来说,此代码会打印IIS Express Development Certificate

var store = new X509Store(StoreLocation.LocalMachine);
store.Open(OpenFlags.ReadOnly);
var certificates = store.Certificates;
foreach (var certificate in certificates)
{
     Console.WriteLine(certificate.FriendlyName);
}
store.Close();