Problems with X509Store Certificates.Find FindByThumbprint

后端 未结 14 2150
醉话见心
醉话见心 2020-12-04 20:56

I\'m having a problem when I use the method X509Store.Certificates.Find

public static X509Certificate2 FromStore(StoreName storeName, 
                  


        
14条回答
  •  孤城傲影
    2020-12-04 21:10

    I took some of the answers here and combined them into a static method that takes care of removing special characters and upper cases everything. Hopefully someone else can use it.

        public static X509Certificate2 GetCertificate(string thumbprint)
        {
            // strip any non-hexadecimal values and make uppercase
            thumbprint = Regex.Replace(thumbprint, @"[^\da-fA-F]", string.Empty).ToUpper();
            var store = new X509Store(StoreName.My, StoreLocation.LocalMachine);
    
            try
            {
                store.Open(OpenFlags.ReadOnly);
    
                var certCollection = store.Certificates;
                var signingCert = certCollection.Find(X509FindType.FindByThumbprint, thumbprint, false);
                if (signingCert.Count == 0)
                {
                    throw new FileNotFoundException(string.Format("Cert with thumbprint: '{0}' not found in local machine cert store.", thumbprint));
                }
    
                return signingCert[0];
            }
            finally
            {
                store.Close();
            }
        }
    

提交回复
热议问题