简体   繁体   中英

how to get X509Certificate using Friendly Name rather than Thumbprint?

I have a certificate which having Friendly Name as well and I want to get the certificate using Friendly Name rather than Thumbprint. I don't see any method like FindByFriendlyName... , how to do this?

在此处输入图像描述

 var thumbprint ="f454......"
 var friendlyName = "ASP.NET Core...."    

 X509Certificate2Collection signingCerts = store.Certificates.Find(X509FindType.FindByThumbprint, thumbprint, false);
            X509Certificate2Enumerator enumerator = signingCerts.GetEnumerator();

Built-in search can be done only against static fields, that never change for any given certificate. Friendly name is not static, it can be changed for any single certificate unlimited times. Thus, I would STRONGLY recommend to not rely on cert friendly name. EVER.

you can do manual filtering, by enumerating all certificates and checking for matching certificate, but it is very poor and fragile way.

If you want something that's a stable search value across cert renewals and is easy to read, you might try the subject name (if the cert has a decent subject name, other than localhost or something):

var subject ="org name signing cert......"
var friendlyName = "ASP.NET Core...."    

X509Certificate2Collection signingCerts = store.Certificates.Find(X509FindType.FindBySubjectName, subject, true);
        X509Certificate2Enumerator enumerator = signingCerts.GetEnumerator();

(You probably only want valid/non-expired certs, too, so use true for the last param.)

I have a use case to look up by FriendlyName. The code is below

            //store variable 
            X509Store store;
            //certificate variable 
            X509Certificate2 cert;

            //init store using root and local machine
            store = new X509Store(StoreName.Root, StoreLocation.LocalMachine);
            //open store for read only
            store.Open(OpenFlags.ReadOnly);
            //find cert using linq
            cert = store.Certificates.OfType<X509Certificate2>().FirstOrDefault(x => x.FriendlyName == "cert-friendlyname-here");
            //close store
            store.Close();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM