我有一个Windows认证机构,我正在使用它通过 .net / c# 发放客户端身份验证证书。我已经成功地通过调用认证机构的API来进行编程, 从而能够发放证书。在设置客户端时,我会发放新的证书。
运行时,这些客户端将证书附加到向我的服务器发送的请求中。如何通过编程验证X509Certificate2是由我的证书颁发机构的根证书签名的(并拒绝由任何其他来源签名的证书)?
我有一个Windows认证机构,我正在使用它通过 .net / c# 发放客户端身份验证证书。我已经成功地通过调用认证机构的API来进行编程, 从而能够发放证书。在设置客户端时,我会发放新的证书。
运行时,这些客户端将证书附加到向我的服务器发送的请求中。如何通过编程验证X509Certificate2是由我的证书颁发机构的根证书签名的(并拒绝由任何其他来源签名的证书)?
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.");
}
chain.ChainElements.Cast<X509ChainElement>().All(x => x.Certificate.Thumbprint != "XX");
- OgglasVerify()
来验证X509Certificate2
。X509Certificate2 certificateToValidate = GetCertificateToValidate();
bool valid = certificateToValidate.Verify()