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