从浏览器证书库获取有效证书以进行签名

时间:2016-02-23 08:06:48

标签: c# linq

我需要在WPF中创建一个简单的签名客户端。工作站已配置了一组由智能卡导入的证书。其中一个是签名证书,其他用于电子邮件身份验证和加密。

所以我正在创建一个简单的下拉列表,用户可以从列表中选择他的首选证书,但我想排除与签名文档无关的证书。通过检查证书,我可以阅读它的目的,然后我想以程序的方式阅读它。

到目前为止,我写道:

        IEnumerable<Certificate> certificates;

        X509Store store = new X509Store(StoreLocation.CurrentUser);
        store.Open(OpenFlags.ReadOnly);
        try
        {
            certificates = from X509Certificate2 certificate in store.Certificates
                           where certificate.HasPrivateKey
                           && certificate.NotAfter <= DateTime.Now && certificate.NotBefore >= DateTime.Now
                           select new Certificate
                           {
                               CommonName = certificate.SubjectName.Decode(X500DistinguishedNameFlags.UseUTF8Encoding),
                               Id = Convert.ToString(certificate.GetSerialNumber())
                           };
        }
        finally
        {
            store.Close();
        }

上述代码的结果是一个至少包含众所周知的电子邮件身份验证证书的列表。

要检查证书是否有usage attribute == non repudiation,需要添加哪些条件?

2 个答案:

答案 0 :(得分:0)

感谢@WiktorZychla

        IEnumerable<Certificate> certificates;

        X509Store store = new X509Store(StoreLocation.CurrentUser);
        store.Open(OpenFlags.ReadOnly);
        try
        {
            certificates = from X509Certificate2 certificate in store.Certificates
                           where certificate.HasPrivateKey
                               //&& certificate.NotAfter <= DateTime.Now && certificate.NotBefore >= DateTime.Now
                           //Commented because doesn't work, strangely
                           && certificate.Extensions.OfType<X509KeyUsageExtension>().Any(ku => ku.KeyUsages == X509KeyUsageFlags.NonRepudiation)
                           select new Certificate
                           {
                               CommonName = certificate.SubjectName.Decode(X500DistinguishedNameFlags.UseUTF8Encoding),
                               Id = Encoding.UTF8.GetString(certificate.GetSerialNumber())
                           };
        }
        finally
        {
            store.Close();
        }

答案 1 :(得分:0)

OP接受的答案的关键部分是:

您可以查看Extensions集合并搜索KeyUsage扩展名。

https://msdn.microsoft.com/en-us/library/system.security.cryptography.x509certificates.x509keyusageextension(v=vs.110).aspx

KeyUsages属性可以告诉您实际检查的证书类型。