Opening Encryption Key Works in Powershell Not in C#

1

I am opening an encryption key stored in an HSM. I have the HSM's client library installed on my machine. If I run the following Windows Powershell snippet:

##Open an existing Key
$keyName = 'foo'
$providername = 'SafeNetProtectApp Key Storage Provider'
$provider = New-Object 'System.Security.Cryptography.CngProvider' -ArgumentList $providername
$key = [System.Security.Cryptography.CngKey]::Open($keyName, $provider)

It works.

If I attempt to compile the following C# snippet:

using System.Security.Cryptography;

namespace SaveSecret
{
    class Program
    {
        static void Main(string[] args)
        {
            System.Console.WriteLine(">>> Starting application <<<");

            string keyName = "foo";
            string providerName = "SafeNetProtectApp Key Storage Provider";
            CngProvider provider = new CngProvider(providerName);
            CngKey key = null;
            key = CngKey.Open(keyName, provider);

            System.Console.Write("[Hit Enter to Continue]");
            System.Console.ReadLine();
        }
    }
}

I get the following exception:

System.Security.Cryptography.CryptographicException
  HResult=0x8009001E
  Message=Provider DLL could not be found.

  Source=System.Core
  StackTrace:
   at System.Security.Cryptography.NCryptNative.OpenStorageProvider(String providerName)
   at System.Security.Cryptography.CngKey.Open(String keyName, CngProvider provider, CngKeyOpenOptions openOptions)
   at System.Security.Cryptography.CngKey.Open(String keyName, CngProvider provider)

I'm confused why I can open the key using the same libraries in Powershell without an issue. On the same machine, if I attempt the action in C#, I get an exception. Can anyone explain why this is happening?

Additional facts...

  • Project doesn't target .NET Core
  • Compiling C# Console App in Visual Studio 2017 Shell
c#
powershell
cng
asked on Stack Overflow Oct 17, 2018 by Adam • edited Oct 18, 2018 by Adam

1 Answer

1

The project I wrote was targeting the wrong processor architecture. The provider library was 64-bit, but my project was targeting 32-bit. I changed my project to target a 64-bit executable, and it worked.

enter image description here

Thanks for the help all!

answered on Stack Overflow Oct 18, 2018 by Adam

User contributions licensed under CC BY-SA 3.0