Search code examples
c#cryptographypkcs#11pkcs11interop

Convert PKCS'11 Object handle to X509Certificate Object in C#


How can i convert the Object_Handle which is a ulong returned by C_FindObject to a X509Certificate object in C#. Here is the code .

ulong[] foundObjectIds = new ulong[10];
foundObjectIds[0] = CK_INVALID_HANDLE;
success = PKCS11CsharpWrapper.C_FindObjects(session, foundObjectIds, Convert.ToUInt64(foundObjectIds.Length), ref foundObjectCount);

Now i have to convert foundObjectIds[0] to a X509Certificate object .

I tried the below way and it doesn't work for me .

IntPtr ptr = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(ulong)));
Marshal.StructureToPtr(foundObjectIds[0], ptr, false);
IntPtr[] arr = new IntPtr[2];
Marshal.Copy(ptr, arr, 0, 1);
X509Certificate2 cert= new X509Certificate2((IntPtr)foundObjectIds[0]);

Solution

  • Object handle cannot be converted to X509Certificate2 object. You need to read the value of CKA_VALUE attribute of the certificate object using C_GetAttributeValue function. CKA_VALUE attribute contains DER encoded certificate which can be passed as byte[] into the constructor of X509Certificate2 class.

    BTW if you are using Pkcs11Interop library then why are you working with LowLevelAPI instead of HighLevelAPI?