我需要验证证书(X509Certificate2),其验证方式与在用于通信之前验证的方式相同。
在这种情况下,X509Certificate2.Verify() 将在证书未颁发给安装它的服务器时返回 true。
是否有任何完成的代码块可以对 X509 证书进行全面验证?
问候
编辑:这是我尝试过的代码:
var certificate = GetServerCertificate(CertificateStore,CertificateLocation,Thumbprint);
if(certificate != null)
{
if(certificate.Verify())
_logger.Log(NLog.LogLevel.Info, $"Yes");
else
_logger.Log(NLog.LogLevel.Info, $"No");
}
最佳答案
The X509Certificate2.Verify() will in this case return true while the certificate is not issued to the server it is installed on.
Verify
方法不检查有关主机名的任何内容。它验证了它完全等于
using (X509Chain chain = new X509Chain())
{
// Use the default vales of chain.ChainPolicy including:
// RevocationMode = X509RevocationMode.Online
// RevocationFlag = X509RevocationFlag.ExcludeRoot
// VerificationFlags = X509VerificationFlags.NoFlag
// VerificationTime = DateTime.Now
// UrlRetrievalTimeout = new TimeSpan(0, 0, 0)
bool verified = chain.Build(cert);
for (int i = 0; i < chain.ChainElements.Count; i++)
{
chain.ChainElements[i].Certificate.Dispose();
}
return verified;
}
Is there any finished code block to do a full validation of the X509 certificate?
如果“完全验证”只是意味着所有的东西
Verify
确实如此,那么是的。如果您还关心它是否可用作 TLS 客户端证书(或 TLS 服务器证书),那么您将使用更长的形式(直接使用 X509Chain)并在调用 chain.Build 之前添加应用程序策略要求:// See if it's valid as a TLS server
chain.ChainPolicy.ApplicationPolicy.Add(new Oid("1.3.6.1.5.5.7.3.1"));
// Alternatively, if it's valid as a TLS client
chain.ChainPolicy.ApplicationPolicy.Add(new Oid("1.3.6.1.5.5.7.3.2"));
主机名更难。客户端证书没有可验证的名称,这取决于服务器对其的处理方式。服务器证书具有与 SAN/Subject-CN 匹配的主机名,但除了与 TLS (
SslStream
) 连接之外,没有任何内置功能可以检查。
关于c# - 如何完全验证 X509 证书?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60109454/