Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / C#5.0

Get Certificates from the System Store

4.72/5 (8 votes)
15 Oct 2014CPOL 34.5K  
Retrieve certificates from the system certificate store

Introduction

I was working on some code today that required me to retrieve a file from a secure web site on a CAC (smart card) controlled intranet. I found out how to do it, but developed the following code that turned out to be not needed. There are two methods - one that retrieves certificates for the current user from the system certificate store, another that determines if the specified certificate was retrieved from a smart card, and finally, a method that simply lists all categories of certificates found in the store.

The Code

C#
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using System.Security.Principal;

/// Gets the current user certificates from the x509 store.
public static List<X509Certificate2> GetCurrentUserCertificates()
{
    List<X509Certificate2> certificates = new List<x509certificate2>();
    X509Store store = new X509Store(StoreName.My, StoreLocation.CurrentUser);
    store.Open(OpenFlags.OpenExistingOnly);
    foreach(X509Certificate2 cert in store.Certificates)
    {
        certificates.Add(cert);
    }
    return certificates;
}

/// Determines whether the specified certificate was retrieved from a smart card
public static bool IsFromSmartCard(X509Certificate2 certificate)
{
    bool result = (certificate.HasPrivateKey);
    if (result)
    {
        RSACryptoServiceProvider rsa = certificate.PrivateKey as RSACryptoServiceProvider;
        if (rsa != null && rsa.CspKeyContainerInfo.HardwareDevice)
        {
            result = true;
        }
    }
    return result;
}</x509certificate2>

History

  • 15 Oct 2014 - Initial release

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)