C# Certificates search - why serial from Win view Tool don't work

独自空忆成欢 提交于 2019-12-11 10:17:35

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!