我需要通过序列号获得一个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];我在这里做错什么了?
发布于 2013-08-21 12:53:16
您要查找的证书序列号中似乎有两个不可见字符,这就是它们不匹配的原因。如果将foreach循环中的输出更改为:
System.Web.HttpContext.Current.Response.Write (string.Format("{0} (Length: {1}) = {2} (Length: {3})<br/>", cert.SerialNumber, cert.SerialNumber.Length oauthCertificateFindValue, oauthCertificateFindValue.Length);您很可能会看到这些值看起来是相同的,但是它们的长度不同(表示这些不可见字符的存在)。
您需要更新搜索值,以匹配证书的序列号,包括不可见字符。
发布于 2013-08-21 12:17:34
您打开的第一个X509Store尚未关闭,您试图从该中获取已经读取的证书。
首先,在匹配序列化和从存储中读取的代码中关闭存储,然后重新打开存储。
下面的代码对我有用。只要确认一次。
private static void CompareCertSerialse()
{
string oauthCertificateFindValue = "7C00001851CBFF5E9F563E236F000000001851";
X509Store store = new X509Store(StoreName.My, StoreLocation.LocalMachine);
store.Open(OpenFlags.ReadOnly);
foreach (X509Certificate2 cert in store.Certificates)
{
Console.WriteLine(cert.SerialNumber + "=" + oauthCertificateFindValue);
if (cert.SerialNumber == oauthCertificateFindValue)
{
Console.WriteLine("FOUND FOUND FOUND>");
//Close the store
store.Close();
GetCert(oauthCertificateFindValue);
}
}
}
private static X509Certificate2 GetCert(string oauthCertificateFindValue)
{
//Reopen the store
X509Store store = new X509Store(StoreName.My, StoreLocation.LocalMachine);
store.Open(OpenFlags.ReadOnly);
X509Certificate2Collection certificateCollection = store.Certificates.Find(X509FindType.FindBySerialNumber, oauthCertificateFindValue, false);
if (certificateCollection.Count == 0)
{
Console.WriteLine("Nothing Found");
}
return certificateCollection[0];
}https://stackoverflow.com/questions/18356362
复制相似问题