首页 > Windows开发 > 详细

C#.NET 使用Windows证书库中的证书

时间:2021-01-20 13:11:34      阅读:44      评论:0      收藏:0      [点我收藏+]

 

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);
}

 

C#.NET 使用Windows证书库中的证书

原文:https://www.cnblogs.com/runliuv/p/14301623.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!