C#如何验证根CA证书(x509)链?

前端之家收集整理的这篇文章主要介绍了C#如何验证根CA证书(x509)链?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
假设我有三张证书(以Base64格式)
Root
 |
 --- CA
     |
     --- Cert (client/signing/whatever)

如何验证C#中的证书和证书路径/链?
(所有这三个证书可能不在我的电脑认证商店)

编辑:BouncyCastle具有验证功能.但我试图不使用任何第三方库.

byte[] b1 = Convert.FromBase64String(x509Str1);
    byte[] b2 = Convert.FromBase64String(x509Str2);
    X509Certificate cer1 = 
        new X509CertificateParser().ReadCertificate(b1);
    X509Certificate cer2 =
        new X509CertificateParser().ReadCertificate(b2);
    cer1.Verify(cer2.GetPublicKey());

如果cer1没有被cert2(CA或root)签名,将会有异常.这正是我想要的.

解决方法

X509Chain课程旨在做到这一点,甚至可以自定义如何执行链式构建过程.
static bool VerifyCertificate(byte[] primaryCertificate,IEnumerable<byte[]> additionalCertificates)
{
    var chain = new X509Chain();
    foreach (var cert in additionalCertificates.Select(x => new X509Certificate2(x)))
    {
        chain.ChainPolicy.ExtraStore.Add(cert);
    }

    // You can alter how the chain is built/validated.
    chain.ChainPolicy.RevocationMode = X509RevocationMode.NoCheck;
    chain.ChainPolicy.VerificationFlags = X509VerificationFlags.IgnoreWrongUsage;

    // Do the validation.
    var primaryCert = new X509Certificate2(primaryCertificate);
    return chain.Build(primaryCert);
}

如果需要,X509Chain将包含有关Build()== false的验证失败的附加信息.

编辑:这只会确保您的CA有效.如果要确保链条相同,可以手动检查指纹.您可以使用以下方法来确保认证链是正确的,它期望链条按顺序:…,INTERMEDIATE2,INTERMEDIATE1(INTERMEDIATE2签名者),CA(INTERMEDIATE1签约者)

static bool VerifyCertificate(byte[] primaryCertificate,IEnumerable<byte[]> additionalCertificates)
{
    var chain = new X509Chain();
    foreach (var cert in additionalCertificates.Select(x => new X509Certificate2(x)))
    {
        chain.ChainPolicy.ExtraStore.Add(cert);
    }

    // You can alter how the chain is built/validated.
    chain.ChainPolicy.RevocationMode = X509RevocationMode.NoCheck;
    chain.ChainPolicy.VerificationFlags = X509VerificationFlags.IgnoreWrongUsage;

    // Do the preliminary validation.
    var primaryCert = new X509Certificate2(primaryCertificate);
    if (!chain.Build(primaryCert))
        return false;

    // Make sure we have the same number of elements.
    if (chain.ChainElements.Count != chain.ChainPolicy.ExtraStore.Count + 1)
        return false;

    // Make sure all the thumbprints of the CAs match up.
    // The first one should be 'primaryCert',leading up to the root CA.
    for (var i = 1; i < chain.ChainElements.Count; i++)
    {
        if (chain.ChainElements[i].Certificate.Thumbprint != chain.ChainPolicy.ExtraStore[i - 1].Thumbprint)
            return false;
    }

    return true;
}

我无法测试,因为我没有一个完整的CA链与我,所以最好是调试和逐步的代码.

原文链接:https://www.f2er.com/csharp/94134.html

猜你在找的C#相关文章