c# - 如何验证 KeyUsage 的证书

标签 c# .net x509certificate2

我正在尝试验证证书以确保它具有正确的 keyUsage。 但是看不到我如何将我的 X509KeyUsageFlags.KeyEncypherment 使用标志指定到此应用程序策略中。

这是我目前的代码。还有其他人让这个工作吗?

X509Certificate2 tmpCert = new X509Certificate2(Cert);

X509Chain ch = new X509Chain();
ch.ChainPolicy.RevocationMode = X509RevocationMode.NoCheck;
ch.ChainPolicy.VerificationFlags = X509VerificationFlags.AllowUnknownCertificateAuthority;

var kUsage = new System.Security.Cryptography.Oid("2.5.29.15");                    
ch.ChainPolicy.ApplicationPolicy.Add(kUsage);

bool success = ch.Build(tmpCert);

最佳答案

KeyUsage 扩展不是链的一部分,因为这个扩展没有限制。因此,您需要两个单独的过程

  1. 验证证书链
  2. 根据其他要求验证链中的单个证书。

@Yacoub 提供的代码缺少一个重要结果:证书中未提供 key 使用扩展。在这种情况下,假定 key 对所有用途都有效,但 certKeySigncRLSign 对所有类型的 V3 证书的用途除外。在 V1 或 V2 证书的情况下,缺少 KeyUsage 扩展字面意思是所有用法。

我建议使用以下代码:

using System.Linq;
using System.Security.Cryptography.X509Certificates;
// there should go namespace and class definition
...
//
public bool KeyUsageHasUsage(X509Certificate2 cert, X509KeyUsageFlags flag) {
    if (cert.Version < 3) { return true; }
    List<X509KeyUsageExtension> extensions = cert.Extensions.OfType<X509KeyUsageExtension>().ToList();
    if (!extensions.Any()) {
        return flag != X509KeyUsageFlags.CrlSign && flag != X509KeyUsageFlags.KeyCertSign;
    }
    return (extensions[0].KeyUsages & flag) > 0;
}

它被实现为验证任意 key 使用标志的通用函数。

关于c# - 如何验证 KeyUsage 的证书,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32704248/

相关文章:

c# - 如何从私有(private)工作组队列接收消息

c# - 如果我向 AddControllersWithViews() 添加扩展,它是否也适用于 AddRazorPages()

c# - 我的循环迭代了多少次

asp.net - 如何让 TypeScript 与 Visual Studio 2013 一起工作

web-services - 如何使用 WCF 连接 Apple 的 GSX NewGeneration Web 服务?

c# - .Net MySql 用户定义变量作为输出参数

c# - System.Transactions 中未处理的异常在网络不稳定期间停止 Windows 服务

c# - PrivateKey 引发了 System.Security.Cryptography.CryptographicException 类型的异常

c# - 将字节数组转换为 X.509 证书

c# - 使用 DataGridView.DataSource 显示单个对象