Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get List of Certificate Store Names in C#

I am able to get certificate collection in particulaer store by using the following statment.

X509Store.Certificates

But not sure how I can get the list of certificate store names present under current user or local machine. I also checked the StoreName enumeration but it only lists the standard store names but not the ones defined by the user.

I want the list of CERTIFICATE STORES, not the list of certificates in the particular store.

like image 909
Imran Avatar asked Oct 27 '10 19:10

Imran


3 Answers

http://msdn.microsoft.com/en-us/library/aa376058(VS.85).aspx

Don't think there's a managed .net way of doing this. Possibly the closest may be to use .net's registry functions to read the store names from the registry?

like image 69
dotalchemy Avatar answered Sep 22 '22 13:09

dotalchemy


You can invoke Powershell script from C# code. Here is an sample function (You need to add in project a reference to System.Management.Automation assembly) which returns a list of certificate stores for LocalMachine:

    private static String[] GetLocalMachineStoresNames()
    {
        List<String> names;

        using (RunspaceInvoke runtimeInvoke = new RunspaceInvoke())
        {

            Collection<PSObject> results = runtimeInvoke.Invoke(@" cd cert:\LocalMachine; dir | % { $_.Name }");

            names = new List<String>();

            for (Int32 q = 0; q < results.Count; q++)
            {
                names.Add(results[q].BaseObject.ToString());
            }
        }

        return names.ToArray();
    }
like image 44
sk_ra Avatar answered Sep 22 '22 13:09

sk_ra


As dotalchemy mentioned, you have to read the names from the registry. Check out the following site for locations: https://msdn.microsoft.com/en-us/library/windows/desktop/aa388136(v=vs.85).aspx

For example the CERT_SYSTEM_STORE_LOCAL_MACHINE is located at

HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\SystemCertificates

Here's how to get the names/stores

using (var rootKeySystemCertificates = Microsoft.Win32.Registry.LocalMachine.OpenSubKey("SOFTWARE\\Microsoft\\SystemCertificates", false))
{
    foreach (var subKeyName in rootKeySystemCertificates.GetSubKeyNames())
    {
        var store = new X509Store(subKeyName, StoreLocation.LocalMachine);
        store.Open(OpenFlags.ReadOnly);
        //your part with store.Certificates...
        store.Close();
    }
}
like image 2
pr0gg3r Avatar answered Sep 24 '22 13:09

pr0gg3r