我有一个Windows证书颁发机构,我用它通过.net / c#发出客户端身份验证证书。通过COM调用证书颁发机构的API,我已经能够成功地以编程方式颁发证书。我在设置客户端时发出新证书。
在运行时,这些客户端将证书附加到我的服务器的请求。如何以编程方式验证X509Certificate2是否由我的证书颁发机构的根证书签名(并拒绝由任何其他来源签名的证书)?
答案 0 :(得分:20)
我已经做了很多很多。这里有一些你可以使用的简单代码。
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.");
}
答案 1 :(得分:0)
如果您说您拥有 root (自签名)证书,那么您唯一的选择就是在服务器上保留此根证书(当然没有私钥)并执行针对根证书的证书验证过程。这是Web客户端验证服务器证书链的镜像情况。
答案 2 :(得分:0)
您还可以使用Verify()
的内置方法X509Certificate2
。
X509Certificate2 certificateToValidate = GetCertificateToValidate();
bool valid = certificateToValidate.Verify()