我需要通过序列号获得 X509 证书,我有序列号,我正在遍历它们,我在我需要的集合中看到了序列号,但从未找到。
这是我的调试代码,只是为了确保我看到正确的序列号:
X509Store store = new X509Store(StoreName.My, StoreLocation.LocalMachine);
store.Open(OpenFlags.ReadOnly);
foreach (X509Certificate2 cert in store.Certificates)
{
System.Web.HttpContext.Current.Response.Write (cert.SerialNumber + "=" + oauthCertificateFindValue + "<br/>");
if (cert.SerialNumber == oauthCertificateFindValue)
{
System.Web.HttpContext.Current.Response.Write("<br/>FOUND FOUND FOUND<br/>");
}
}
这是这段代码的输出:
0091ED5F0CAED6AD52=0091ED5F0CAED6AD52
3D3233116A894CB244DB359DF99E7862=0091ED5F0CAED6AD52
很明显,我循环的第一个匹配序列号,但 if
总是失败,我真正需要根据这个序列号工作的也失败了:
X509Certificate2Collection certificateCollection = store.Certificates.Find(x509FindType, oauthCertificateFindValue, false);
if (certificateCollection.Count == 0)
{
throw new ApplicationException(string.Format("An OAuth certificate matching the X509FindType '{0}' and Value '{1}' cannot be found in the local certificate store.", oauthCertificateFindType, oauthCertificateFindValue));
}
return certificateCollection[0];
我在这里做错了什么?
最佳答案
您要查找的证书的证书序列号中似乎有两个不可见字符,这就是它们不匹配的原因。如果您将 foreach
循环的输出更改为:
System.Web.HttpContext.Current.Response.Write (string.Format("{0} (Length: {1}) = {2} (Length: {3})<br/>", cert.SerialNumber, cert.SerialNumber.Length oauthCertificateFindValue, oauthCertificateFindValue.Length);
您很可能会看到这些值看起来相同,但它们的长度不同(表明存在这些不可见字符)。
您需要更新搜索值以匹配证书的序列号,包括不可见字符。
关于c# - X509 商店无法通过序列号找到证书,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18356362/