关于我的企业项目(仅限内联网),我遇到了使用 .net System.Security.Cryptography.X509Certificates
验证证书的问题
第 1 步:创建根证书
使用 makecert
创建根证书并将其安装到 Trusted Root Certification Authorities
makecert -r -pe -n "CN=Test Labs (CA)" -ss CA -sr CurrentUser -a sha256 -cy authority -sky signature -sv TestLabCA.pvk TestLabCA.cer
pvk2pfx -pvk TestLabCA.pvk -spc TestLabCA.cer -pfx TestLabCA.pfx
第 2 步:创建证书并使用根证书对其进行签名
使用makecert
创建一个证书,用根证书签名并安装到Trusted Publishers
makecert -pe -n "CN=Test Labs (SPC)" -a sha256 -cy end -sky signature -ic TestLabCA.cer -iv TestLabCA.pvk -sv TestLabSPC.pvk TestLabSPC.cer
pvk2pfx -pvk TestLabSPC.pvk -spc TestLabSPC.cer -pfx TestLabSPC.pfx
第 3 步:在代码中验证
这是用于验证证书的 C# 代码示例:
X509Certificate2 rootCertificate = new X509Certificate2("TestLabCA.cer");
X509Certificate2 certificate = new X509Certificate2("TestLabSPC.cer");
// will return true
Console.WriteLine("{0}, verified = {1}", rootCertificate.GetName(), rootCertificate.Verify());
// will return false
Console.WriteLine("{0}, verified = {1}", certificate.GetName(), certificate.Verify());
// validate the chain
var chain = new X509Chain();
chain.Build(certificate);
Console.WriteLine("{0}, verified root of chain = {1}", certificate.GetName(), chain.ChainElements[chain.ChainElements.Count-1].Certificate.Verify());
问题:
如果我想验证证书,我是否必须检查链并验证链中的最后一个,假设这是根证书?
有更好的方法吗?
最佳答案
是的,您必须创建信任链。这意味着您必须将其追溯到您信任的证书。这不一定是根证书,但通常信任根证书而不是中间证书。有时您只想允许具有单个证书的单个实体。只要您确定它是正确的证书,您就可以简单地信任该单叶证书,因此“链”将包含一个证书。这方面的一个例子是网络服务有时使用的自签名根证书。
请注意,证书链的验证只是整个证书验证的一部分。您需要确保证书没有被吊销,证书仍然有效(在生效日期和到期日期之间)。有时还有额外的专有规则来验证证书,例如数据库中存在证书 ID - 白名单/黑名单。
关于c# - 在 .Net 中创建和验证 x509 证书,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14863999/