c# - 如何完全验证 X509 证书?

标签 c# .net ssl certificate x509certificate

我需要验证证书(X509Certificate2),其验证方式与在用于通信之前验证的方式相同。

在这种情况下,X509Certificate2.Verify() 将在证书未颁发给安装它的服务器时返回 true。

是否有任何完成的代码块可以对 X509 证书进行全面验证?

问候

编辑:这是我尝试过的代码:

var certificate = GetServerCertificate(CertificateStore,CertificateLocation,Thumbprint);

            if(certificate != null)
            {
                if(certificate.Verify())
                    _logger.Log(NLog.LogLevel.Info, $"Yes");
                else
                    _logger.Log(NLog.LogLevel.Info, $"No");
            }

最佳答案

The X509Certificate2.Verify() will in this case return true while the certificate is not issued to the server it is installed on.


Verify方法不检查有关主机名的任何内容。它验证了
  • 证书未过期。
  • 证书最终链接到受信任的根授权。
  • 链中的所有证书都有适当的嵌套过期时间。
  • 目标证书,除非它是自行颁发的,否则具有吊销端点,并且不会被吊销。
  • 任何中间证书都有吊销端点并且不会被吊销。

  • 它完全等于
    using (X509Chain chain = new X509Chain())
    {
        // Use the default vales of chain.ChainPolicy including:
        //  RevocationMode = X509RevocationMode.Online
        //  RevocationFlag = X509RevocationFlag.ExcludeRoot
        //  VerificationFlags = X509VerificationFlags.NoFlag
        //  VerificationTime = DateTime.Now
        //  UrlRetrievalTimeout = new TimeSpan(0, 0, 0)
    
        bool verified = chain.Build(cert);
    
        for (int i = 0; i < chain.ChainElements.Count; i++)
        {
            chain.ChainElements[i].Certificate.Dispose();
        }
    
        return verified;
    }
    

    Is there any finished code block to do a full validation of the X509 certificate?



    如果“完全验证”只是意味着所有的东西Verify确实如此,那么是的。如果您还关心它是否可用作 TLS 客户端证书(或 TLS 服务器证书),那么您将使用更长的形式(直接使用 X509Chain)并在调用 chain.Build 之前添加应用程序策略要求:
    // See if it's valid as a TLS server
    chain.ChainPolicy.ApplicationPolicy.Add(new Oid("1.3.6.1.5.5.7.3.1"));
    // Alternatively, if it's valid as a TLS client
    chain.ChainPolicy.ApplicationPolicy.Add(new Oid("1.3.6.1.5.5.7.3.2"));
    

    主机名更难。客户端证书没有可验证的名称,这取决于服务器对其的处理方式。服务器证书具有与 SAN/Subject-CN 匹配的主机名,但除了与 TLS (SslStream) 连接之外,没有任何内置功能可以检查。

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

    相关文章:

    c# - 具有多个条件的可观察 TakeUntil

    c# - Unity - 如果我使用自己的 Start() 方法创建两个脚本,哪一个将首先调用?

    c# - AutoMapper.Map 忽略源对象中的所有 Null 值属性

    ssl - AWS ELB IP 地址是 ELB 独有的吗?

    c# - 如何为unicode字符串的存储过程中的参数添加前缀 'N'

    C# - 使用反射比较两个 .net dll

    c# - SqlGeography 类型不匹配

    c# - .NET 相当于旧的 vb left(string, length) 函数

    ssl - Traefik IngressRoute 不接受 TLS 证书

    php - 什么时候我的安全传输尝试变得多余?