I wanted to blog about using C# with pkcs11 on SafeNet ProtectServer HSM for your encryption need. The library I intent to use is the Pkcs11 Interop library on GitHub.
To being with we need to understand what an HSM is? In wikipedia we find this definition.

A hardware security module (HSM) is a physical computing device that safeguards and manages digital keys for strong authentication and provides cryptoprocessing. These modules traditionally come in the form of a plug-in card or an external device that attaches directly to a computer or network server.

So how does an HSM really look like? Its just like a Pizza box that you see for other servers like below the Gemalto ProtectServer HSM.

protectserverhsm

protectserverhsm

Getting Started

In order to use the Gemalto ProtectServer HSM you first need to download the Driver. Unfortunately it is not distributed publicly so you need to have an account to download the driver and software related to it. Trust me I work for Gemalto and had to create a customer account in order to download it.
Assuming that you have the driver and have installed you should have most of your software located at C:\Program Files\SafeNet\Protect Toolkit 5
In our application we will be using a Network HSM, in order to use an Network HSM you need to execute the command of SetMode.cmd

One will have to choose the Network Mode, remember to enter the ip address of the HSM in your registry key. ET_HSM_NETCLIENT_SERVERLIST, needs to have the ip or ip address of the machines you plan to connect.

One can then use KMU (a java program) or ctbrowse.exe (a native windows application) to view the HSM.

Tools

Here is the Java Program to use to create keys and manage HSM etc

kmu

kmu

Another application that one can use to create keys and manage the HSM.

ctbrowse

ctbrowse

Now lets use the tool to create the key we want, I will use the KMU tool for this and create an AES key labelled as demokey, note there are attributes for the key and I have generated it into a Slot that I plan to use. HSM are divided into Slots that one can use.

generatekey_aes

generatekey_aes

C# PKCS11 on SafeNet ProtectServer HSM

Now we can finally get into the code we will use the interop library one can install using nuget.

PM> Install-Package Pkcs11Interop

Summary

In the above example we have encrypted hello world with our demo key and also decrypted it using C# with the Interop library. The key never gets into your code since the HSM is the one which encrypts it.