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
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using System.Security.Principal;
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;
}
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