如何验证证书是由特定的证书颁发机构创建的
本文关键字:证书 创建 机构 何验证 验证 | 更新日期: 2023-09-27 18:00:41
我有一个Windows证书颁发机构,用于通过.net/c#颁发客户端身份验证证书。我通过COM调用证书颁发机构的API,成功地使其以编程方式颁发证书。我在设置客户端时颁发新证书。
在运行时,这些客户端将证书附加到我的服务器请求中。我如何通过编程验证X509Certificate2是否由我的证书颁发机构的根证书签名(并拒绝由任何其他来源签名的证书)?
我已经做了很多了。这里有一些你可以使用的简单代码。
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.");
}
对于X509Certificate2
,您也可以使用内置的方法Verify()
。
X509Certificate2 certificateToValidate = GetCertificateToValidate();
bool valid = certificateToValidate.Verify()
https://msdn.microsoft.com/en-us/library/system.security.cryptography.x509certificates.x509certificate2.verify.aspx
如果你说你有一个根(它是自签名的)证书,那么你唯一的选择就是在你的服务器上保持这个根证书可用(当然没有私钥),并对你的根证书执行证书验证过程。这是web客户端验证服务器证书链的镜像情况。