List all Key Storage Providers (CNG) in windows programatically in c#

For legacy cryptographic providers it is quite easy with:


CCspInformations cspInformations = new ();
cspInformations.AddAvailableCsps();

For CNG we need to do it with pinvoke like this:


public struct NCryptProviderName
{
    public IntPtr pszName;
    public IntPtr pszComment;
    
    public string Name()
    {
    	return Marshal.PtrToStringAuto(pszName);
    }
    
    public string Comment()
    {
    	return Marshal.PtrToStringAuto(pszComment);
    }
};

...

[DllImport("Ncrypt.dll")]
public extern static int NCryptEnumStorageProviders(ref int pdwProviderCount, out IntPtr ppProviderList, int dwFlags);
[DllImport("Ncrypt.dll")]
public static extern int NCryptFreeBuffer(IntPtr pvInput);

...

public string[] ListKeyStorageProviders()
{
    int pdwProviderCount = 0;
    
    int res = NCryptEnumStorageProviders(ref pdwProviderCount, out IntPtr ppProviderList, 0);
    
    if (res != 0)
    {
    	return Array.Empty<string>();
    }
    
    List<string> kspList = new ();
    
    IntPtr ppProviderListIdx = ppProviderList;
    
    for (int i = 0; i < pdwProviderCount; i++)
    {
    	NCryptProviderName ncryptProviderName = Marshal.PtrToStructure<NCryptProviderName>(ppProviderListIdx);
        kspList.Add(ncryptProviderName.Name());
        ppProviderListIdx = IntPtr.Add(ppProviderListIdx, Marshal.SizeOf<NCryptProviderName>());
    }
    
    if (pdwProviderCount == 0)
    {
    	return Array.Empty<string>();
    }
    
    NCryptFreeBuffer(ppProviderList);
    
    return kspList.ToArray();
    
}

Post a Comment

Previous Post Next Post