static string pkcs11LibraryPath = @"C:\Windows\System32\eTPKCS11.dll";
using (Pkcs11 pkcs11 = new Pkcs11(pkcs11LibraryPath, AppType.SingleThreaded))
{
// Get list of available slots with token present
List<Slot> slots = pkcs11.GetSlotList(SlotsType.WithTokenPresent);
// Find first slot with token present
Slot slot = slots[0];
// Open RO session
using (Session session = slot.OpenSession(SessionType.ReadWrite))
{
session.Login(CKU.CKU_USER, "654321");//HSM:123456
for (int i = 0; i <= slot.GetMechanismList().Count - 1; i++)
{
Console.WriteLine(slot.GetMechanismList()[i].ToString());
}
// Prepare attribute template that defines search criteria
List<ObjectAttribute> objectAttributes = new List<ObjectAttribute>();
//objectAttributes.Add(new ObjectAttribute(CKA.CKA_LABEL, "test"));//HSM:KEY_028_04
objectAttributes.Add(new ObjectAttribute(CKA.CKA_TOKEN, true));
// Initialize searching
session.FindObjectsInit(objectAttributes);
// Get search results
List<ObjectHandle> foundObjects = session.FindObjects(2);
// Terminate searching
session.FindObjectsFinal();
ObjectHandle objectHandle = foundObjects[0];
byte[] iv = Encoding.UTF8.GetBytes("00000000");
byte[] inputData = Encoding.UTF8.GetBytes("data to encrypt.");
Mechanism mechanism = new Mechanism(CKM.CKM_DES3_CBC, iv);;//HSM: CKM_DES3_CBC
byte[] result = session.Encrypt(mechanism, objectHandle, inputData);
Console.WriteLine(Convert.ToBase64String(result));
}
}
I got the error Net.Pkcs11Interop.Common.Pkcs11Exception: 'Method C_EncryptInit returned CKR_KEY_TYPE_INCONSISTENT'
in byte[] result = session.Encrypt(mechanism, objectHandle, inputData);
I am using safenet 5100 etoken could you please help?
It seems you are hitting the most common issue and as a result you are using search template which is too broad. With your search template you'll find all objects that have CKA_TOKEN
set to CK_TRUE
value. That means all certificates, all asymmetric (e.g. RSA) keys, all symmetric keys (e.g. AES), all data objects and all the other stuff that is stored in your device.
You are then using the first found object (RSA key? AES key? no one knows...) with CKM_DES3_CBC
mechanism which requires key of type CKK_DES3
and C_EncryptInit
functions complains that you have provided incorrect type of key by returning CKR_KEY_TYPE_INCONSISTENT
error.
If you want to be sure that you will find just 3DES keys than you need to use more specific search template:
List<ObjectAttribute> objectAttributes = new List<ObjectAttribute>();
objectAttributes.Add(new ObjectAttribute(CKA.CKA_TOKEN, true));
objectAttributes.Add(new ObjectAttribute(CKA.CKA_KEY_TYPE, CKK_DES3));
Even better use CKA_LABEL
and/or CKA_ID
to specify exactly one key that you want to use. And don't forget to read at least "Chapter 2 - Scope", "Chapter 6 - General overview" and "Chapter 10 - Objects" of PKCS#11 v2.20 specification.