1

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]);
jariq
  • 11,681
  • 3
  • 33
  • 52
  • Take a look on my answer about Pkcs11X509store: https://stackoverflow.com/a/72376132/1382345 It provides code to retrieve a X509Certificate2 from a Pkcs11 capable device – Noman_1 May 25 '22 at 13:59

1 Answers1

0

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?

jariq
  • 11,681
  • 3
  • 33
  • 52
  • I recently come across this PKCS11 interop .Before that my prototype is based on the lowlevel api . I just started replacing them with the highlevel api .But in both cases it returns a IntPtr . I try to copy the contents to a byte[] and try to use that to initialize X509Certifcate .But i get error. "Byte Array cannot be converted to X509Certificate" – Sandeep Srinivas Indraganti Apr 11 '17 at 01:17