runliuv

runliuv@cnblogs

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

 

public static X509Certificate2 GetCertificate(string commonName, StoreName storeName)
        {
            X509Certificate2 certificate = null;

            // Look for a certificate in the local machine store.
            // We will search for a certificate that has a CN (common name) that matches
            // the currently logged-in user.
            using (var store = new X509Store(storeName, StoreLocation.LocalMachine))
            {
                store.Open(OpenFlags.ReadOnly);
                foreach (var cert in store.Certificates)
                {
                    var subjectNames = cert.SubjectName.Name.Split(',');
                    foreach (var subjectName in subjectNames)
                    {
                        if (subjectName.Equals($"CN={commonName}"))
                        { certificate = cert;
                            break;
                        }
                    }

                    if (certificate != null)
                    {
                        break;
                    }
                }
            }

            return certificate;
        }

使用:

X509Certificate2 clientCer = CertUtil.GetCertificate("SIZZZ", StoreName.My);

if (clientCer == null)
{
     clientCer = CertUtil.GetCertificate("SIZZZ", StoreName.Root);
}

 

posted on 2021-01-20 10:44  runliuv  阅读(362)  评论(0编辑  收藏  举报