如何验证证书是否由特定证书颁发机构创建?

Jef*_*yer 14 .net c# security certificate

我有一个Windows证书颁发机构,我用它来通过.net/c#发出客户端身份验证证书.通过COM调用证书颁发机构的API,我已经能够成功地以编程方式颁发证书.我在设置客户端时发出新证书.

在运行时,这些客户端将证书附加到我的服务器的请求.如何以编程方式验证X509Certificate2是否由我的证书颁发机构的根证书签名(并拒绝由任何其他来源签名的证书)?

Chr*_*ard 24

我做了很多.这里有一些你可以使用的简单代码.

if (!isChainValid)块中的部分是发出一个非常错误的消息.如果您不想要,则不必使用它,但如果无法构建链,则应抛出错误.链元素是检查根的必要条件.

X509Certificate2 authority = GetAuthorityCertificate();
X509Certificate2 certificateToValidate = GetCertificateToValidate();

X509Chain chain = new X509Chain();
chain.ChainPolicy.RevocationMode = X509RevocationMode.NoCheck;
chain.ChainPolicy.RevocationFlag = X509RevocationFlag.ExcludeRoot;
chain.ChainPolicy.VerificationFlags = X509VerificationFlags.AllowUnknownCertificateAuthority;
chain.ChainPolicy.VerificationTime = DateTime.Now;
chain.ChainPolicy.UrlRetrievalTimeout = new TimeSpan(0, 0, 0);

// This part is very important. You're adding your known root here.
// It doesn't have to be in the computer store at all. Neither certificates do.
chain.ChainPolicy.ExtraStore.Add(authority);

bool isChainValid = chain.Build(certificateToValidate);

if (!isChainValid)
{
    string[] errors = chain.ChainStatus
        .Select(x => String.Format("{0} ({1})", x.StatusInformation.Trim(), x.Status))
        .ToArray();
    string certificateErrorsString = "Unknown errors.";

    if (errors != null && errors.Length > 0)
    {
        certificateErrorsString = String.Join(", ", errors);
    }

    throw new Exception("Trust chain did not complete to the known authority anchor. Errors: " + certificateErrorsString);
}

// This piece makes sure it actually matches your known root
var valid = chain.ChainElements
    .Cast<X509ChainElement>()
    .Any(x => x.Certificate.Thumbprint == authority.Thumbprint);

if (!valid)
{
    throw new Exception("Trust chain did not complete to the known authority anchor. Thumbprints did not match.");
}
Run Code Online (Sandbox Code Playgroud)