我正在使用智能卡进行身份验证。
SecurityTokenService(身份验证服务)仅托管在我的机器上。智能卡有一个有效的证书,它的根证书也安装在我机器上的本地计算机存储中。
当我使用 X509Certificate2.Verify
方法来验证我的服务中的证书时,它总是返回 false
。
谁能帮我理解为什么 X509Certificate2.Verify() 方法总是返回 false?
注意:
我使用了 X509Chain
并检查了所有标志 (X509VerificationFlags.AllFlags
)。当我构建 chanin 时,它返回 true
,ChainStatus
为 RevocationStatusUnknown
。
编辑 1:
我观察到,如果我在 Windows 窗体应用程序中编写此代码,X509Certificate2.Verify()
方法会返回 true
。它仅在服务端代码中返回 false
。为什么这样?奇怪但真实!
最佳答案
X509VerificationFlags 值是抑制项,因此指定 X509VerificationFlags.AllFlags
实际上可以防止 Build 在大多数情况下返回 false。
RevocationStatusUnknown
回应似乎特别相关。无论它报告的是哪个证书,都无法验证是否未被撤销。 Verify
方法可以建模为
public bool Verify()
{
using (X509Chain chain = new X509Chain())
{
// The defaults, but expressing it here for clarity
chain.ChainPolicy.RevocationMode = X509RevocationMode.Online;
chain.ChainPolicy.RevocationFlag = X509RevocationFlag.ExcludeRoot;
chain.ChainPolicy.VerificationTime = DateTime.Now;
chain.ChainPolicy.VerificationFlags = X509VerificationFlags.NoFlag;
return chain.Build(this);
}
}
哪个,因为它没有断言 X509VerificationFlags.IgnoreCertificateAuthorityRevocationUnknown
或 X509VerificationFlags.IgnoreEndRevocationUnknown
在请求 None
以外的 X509RevocationMode 时, 失败。
首先,您应该确定链中的哪些证书失败了:
using (X509Chain chain = new X509Chain())
{
// The defaults, but expressing it here for clarity
chain.ChainPolicy.RevocationMode = X509RevocationMode.Online;
chain.ChainPolicy.RevocationFlag = X509RevocationFlag.ExcludeRoot;
chain.ChainPolicy.VerificationTime = DateTime.Now;
chain.Build(cert);
for (int i = 0; i < chain.ChainElements.Count; i++)
{
X509ChainElement element = chain.ChainElements[i];
if (element.ChainElementStatus.Length != 0)
{
Console.WriteLine($"Error at depth {i}: {element.Certificate.Subject}");
foreach (var status in element.ChainElementStatus)
{
Console.WriteLine($" {status.Status}: {status.StatusInformation}}}");
}
}
}
}
如果您在 Windows CertUI 中查看任何失败的证书(在资源管理器或证书 MMC 管理单元中双击 .cer),请查找名为“CRL 分发点”的字段。这些是将在运行时检索的 URL。也许您的系统有数据导出限制,不允许查询这些特定值。您始终可以尝试从您的 Web 服务发出 Web 请求,以查看它是否可以在不在证书子系统中的情况下获取 URL。
关于c# - X509Certificate2.Verify() 方法始终为有效证书返回 false,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10137208/