问题
I tryed to search sertificates in local store by serial with the following code:
X509Store store = new X509Store(StoreName.My, StoreLocation.CurrentUser);
store.Open(OpenFlags.ReadOnly | OpenFlags.OpenExistingOnly);
var certSerial = "18 99 ac c2 1e ed 69 ae"; //copied from Windows Certificates view tool
certSerial = certSerial.Replace(" ", string.Empty).ToUpper();
var foundCerts = store.Certificates.Find(
X509FindType.FindBySerialNumber,
certSerial ,
true);
...And found nothing. However then I looked into that store in Debug mode and coppied the serial of certificate I wanted to find - 1899ACC21EED69AE and changed the certSerial
variable into:
var certSerial = "1899ACC21EED69AE";
it returns me the right certificate. In Debug both variables seems the same - what should I do to make the first code work? I just don't understand why it behaves so.
回答1:
As explain in FindBySerialNumber, the serial number must be in reverse order because it is an integer.
Retype you string in :
var certSerial = "18 99 ac c2 1e ed 69 ae";
When I paste it in my editor I received :
var certSerial = "?18 99 ac c2 1e ed 69 ae";
回答2:
I got this very same problem today and found a different solution:
var store = new X509Store(StoreLocation.CurrentUser);
store.Open(OpenFlags.ReadOnly | OpenFlags.OpenExistingOnly);
var certificates = store.Certificates;
X509Certificate2 match = null;
foreach(var item in certificates)
{
if (item.SerialNumber != null && item.SerialNumber.Equals(serial, StringComparison.InvariantCultureIgnoreCase))
{
match = item;
break;
}
}
If you need only the valid certificates, you can use the Verify method, as sample:
match.Verify()
Looks like the Find method got some culture problem.....
Sorry for my poor english, and hope this helps someone.
来源:https://stackoverflow.com/questions/9076920/c-sharp-certificates-search-why-serial-from-win-view-tool-dont-work