Symmetric Key Encryption/Decryption using advapi32.dll - how to retrieve a key handle from an HSM

  • 9 years ago

    I'm am trying to use the cryptographic function within the advapi32.dll to perform symmetric encryption/decryption using an AES key.  The issue I am having is that the AES key is required to be stored on a LunaPCI HSM and I am having trouble obtaining a handle to the key to then perform the encrypt/decrypt. 

    My first question really is can this be achieved?  I am led to believe the storing/retrieval o symmetric keys cannot be done via the MS CAPI hence I am going down this path.

    I have the LunaPCI card installed and have registered it in the registry as a CSP.

    Using the following code I a "True" from the CryptAcquireContext() method - so I am connection to the CSP ok and default key container.  The problem is I do not seem to be able to get a handle to a key?  There doesn't seem to be a method available to get a symmetric key - am I missing something here?

    Any help here would be much appreciated.



    using System;
    using System.Collections.Generic;
    using System.Text;
    using System.IO;
    using System.Security.Cryptography;
    using System.Runtime.InteropServices;

    using Microsoft.Practices.EnterpriseLibrary.Common.Configuration;
    using Microsoft.Practices.EnterpriseLibrary.Security.Cryptography;
    using Microsoft.Practices.EnterpriseLibrary.Security.Cryptography.Configuration;

    namespace URUPlay
        class Program
            [DllImport("advapi32.dll", CharSet = CharSet.Auto)]
            [return: MarshalAs(UnmanagedType.Bool)]
            private static extern bool CryptAcquireContext(
                ref IntPtr hProv,
                string pszContainer,
                string pszProvider,
                uint dwProvType,
                uint dwFlags);

            [return: MarshalAs(UnmanagedType.Bool)]
            internal static extern bool CryptEncrypt(
                IntPtr hKey,
                int hHash,
                int Final,
                int dwFlags,
                byte[] pbData,
                ref int pdwDataLen,
                int dwBufLen);

            [DllImport(@"advapi32.dll", SetLastError = true)]
            [return: MarshalAs(UnmanagedType.Bool)]
            internal static extern bool CryptDecrypt(
                IntPtr hKey,
                int hHash,
                int Final,
                int dwFlags,
                byte[] pbData,
                ref int pdwDataLen);

            [return: MarshalAs(UnmanagedType.Bool)]
            internal static extern bool CryptReleaseContext(
                IntPtr hProv,
                int dwFlags);

            [DllImport(@"advapi32.dll", EntryPoint = "CryptGetUserKey", CharSet = CharSet.Ansi)]
            [return: MarshalAs(UnmanagedType.Bool)]
            internal static extern bool CryptGetUserKey(
                IntPtr hProv,
                int dwKeySpec,
                ref IntPtr phUserKey);

            static void Main(string[] args)

                    string text = "1234567891234567";
                    System.Console.WriteLine("Raw Text = [{0}]", text);
                    string enc = Encrypt(text);
                    System.Console.WriteLine("Encrpyted Text = [{0}]", enc);
                    //string dec = Decrypt(enc);
                    //System.Console.WriteLine("Decrypted Text = [{0}]", dec);
                catch (Exception e)
                    System.Console.WriteLine("error [{0}]", e.Message);
                    System.Console.WriteLine("Stack Trace [{0}]", e.StackTrace);


            static string Encrypt(string text)
                IntPtr hProv = IntPtr.Zero;
                IntPtr hKey = IntPtr.Zero;
                string passphrase = "";

                uint PROV_RSA_FULL = 1;
                uint CRYPT_VERIFYCONTEXT = 0xf0000000;
                uint CRYPT_NEWKEYSET = 0x8;

                byte[] data = Encoding.UTF8.GetBytes(text);
                uint dataLength = (uint)data.Length;
                uint bufLength = (uint)data.Length;
                bool status = Program.CryptAcquireContext(ref hProv, null, "Luna Cryptographic Services for Microsoft

    Windows",  1, CRYPT_VERIFYCONTEXT);
         // This returns True
                System.Console.WriteLine("Acquire Context Status = [{0}]", status);

         // This line doesn't work - how would I get a handle to Key "5" from the HSM?
                status = Program.CryptGetUserKey(hProv, 7, ref hKey);
                System.Console.WriteLine("Get Key Status = [{0}]", status);

                // First Parameter Here - I need the key!!!

                CryptReleaseContext(hProv, 0);

                return "";

            static string Decrypt(string text)
                return "";

  • 6 years ago

    Hi RodTodd,

    I have the same problem, So if you can help me,it will be greatfull.


Post a reply

Enter your message below

Sign in or Join us (it's free).


Why not write for us? Or you could submit an event or a user group in your area. Alternatively just tell us what you think!

Our tools

We've got automatic conversion tools to convert C# to VB.NET, VB.NET to C#. Also you can compress javascript and compress css and generate sql connection strings.

“I have always wished for my computer to be as easy to use as my telephone; my wish has come true because I can no longer figure out how to use my telephone” - Bjarne Stroustrup