Search code examples
pkcs#11pkcs11interop

Attempted to read or write protected memory. PKCS11Interop


I am getting Access violation exception in the highlighed line.

Attempted to read or write protected memory. This is often an indication that other memory is corrupt.

I have the certificate on the hsm and the label . I am building my application as x64

public void getCertificateFromHSM(string certLabel) {

    List<ObjectAttribute> objectAttributes = new List<ObjectAttribute>();
    objectAttributes.Add(new ObjectAttribute(CKA.CKA_CLASS, CKO.CKO_CERTIFICATE));
    objectAttributes.Add(new ObjectAttribute(CKA.CKA_LABEL, certLabel));

    **session.FindObjectsInit(objectAttributes);** --Exception from here

    // Get search results
    List<ObjectHandle> foundObjects = session.FindObjects(2);

    // Terminate searching
    session.FindObjectsFinal();


    // Prepare list of empty attributes we want to read
    List<CKA> attributes = new List<CKA>();
    attributes.Add(CKA.CKA_LABEL);
    attributes.Add(CKA.CKA_VALUE);
}                                                                               

I am getting exception from this line session.FindObjectsInit();. I am new to pkcs11.

Any help in this regard is appreciated.

I also tried to build the application as 32 bit by passing the 32bit crypto.dll ,but in that case i am getting exception from this line in PKCS11Interop Net.Pkcs11Interop.LowLevelAPI81.Delegates.InitializeWithGetF‌​unctionList(IntPtr libraryHandle) and the exception is

Value was either too large or too small for a UInt32. OverflowExcepiton was unhandled.


Solution

  • You seem to be using wrong set of HighLevelAPIs. You need to use classes from Net.Pkcs11Interop.HighLevelAPI namespace without any numbers at the end.

    In other words you need to use following line

    using Net.Pkcs11Interop.HighLevelAPI;
    

    in your code instead of

    using Net.Pkcs11Interop.HighLevelAPI81;
    

    See Pkcs11Interop library architecture for more info and you can also take a look at official code samples which are using Net.Pkcs11Interop.HighLevelAPI too.