GithubHelp home page GithubHelp logo

pkcs11interop / pkcs11interop Goto Github PK

View Code? Open in Web Editor NEW
249.0 26.0 87.0 7.8 MB

Managed .NET wrapper for unmanaged PKCS#11 libraries

License: Apache License 2.0

C# 99.62% Batchfile 0.07% Smalltalk 0.17% Shell 0.13%
pkcs pkcs11 security crypto cryptography smartcard hsm

pkcs11interop's Introduction

Pkcs11Interop

Managed .NET wrapper for unmanaged PKCS#11 libraries

License AppVeyor NuGet Stack Overflow Twitter

Table of Contents

Overview

PKCS#11 is cryptography standard maintained by the OASIS PKCS 11 Technical Committee (originally published by RSA Laboratories) that defines ANSI C API to access smart cards and other types of cryptographic hardware.

Pkcs11Interop is managed library written in C# that brings full power of PKCS#11 API to the .NET environment. It loads unmanaged PKCS#11 library provided by the cryptographic device vendor and makes its functions accessible to .NET application.

Following figure presents the typical usage of Pkcs11Interop library in .NET application:

Pkcs11Interop architecture

Pkcs11Interop library:

  • implements .NET wrapper for unmanaged PKCS#11 libraries
  • is compliant with PKCS#11 v2.40 specification and PKCS#11 URI scheme defined in RFC 7512
  • is compatible with .NET Framework 2.0 and higher, .NET Core, Mono and Xamarin
  • is supported on Windows, Linux, Mac OS X, Android and iOS
  • is supported on both 32-bit and 64-bit platforms
  • is open source and completely free for commercial use
  • is used in production by several information security and financial organizations
  • uses 100% managed and fully documented code
  • contains code samples covering all methods of PKCS#11 API

Pkcs11Interop has been confirmed to be working with the following devices:

  • Atos CardOS (former Siemens CardOS) smartcard
  • Thales nShield Solo (former nCipher nShield) HSM
  • SoftHSM (virtual HSM from OpenDNSSEC project)
  • Feitian ePass 2003 token
  • SafeNet ProtectServer HSM
  • SafeNet Luna SA HSM
  • Utimaco CryptoServer HSM
  • Belgian and Slovak eID cards
  • SmartCard-HSM

Documentation

It is highly recommended that before you start using Pkcs11Interop you get familiar at least with "Chapter 2 - Scope", "Chapter 6 - General overview" and "Chapter 10 - Objects" of PKCS#11 v2.20 specification (or equivalent chapters of any previous or subsequent specification version).

Pkcs11Interop API is fully documented with the inline XML documentation that is displayed by the most of the modern IDEs during the application development. Detailed Pkcs11Interop API documentation is also available online.

Following topics are covered by standalone documents:

Download

Archives with the source code and binaries can be downloaded from our releases page. Official NuGet packages are published in nuget.org repository. All official items are signed with GnuPG key or code-signing certificate of Jaroslav Imrich and announced via public mailing list.

License

Pkcs11Interop is available under the terms of the Apache License, Version 2.0.
Human friendly license summary is available at tldrlegal.com but the full license text always prevails.

Support

If you need help please pick one of the options that best suits your needs:

Related projects

  • Pkcs11Admin
    GUI tool for administration of PKCS#11 enabled devices based on Pkcs11Interop library.
  • PKCS11-LOGGER
    PKCS#11 logging proxy module useful for debugging of PKCS#11 enabled applications.
  • SoftHSM2-for-Windows
    Pure software implementation of a cryptographic store accessible through a PKCS#11 interface.

About

Pkcs11Interop has been written by Jaroslav Imrich.
Please visit project website - pkcs11interop.net - for more information.

pkcs11interop's People

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

pkcs11interop's Issues

Error in GetValueAsBool

hi
i have old source of pkcs11 lib, that read my token
today i updated to least version and get error in ReadCertificate method, i debug it and found an inner method in ObjectAttribute.cs in HightLevelApi

public bool GetValueAsBool()
        {
            if (this._disposed)
                throw new ObjectDisposedException(this.GetType().FullName);

            if (Platform.UnmanagedLongSize == 4)
                return (Platform.StructPackingSize == 0) ? _objectAttribute40.GetValueAsBool() : _objectAttribute41.GetValueAsBool();
            else
                return (Platform.StructPackingSize == 0) ? _objectAttribute80.GetValueAsBool() : _objectAttribute81.GetValueAsBool();
        }

that throw error: Unable to convert byte to bool

but my old source that work and read certificate:

public bool GetValueAsBool()
        {
            if (this._disposed)
                throw new ObjectDisposedException(this.GetType().FullName);

            if (UnmanagedLong.Size == 4)
                return _objectAttribute4.GetValueAsBool();
            else
                return _objectAttribute8.GetValueAsBool();
        }

image 2 2

Update:
i found that this method throw eception: public static bool BytesToBool(byte[] value)
in file .\Common\ConvertUtils.cs

i fixed with these codes:

public static bool BytesToBool(byte[] value)
        {
            // Cryptoki uses boolean flag with size of 1 byte
            if ((value == null) || (value.Length != 1))
                value = new byte[] {0};
            
            return BitConverter.ToBoolean(value, 0);
        }

Problem solved. please fix in your source

Exception of "Method C_DeriveKey returned CKR_MECHANISM_INVALID" While trying to Derive ECB Key

I need to derive the Session key for Smart cards using KMCA for External Authentication. KMCA is already defined in HSM.

ObjectHandle DbaseKey = foundObjects[0];

                #region Derive Key


                //ResponseofUI="141114112381F0011411141123810F01";
                //CkKeyDerivationStringData DmechanismParams = new CkKeyDerivationStringData(Utility.ToByteArray(ResponseofIU, System.Globalization.NumberStyles.HexNumber));
                CkKeyDerivationStringData DmechanismParams = new CkKeyDerivationStringData(new byte[] { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 });


                Mechanism Dmech = new Mechanism(CKM.CKM_DES3_ECB_ENCRYPT_DATA, DmechanismParams);
                //Mechanism Dmech = new Mechanism(CKM.CKM_DES3_ECB_ENCRYPT_DATA, new byte[] { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 });

                List<ObjectAttribute> DobjectAttributes = new List<ObjectAttribute>();

                DobjectAttributes.Add(new ObjectAttribute(CKA.CKA_CLASS, CKO.CKO_SECRET_KEY));
                DobjectAttributes.Add(new ObjectAttribute(CKA.CKA_KEY_TYPE, CKK.CKK_DES2));
                DobjectAttributes.Add(new ObjectAttribute(CKA.CKA_PRIVATE, true));
                DobjectAttributes.Add(new ObjectAttribute(CKA.CKA_ENCRYPT, true));
                DobjectAttributes.Add(new ObjectAttribute(CKA.CKA_DERIVE, true));
                DobjectAttributes.Add(new ObjectAttribute(CKA.CKA_WRAP, true));
                DobjectAttributes.Add(new ObjectAttribute(CKA.CKA_VALUE_LEN, 0x10));

                ObjectHandle DderivedKey = session.DeriveKey(Dmech, DbaseKey, DobjectAttributes);
                #endregion

But I am getting an Exception of "{"Method C_DeriveKey returned CKR_MECHANISM_INVALID"}".
Can you please help me to correct this code or also can guide me to use different method.

Create X509 Public key certificate from generated key pair

Hi.
Ive recently started programming with pkcs11interop, the features and examples of this application Is amazing but I cant find an example regarding the subject, which is really necessary for generating a valid ms_word (openxml dsig)signature,
any help on this topic is appreciated. Thanks in advance

kcv with SafeNet hsm

Hi Jariq,
i tryed to get kcv attrib on SafeNet hsm but i read an empty buffer. On Utimaco hsm work fine. Have you some idea about ?

thanks

Key derivation with FIPS mode enabled

Hi all,
I have a Safenet HSM with FIPS Mode enabled. The following code for key derivation does not run .
If the HSM has FIPS mode disable, the code runs and it is possible to derive a key.

Could you help me?
Regards
Ubaldo

ObjectHandle key2DeriveHandle= foundObjects[0];

// Specify mechanism parameters
CkKeyDerivationStringData mechanismParams = new CkKeyDerivationStringData(data);

//Specify derivation mechanism with parameters
Mechanism mechanism = new Mechanism(CKM.CKM_DES_ECB_ENCRYPT_DATA,mechanismParams);
List objectAttributes = new List();
objectAttributes.Add(new ObjectAttribute(CKA.CKA_CLASS, CKO.CKO_SECRET_KEY));
objectAttributes.Add(new ObjectAttribute(CKA.CKA_KEY_TYPE, CKK.CKK_DES2));
objectAttributes.Add(new ObjectAttribute(CKA.CKA_LABEL, derivedKeyName));
objectAttributes.Add(new ObjectAttribute(CKA.CKA_ENCRYPT, true));
objectAttributes.Add(new ObjectAttribute(CKA.CKA_DECRYPT, true));
objectAttributes.Add(new ObjectAttribute(CKA.CKA_EXTRACTABLE, true));
objectAttributes.Add(new ObjectAttribute(CKA.CKA_TOKEN, true));
objectAttributes.Add(new ObjectAttribute(CKA.CKA_MODIFIABLE, true));
objectAttributes.Add(new ObjectAttribute(CKA.CKA_SENSITIVE, true));
objectAttributes.Add(new ObjectAttribute(CKA.CKA_DERIVE,true));

// Derive key
ObjectHandle derivedKey = session.DeriveKey(mechanism, key2DeriveHandle, objectAttributes);

undefined symbol: C_Initialize

When i run test i receive error: "Unable to get function pointer: opensc-pkcs11.so undefined symbol C_Initialize" .
I'm use Fedora 18 64bit.

Retrieve non-expired Private Key(s) from CardOS Card?

Hello there Jaroslav,

I am currently starting to dig into card based data signing / signature generation and the PKI infrastructure here is based on Siemens / Atos CardOS and I was wondering how I could retrieve the currently valid, non-expired private key from a card.

I can log in & create a CKU.CKU_USER session with the correct pin, but I am a bit confused how to retrieve the non-expired, private key(s) for / from the currently plugged in card.

In your test project there's a Helper class that generates a public/private key, but as far as I understand it, those are only temporary and for the purpose of your test-project, right? Or maybe I am missing something here :-/

I.e. I have 6 certificates on my card, and when calling

using (Pkcs11 pkcs11 = new Pkcs11(@"C:\Windows\System32\cardos11_64.dll", true))
{
  // Find first slot with token present
  var slot = pkcs11.GetSlotList(true).FirstOrDefault();

  using (var session = slot.OpenSession(true))
  {
    session.Login(CKU.CKU_USER, "12345678");

    List<ObjectAttribute> keyAttributes = new List<ObjectAttribute>
    {
        new ObjectAttribute(CKA.CKA_TOKEN, true),
        new ObjectAttribute(CKA.CKA_PRIVATE, true),
        new ObjectAttribute(CKA.CKA_SENSITIVE, true),
        new ObjectAttribute(CKA.CKA_SIGN, true)
    };

    var objectHandleForPotentiallyPrivateKeys = session.FindAllObjects(keyAttributes);
  }
}

.. I get 6 handles back - out of those 6 handles/certificates I know 4 are already expired.. so I was wondering how to tell which of those handles correspond to which certificate and how I'd get the private and public key for the other two?

Or maybe I am totally wrong here, but any kind of help / pointer in the right direction would be highly appreciated.

Cheers & thanks,
-Jörg

Support for netstandard1.3 in NuGet package

Hi,

First of all, thanks for this amazing library, it saves me a lot of time, and this code is so far cleaner than other implementation.

However, do you think that you can add support for netstandard 1.3 ? Our team is working in this version for some compatibility reasons, and Pkcs11 is not compatible with it. We don't want to fork the whole projet just for this ...

Thanks !

Pkcs11Interop with cron Job

hello
i use Pkcs11Interop Class with cron Job , that should reads Slots at
specific Time, It's work well jus when one job is define, i mean when
i define more than one job , only one of them execute completly , and
As soon as receive second job , the app is hanged when get this line
of code :
List slots = pkcs11.GetSlotList(true); --> (in Helper class)

public static Slot GetUsableSlot(Pkcs11 pkcs11)
{
// Get list of available slots
List slots = pkcs11.GetSlotList(true);
Assert.IsNotNull(slots);
Assert.IsTrue(slots.Count > 0);
// Let's use first slot with token present
return slots[0];
}
Please Help Me to find The Problem?

Retrieving keys from HSM

Hi may I just ask. Is there a way to extract generated keys from HSM and use it externally? If so, how?
I tried to use generatekey function it returned an object but it is encrypted. Is there a way to get the real key?
Thanks.

Question on Storing PIN as plaintext

Hi Jariq,

One question I want to ask, using this interop means that the user password/PIN is stored in plaintext in the settings/ web config. Granted that the application will be within firewall, but do you foresee a security problem in this?
If so, do you have a suggestion on securing this PIN for login/open session.

Thank you kindly

key Derivation of a TripleDES CBC Key from an existing Key

Hi,
I am trying to derive a TripleDes CBC key from an existing key stored on hsm using the following code (C#)

CkKeyDerivationStringData mechanismParams = new CkKeyDerivationStringData(data);
Mechanism mechanism = new Mechanism(CKM.CKM_DES_CBC_ENCRYPT_DATA,mechanismParams);

List objectAttributes = new List();
objectAttributes.Add(new ObjectAttribute(CKA.CKA_CLASS, CKO.CKO_SECRET_KEY));
objectAttributes.Add(new ObjectAttribute(CKA.CKA_KEY_TYPE, CKK.CKK_DES2));
objectAttributes.Add(new ObjectAttribute(CKA.CKA_LABEL, derivedKeyName));
objectAttributes.Add(new ObjectAttribute(CKA.CKA_ENCRYPT, true));
objectAttributes.Add(new ObjectAttribute(CKA.CKA_DECRYPT, true));
objectAttributes.Add(new ObjectAttribute(CKA.CKA_EXTRACTABLE, true));
objectAttributes.Add(new ObjectAttribute(CKA.CKA_TOKEN, true));
objectAttributes.Add(new ObjectAttribute(CKA.CKA_MODIFIABLE, true));
objectAttributes.Add(new ObjectAttribute(CKA.CKA_SENSITIVE, true));
objectAttributes.Add(new ObjectAttribute(CKA.CKA_DERIVE,true));
ObjectHandle derivedKey = session.DeriveKey(mechanism, key2DeriveHandle, objectAttributes);

But C_Derive function send me an Error message.. Please, the same function with a TripleDesECB algorithm does not send me any error message but build the derivated key on hsm.

is it a bug of api or i have a mistake using the mechanism?

Thank you
Ubaldo

Multithread

Hi Jariq,
i trying to use static methods to recall Pkcs11Interop from other threads.
My approch is http://pastebin.com/AeZP048V
i use only one session for application and use lock of a queue to detect if there are operations active but with a test of 100 thread that perform continuous Des3, after some seconds i have wrong result values generated for some random operations.

GetSlotList returns empty list after accessing X509Certificate2.PrivateKey

Hi,
In my setup, the X509Certificate2 is stored in the server's Local Machine cert store and the keys are stored on a SafeNet HSM.
I downloaded Pkcs11Interop V2.0.1 the other day along with the Pkcs7SignatureGenerator.
I've created a simple WinForms test app to try this component.

When I access the Pkcs11Interop via the Pkcs7SignatureGenerator using the following code without trying to access the signing certificate's private key then a signature is generated as expected.

            using (Pkcs7SignatureGenerator pkcs7SignatureGenerator = new Pkcs7SignatureGenerator(pkcs11Dll, tokenSerial, tokenLabel, pin, keyLabel, keyId, hashAlgorithm))
            {
                X509Certificate2 intermediaryCertificate = CertUtils.LoadIntermediaryCertificate(this.signingCertificate, StoreLocation.LocalMachine);
                X509Certificate2 rootCertificate = CertUtils.LoadRootCertificate(intermediaryCertificate, StoreLocation.LocalMachine);

                List<X509Certificate2> otherCertificates = new List<X509Certificate2>();
                otherCertificates.Add(intermediaryCertificate);
                //Seem to need the root certificate for checking trusted chain even though not included in PKCS7 message signature.
                otherCertificates.Add(rootCertificate);

                // Build certification path for the signing certificate
                ICollection<Org.BouncyCastle.X509.X509Certificate> certPath = CertUtils.BuildCertPath(this.signingCertificate, otherCertificates, false); //Exclude root certificate.

                // Generate detached PKCS#7 signature
                byte[] signedData = pkcs7SignatureGenerator.GenerateSignature(this.dataBytesToSign, true, CertUtils.ToBouncyCastleObject(signingCertificate), certPath);

                response.Tag = Convert.ToBase64String(signedData);
            }

NB. In the above example the Pkcs7SignatureGenerator constructor "keyLabel" and "keyId" parameters are hard-coded but I'd like to derive them via the certificate.

If I run the following code before the Pkcs7SignatureGenerator code, an empty slot list is returned by the Pkcs7SignatureGenerator "FindSlot" method.

        using (System.Security.Cryptography.RSACryptoServiceProvider rsa = (System.Security.Cryptography.RSACryptoServiceProvider)signingCertificate.PrivateKey)
        {
            string containerName = rsa.CspKeyContainerInfo.KeyContainerName;
        }

After running the code through the PKCS11Logger the last 4 lines in the log file are:
0x00003050 : 0x000037c8 : Calling C_Finalize
0x00003050 : 0x000037c8 : Input
0x00003050 : 0x000037c8 : pReserved: 0000000000000000
0x00003050 : 0x000037c8 : Returning 400 (CKR_CRYPTOKI_NOT_INITIALIZED)

I was hoping to use the KeyContainerName to get the private key ID via the Pkcs11Explorer.

It seems odd that accessing the HSM via the certificate's private key causes the Pkcs11Interop to return an empty slot list. It's as if accessing the private key like this opens a session which isn't closed properly.

I then ran a second instance of my test harness which only called the Pkcs7SignatureGenerator and didn't access the certificate private key. This instance worked fine.

Any suggestions for what might be happening would be appreciated.
Let me know if you need any more information.

Many thanks,
Mark

Derive keys with CKM_EXTRACT_KEY_FROM_KEY returns key handle invalid error

Hi,

I am trying to extract DES value from a DES2 key, and I believe I need to use CKM_EXTRACT_KEY_FROM_KEY. But when I put the code:

List<ObjectAttribute> derivedObjectAttributes = new List<ObjectAttribute>();
derivedObjectAttributes.Add(new ObjectAttribute(CKA.CKA_CLASS, CKO.CKO_SECRET_KEY));

derivedObjectAttributes.Add(new ObjectAttribute(CKA.CKA_VALUE_LEN, 0x08));

ObjectHandle derivedKey = null;
Mechanism m = new Mechanism(CKM.CKM_EXTRACT_KEY_FROM_KEY, new CkExtractParams(0x08)))

derivedKey = session.DeriveKey(m, keyHandle, derivedObjectAttributes);

I'm not sure if it's because I don't assign mechanism correctly? Because using the same keyHandle object, I could perform CKM_CONCATENATE_...

Thank you kindly for any suggestion you have.

value len always zero on linux x86_64

Hi Jariq,
i trying to use Pkcs11Interop with Utimaco HSM. I have a problem during read of Objects Attributes. i writted this test code, using it i have right ObjectHandle.ObjectId for each my object but value always empty (i saw that valuelen of LowLevel CkAttributes is zero). Please could you help me

using System;
using System.Collections.Generic;
using Net.Pkcs11Interop.HighLevelAPI;
using Net.Pkcs11Interop.Common;

namespace Pkcs11InteropConsole
{
class MainClass
{
private static Dictionary<uint, Slot> slots = new Dictionary<uint, Slot>();

    public static void Main(string[] args)
    {
        // init pkcs11 utimaco library
        Pkcs11 pkcs11 = new Pkcs11(@"/usr/lib64/libcs2_pkcs11.so", false);

        // Get list of available slots
        List<Slot> slotList = pkcs11.GetSlotList(false);

        // generate slot dictionary
        foreach (Slot slot in slotList)
        {
            // check for slot id already present
            if (!slots.ContainsKey(slot.SlotId))
            {
                Console.WriteLine("ID: " + slot.SlotId.ToString());
                slots.Add(slot.SlotId, slot);
            }
        }

        ParseSlot(slots[0]);

        pkcs11.Dispose();

    }



    private static void ParseSlot(Slot slotObj)
    {
        // open session
        Session session = slotObj.OpenSession(false);

        // login user
        session.Login(CKU.CKU_USER, "<userpin>");

        // get all objects using empty ObjectAttributes list
        List<ObjectHandle> foundObjects = session.FindAllObjects(new List<ObjectAttribute>());

        Console.WriteLine("Objects Founded: " + foundObjects.Count.ToString());

        // set CKA_LABEL to obtain
        List<CKA> attributes = new List<CKA>();
        attributes.Add(CKA.CKA_LABEL);

        // loop for each object founded into selected slot
        foreach (ObjectHandle oh in foundObjects)
        {
            if (oh.ObjectId != 0)
            {
                Console.WriteLine("ObjectHandle: " + oh.ObjectId.ToString("X8"));                        
                List<ObjectAttribute> oAttr = session.GetAttributeValue(oh, attributes);
                Console.WriteLine("TYPE: " + oAttr[0].Type.ToString("X8"));
                Console.WriteLine("VALUE: " + oAttr[0].GetValueAsString());

            }
        }

        // logout close and dispose pkcs11 instance
        session.Logout();
        session.CloseSession();

    }
}

}

Backward compatibility on PKCS v2.10

Hi Jariq,

I want to check since this wrapper is using v2.20 of PKCS 11, some of the mechanism used is different compare to v2.10. I found out that our firmware HSM is still using v2.10 so do you mind telling me if I can use the method with the old mechanism, if so, how?
For example: I want to use C_DeriveKey with mechanism CKM.DES3_DERIVE_ECB, which in v2.20 replaced by CKM_DES3_ENCRYPT_DATA.
When I list down the mechanism using the wrapper, I couldn't see this specific one.

Thank you kindly for any guidance you could give me,

Ratih

Better handling of attempts to load PKCS#11 library with incorrect bitness

Pkcs11Interop 3.1 throws exception with hard to understand message "Unable to load library: %1 is not a valid Win32 application" when there is an attempt to load 32-bit PKCS#11 library in 64-bit runtime or 64-bit PKCS#11 library in 32-bit runtime. This problem seems to be hit quite frequently (e.g. in #25).

Code generating this message was removed in 4e45617 as a side effect of adding support for netstandard1.1 compatible platforms so this message should never appear in the exception again but I still believe such frequent error deserves its own exception type or at least exception message.

ERROR_BAD_EXE_FORMAT error code returned by Marshal.GetLastWin32Error() seems to be a natural choice for detection whether there was an attempt to load PKCS#11 library with incorrect bitness but I am not sure whether the same error code is returned on all supported platforms so I will need to investigate this further and "manually" check the code (or find other solution) on all platforms.

Following table tracks my progress:

Platform Runtime Solution
Windows 10 net20 32-bit GetLastWin32Error() returns 0xC1
Windows 10 net20 64-bit GetLastWin32Error() returns 0xC1
Windows 10 net40 32-bit GetLastWin32Error() returns 0xC1
Windows 10 net40 64-bit GetLastWin32Error() returns 0xC1
Windows 10 sl5 32-bit I can't get it working on 64-bit OS
Windows 10 sl5 64-bit GetLastWin32Error() returns 0xC1
Windows 10 corefx 32-bit GetLastWin32Error() returns 0xC1
Windows 10 corefx 64-bit GetLastWin32Error() returns 0xC1
Linux mono/corefx 5th byte of ELF binary provides architecture info
Mac OS X mono/corefx dlopen_preflight checks if the library architecture is compatible with the current process
Android Xamarin 5th byte of ELF binary provides architecture info
iOS Xamarin PKCS#11 library is linked statically so it cannot be targeting invalid platform

CK.CK_INVALID_HANDLE == 0 == Slotid

Hi
I have converted all the tests to use VS 2010 testing framework as per your instructions.

I am having a problem with test 03 against the highLevel API.

I am getting an ArgumentException (Invalid Handle) at line 64 of Net.Pkcs11Interop.HighLevelAPI::Slot. This checks if the slitId passed in is == to CK_INVALID_HANDLE. As this is being called against slotId=0, and CK_INVALID_HANDLE=0, then the test will always fail.

Am I missing something obvious here, or can this test ever succeed for a slotID of 0?

Cheers

Peter

Work inside new browsers after death of silverlight

hi
it seems that new browsers will discontinue supporting Silverlight
like chrome, Firefox and new Microsoft browser (Edge browser)
according to reports in here: http://superuser.com/questions/748306/what-does-the-removal-of-npapi-plugin-support-mean-to-an-end-user

but we have an application that use this library through Silverlight,
how we can do? for support our project after death of Silverlight?
it there any new way?

will Microsoft support these browsers?

because Microsoft will not support Silverlight
Microsoft explain here (Compatible Operating Systems and Browsers): http://www.microsoft.com/getsilverlight/Get-Started/Install/Default.aspx

** Chrome is supported up to version 41. For support on Chrome 42 and later, see KB3058254.
*** Silverlight is not available in the Microsoft Edge browser, but is supported in Internet Explorer.

Slot return 0 in IIS

hi,
i am trying this library in iis but
List slots = pkcs11.GetSlotList(true)
it return 0 what is the problem?
in local pc it run's fine.

ArgumentException in UnmanagedMemory.cs

I ran into a problem using the GetAttributeValue method in Session.cs. In some cases we have an attribute with no data, for example a CKA.CKA_LABEL with an empty string. When this is encountered an ArgumentException is thrown in UnmanagedMemory.cs in the Allocate method.

This is caused by the following code in Session.cs:

        // Allocate memory for each attribute
        for (int i = 0; i < template.Length; i++)
        {
            if ((int)template[i].valueLen != -1)
                template[i].value = LowLevelAPI.UnmanagedMemory.Allocate((int)template[i].valueLen);
        }

In this case, the valueLen is 0, which causes the exception. I have worked around this by changing the "if" statement to:

            if ((int)template[i].valueLen > 0)

This seems to work OK except that the GetAttributeValue returns a null instead of string.empty.

This can be demonstrated with the following code:

        byte[] ckaId = session.GenerateRandom(20);

        // Prepare attribute template of new public key
        List<ObjectAttribute> publicKeyAttributes = new List<ObjectAttribute>();
        publicKeyAttributes.Add(new ObjectAttribute(CKA.CKA_TOKEN, true));
        publicKeyAttributes.Add(new ObjectAttribute(CKA.CKA_PRIVATE, false));
        publicKeyAttributes.Add(new ObjectAttribute(CKA.CKA_LABEL, "Pkcs11Interop_Test"));
        publicKeyAttributes.Add(new ObjectAttribute(CKA.CKA_ID, ckaId));
        publicKeyAttributes.Add(new ObjectAttribute(CKA.CKA_ENCRYPT, true));
        publicKeyAttributes.Add(new ObjectAttribute(CKA.CKA_VERIFY, true));
        publicKeyAttributes.Add(new ObjectAttribute(CKA.CKA_VERIFY_RECOVER, true));
        publicKeyAttributes.Add(new ObjectAttribute(CKA.CKA_WRAP, true));
        publicKeyAttributes.Add(new ObjectAttribute(CKA.CKA_MODULUS_BITS, 1024));
        publicKeyAttributes.Add(new ObjectAttribute(CKA.CKA_PUBLIC_EXPONENT, new byte[] {0x01, 0x00, 0x01}));

        // Prepare attribute template of new private key
        List<ObjectAttribute> privateKeyAttributes = new List<ObjectAttribute>();
        privateKeyAttributes.Add(new ObjectAttribute(CKA.CKA_TOKEN, true));
        privateKeyAttributes.Add(new ObjectAttribute(CKA.CKA_PRIVATE, true));
        privateKeyAttributes.Add(new ObjectAttribute(CKA.CKA_LABEL, string.Empty));
        privateKeyAttributes.Add(new ObjectAttribute(CKA.CKA_ID, ckaId));
        privateKeyAttributes.Add(new ObjectAttribute(CKA.CKA_SENSITIVE, true));
        privateKeyAttributes.Add(new ObjectAttribute(CKA.CKA_DECRYPT, true));
        privateKeyAttributes.Add(new ObjectAttribute(CKA.CKA_SIGN, true));
        privateKeyAttributes.Add(new ObjectAttribute(CKA.CKA_SIGN_RECOVER, true));
        privateKeyAttributes.Add(new ObjectAttribute(CKA.CKA_UNWRAP, true));

        // Specify key generation mechanism
        Mechanism mechanism = new Mechanism(CKM.CKM_RSA_PKCS_KEY_PAIR_GEN);

        // Generate key pair
        ObjectHandle publicKeyHandle = null;
        ObjectHandle privateKeyHandle = null;
        session.GenerateKeyPair(mechanism, publicKeyAttributes, privateKeyAttributes, out publicKeyHandle,
                                out privateKeyHandle);

        // Prepare list of attributes we want to read
        var attributesToRead = new List<CKA> { CKA.CKA_LABEL };

        // ArgumentException occurs on next line
        IList<ObjectAttribute> objectAttributes = session.GetAttributeValue(privateKeyHandle, attributesToRead);

Thanks

CKH.CKH_MONOTONIC_COUNTER

Hi,

I try Monotonic Counter in c# vs2013,
here the code
------Start Code---------------
using (Session session = slot.OpenSession(false))
{
session.Login(CKU.CKU_USER, Settings.NormalUserPin);
List objectAttributes = new List();
objectAttributes.Add(new ObjectAttribute(CKA.CKA_CLASS, CKO.CKO_HW_FEATURE));
objectAttributes.Add(new ObjectAttribute(CKA.CKA_HW_FEATURE_TYPE, CKH.CKH_MONOTONIC_COUNTER));
objectAttributes.Add(new ObjectAttribute(CKA.CKA_LABEL, @"Counter"));
objectAttributes.Add(new ObjectAttribute(CKA.CKA_VALUE, Counter));
objectAttributes.Add(new ObjectAttribute(CKA.CKA_RESET_ON_INIT, true));
objectAttributes.Add(new ObjectAttribute(CKA.CKA_HAS_RESET, false));
ObjectHandle CounterObj =session.CreateObject(objectAttributes);
------Stop Code---------------

at "objectAttributes.Add(new ObjectAttribute(CKA.CKA_HW_FEATURE_TYPE, CKH.CKH_MONOTONIC_COUNTER));"
I get 2 error,
1->Error 2 Argument 2: cannot convert from 'Net.Pkcs11Interop.Common.CKH' to 'System.Collections.Generic.List<Net.Pkcs11Interop.Common.CKM>'
2->Error 1 The best overloaded method match for 'Net.Pkcs11Interop.HighLevelAPI.ObjectAttribute.ObjectAttribute(Net.Pkcs11Interop.Common.CKA, System.Collections.Generic.List<Net.Pkcs11Interop.Common.CKM>)' has some invalid arguments

any suggest.
Thanks,

Invalid Characters in Token Data

hi
i read hardware token in pkcs11 lib but when display data i see that there is some character in token title
image 4

i think that middle ware of token generate zero byte as empty so, i replace some codes to show token label correctly

info = pkcs11Slot.TokenInfo.Label.SafeReplace("\0",string.Empty),
i test with another brand of token and these error does not exist.
i found that token with brand "mToken K3" has this problem, i think better there is way to show only human readable characters, but i do not know howto do this

_20_SignAndVerifyTest.cs Example problem

Hi all,
I've had problems with the code _20_SignAndVerifyTest.cs. It has broken the sim card informations on my usb token.
Here are some data about my card and library used:

  • library: bit4ipxi.dll or bit4xpki.dll
  • certification authority: InfoCert
  • smart card: Incard
  • n. of certificates on card: 2

I have tried to run that code 4-5 times and It have broken something on my smartcard. I cannot sign documents with other software, except Dike, nor re-execute that code (it throws CKR_GENERAL_ERROR exception on executing GenerateKeyPair method on the session object ).
The problem may be related to the CKA_ID generated in a random way when it calls:

Helpers.GenerateKeyPair(session, out publicKey, out privateKey);

and in that helper class, in the GenerateKeyPair method:

byte[] ckaId = session.GenerateRandom(20);

So it can interfere with some CKA_ID if the two CKA_IDs match.
Another problem may occur if the objects are not destroyed from card (in case of exceptions after the keys generation) and full the memory in it.

I don't know where the bug resides, and unfortunately I cannot provide more information because I had to return back the usb token to the certification authority.
I suggest to use keys from the card and not to generate a new pair. It was done on another project from the same author ( Pkcs7SignatureGenerator ).

Has someone encountered that problem?

Silverlight version

is there plan to run this moudle in silverlight?

i use library and convert as silverlight version but there is some errors and diffrent on someobject that must be cast

any hope for silverlight 5?

Pkcs11Interop and PGP

Hi,

Does anyone have any experience integrating OpenPGP functionality with Pkcs11Interop?

Regards,
Ivan

GenerateKeyPair gives memory corruption exception

When trying to generate new RSA key pair, then the operation is started by the underlying aetpkss1.dll library (seems to be async) with a visual dialogbox from the dll showing that "generating key pair", and at the same moment the pkcs11interop library gives an exeption. The actual generation takes a long time since it's happening on a java card which is slow, but for some reason the function seems to want to move on and doesn't seem to wait the process to finish. The keys are finally generated correctly by the process and are shown when viewed from the SafeSign token admin, although since the exception occurred then i have to re-insert the card to manage it again.

CKR_ENCRYPTED_DATA_INVALID exception cause high CPU usage

Hi Jariq,

I wrote it from Stackoverflow, but I also wanted to write from here.

We are using Pkcs11Interop library for cryptography and we customize&implement Pkcs11Interop code samples for our project where Pkcs11Interop documents. In production, not everyday but we have to restart server after CPU usage reach maximum when we get an consecutive(4 or 5 times) CKR_ENCRYPTED_DATA_INVALID exception. What cause this ? How can we fix this problem ? If you want I can share our code sample. Thanks for helping.

How to implement extensions

Hello all,

First of all, thank you for providing this good quality library.

The module I am using provides some extended functionality. Is there a way to implement this functionality using Pkcs11Interop?

Kind Regards,

How to get Certificate in Base64

I'm sorry if is a stupid question but i can't find it anywhere in the docs. I want to get certificate as a base64 string from USB Token, how can i get it ?

"Method C_Initialize returned CKR_CANT_LOCK" and problems on Fedora 18 x86_64

Sorry, but i have another problem. When i'm try to use libOpenPGP11 from here http://smartcard-auth.de/download-en.html. Your library return "Unhandled Exception: Net.Pkcs11Interop.HighLevelAPI.Pkcs11Exception: Method C_Initialize returned CKR_CANT_LOCK"
I see here http://jce.iaik.tugraz.at/sic/Products/Core-Crypto-Toolkits/PKCS_11_Provider/FAQs/errors. They said " You can do this by setting the MULTI_THREAD_INIT to false. It is true by default."
Please give me how to set MULTI_THREAD_INIT=false or solve this error.
Thanks,

info about ec key pair generation

Hi Jariq,
i generated some EC KEY PAIRS with brainpool 256 r1 and some private key have len=31 bytes, not 32. I saw that i sould left pad with 0x00 but is there a key attribute or mech parameter to force padding so key len is 32 always ?

i tryed to force VALUE_LEN attribute but on some keys value len is still 31 bytes, seems that hsm generate key not in according with forced VALUE_LEN attributes.

could you help me ?

info on CKA_VALUE on RSA PublicKey

Hi Jariq,
i trying to read public key value from an RSA key pair generated, but i have always CKA_VALUE empty. Instead if i try to generate an EC key pair, i can read public key value.

could be an HSM settings or i miss something ?

Should i consider only CKA_MODULUS as public key value ?
thanks

pkcs11 proxy

Hi Jariq,
i try to use an ARM device (cubietruck with AllWinner A20) for production environment. I have a network hsm that drive from linux x86_64 whit supplier pkcs11 lib that use a public pkcs11 interface but send requests on network vs hsm with private protocol.
To drive this hsm from arm device without supplier libraries i think that could be used a pkcs11 proxy: a pkcs11 server on x86_64 pc that switch request vs real hsm.
What do you think about ?

Export Certificate id and data

Hello.
I was working with your library for a while but it seems that the library is actually not able to export certificates. In this example:

                private static Dictionary<string, X509Certificate2> Certificates = new Dictionary<string, X509Certificate2>();
                List<ObjectAttribute> template = new List<ObjectAttribute>();
                template.Add(new ObjectAttribute(CKA.CKA_CLASS, CKO.CKO_CERTIFICATE));
                template.Add(new ObjectAttribute(CKA.CKA_CERTIFICATE_TYPE, CKC.CKC_X_509));
                List<ObjectHandle> oObjCollection = session.FindAllObjects(template);

                foreach (var item in oObjCollection)
                {
                    var oAttriVal = session.GetAttributeValue(item, new List<CKA>() {CKA.CKA_VALUE}).FirstOrDefault();
                    var oAttriKey = session.GetAttributeValue(item, new List<CKA>() {CKA.CKA_ID}).FirstOrDefault();
                    Certificates[oAttriKey.GetValueAsString()] = new X509Certificate2(oAttriVal.GetValueAsByteArray());
                }

I remember that the Ncryptoki actually used to return certificates as byte array so I could convert them to X509Certificate just by parsing them, but In this case, both oAttriVal and oAttriKey return null, so I'm not able to directly read the certificate and its ID(to retrieve the private key handle with the same ID that is).
But again, this might be an error in my template. :)
So correct me if I'm wrong.

Invalid signature verify on Linux(x64)

Hi
I use my smart card to do a signature, but different results on Windows and Linux.

My environment:

  1. Windows 8(x64) VS 2013 using HighLevelAPI
  2. Ubuntu 16.04(x64) Mono using HighLevelAPI

My signature result:
Source data: "Hello World"
The result on Linux:
A8-EA-22-F6-BE-8E-D3-A4-7F-38-6F-FA-C2-FC-2D-FA-4A-58-77-D6-96-8C-B5-97-BD-90-AF-C7-C0-DF-F4-7B-41-02-EA-9E-72-96-F6-0F-CD-A5-BF-49-53-E0-42-03-15-8D-BA-53-B9-75-B6-B5-9C-D8-A4-2B-69-DC-C6-5E-99-26-FE-0A-1F-D4-D8-78-C1-FC-7A-B7-FC-4D-03-25-AE-87-7E-60-A8-80-9F-81-79-FF-C0-75-C0-5C-61-AE-F8-B9-03-7F-E3-1E-60-81-38-F3-96-52-4D-8A-6C-73-98-10-C9-C9-73-1A-47-90-1D-93-76-D3-13-53-68-7D-08-28-0A-A4-60-9E-FD-49-D5-5E-69-5D-28-A0-50-3A-A8-36-70-5E-4F-3E-93-41-09-61-8F-AD-2B-A0-39-3E-09-49-3C-E8-90-0A-0B-2D-41-C9-F9-50-01-59-FF-C1-1D-C2-B6-21-C6-45-58-40-6F-41-16-58-14-D7-6E-A8-CC-7D-3F-78-C5-BD-51-BF-AF-09-59-2D-E7-82-E9-CE-29-2C-BB-65-9A-2B-2E-83-B9-CE-54-CF-31-2D-76-30-03-3F-2F-7B-E1-DD-99-CC-47-94-15-A3-6E-CF-CA-6A-98-FA-F6-1A-D9-D2-93-E2-91-77-98-EF-25-E7-F7-C4

The result on Windows:
AA-CC-D9-06-A3-1A-15-B6-87-76-23-20-DB-91-00-47-1C-9B-43-63-FA-80-EB-5D-56-78-76-87-57-56-B0-B0-14-29-EB-7D-2D-68-2F-01-3E-8D-80-FF-38-B3-60-09-E9-05-91-78-0B-D6-69-D4-C0-C6-96-D3-B2-BD-E0-F9-BC-F8-A1-C0-82-30-83-5F-E7-28-AC-ED-85-99-82-BE-C9-C7-8F-80-73-76-59-7F-CC-03-B0-36-E2-4F-0F-20-1B-2E-09-A0-A1-D9-93-CD-CC-DE-A1-28-CB-62-BF-D1-85-AA-73-FB-49-08-D1-E2-D2-7A-9C-89-A0-2E-74-99-DA-1E-18-73-36-69-AD-03-E7-FB-0F-D5-AD-80-6F-15-05-11-66-E9-3F-F9-A3-15-5D-CD-67-E7-75-25-DF-70-E3-A1-F5-A9-9E-E9-93-E8-5E-62-5A-33-AA-84-58-95-87-01-0C-EE-89-DD-C1-78-6C-A0-20-2B-57-18-15-97-99-9D-37-51-5D-05-C8-B4-44-11-BD-58-E2-21-9F-DE-F7-0F-57-02-7F-68-25-CF-E7-F0-FE-2A-39-83-8C-B0-3C-4B-DF-24-32-E6-F7-55-49-08-62-F8-CF-B9-A9-50-28-83-86-30-B1-8B-FC-3C-82-FA-49-13-3B-66-85-03

I try to verify the signature by three methods:

  1. Session Verify (HighLevelAPI)
  2. ISigner VerifySignature (BouncyCastle)
  3. RSACryptoServiceProvider VerifyData (System.Security.Cryptography)

Screen shot of verify results below:
On Windows:
image

On Linux:
default

The results of session verify are also different from the others.

Generate strongly named assemblies by default

As I currently see it there are three options when it comes to strong naming open source library:

OPTION 1: Generate single unsigned assembly/package:

  • works in projects that do not require strong naming
  • works in projects that require strong naming
  • easy to maintain

OPTION 2: Generate single signed assembly/package:

  • works in projects that do not require strong naming
  • works in projects that require strong naming
  • easy to maintain (with .snk publicly available in the repository)

OPTION 3: Generate two separate assemblies/packages, one signed and one unsigned:

  • works in projects that do not require strong naming
  • works in projects that require strong naming
  • easy to maintain (doubles the work and may cause issues in projects with complex dependencies)

Historically Pkcs11Interop up to the version 3.3.0 was using OPTION 1 but then in #41 I decided to switch to OPTION 3 because I considered that option to be the least harmful for existing users in that time. Now that we are approaching next major release I am going to switch to OPTION 2 on all platforms that support strong naming.

Self signed certificate

Sorry to bother you again, but this problem was considered a new issue so I had to post it in separate thread.

It seems that in your other project(https://github.com/jariq/Pkcs11Interop.PkiUtils/tree/master/src/Pkcs11Interop.PkiUtils)

You have a template which generates PKCS#10 (To pass it to CA for having it signed)
However it does not provide any example on a self signed certificate.

I wonder, can this method even be achieved using bouncycastle you used for generating pkcs#10, or are there any libraries out there that can delay the certificate signature process and let the application sign the certificate itself?

Thanks in advance.

Pkcs11Interop.PDF

Dear Jaroslav,

first, i would like to appreciate your efforts.

second, i am in a badly need the integration layer between Pkcs11Interop and iTextSharp libraries (Pkcs11Interop.PDF).

can you provide help

Best Regards
rock82egy

Support for Cryptosec PCI V1.1 by Realsec

I tried to use the library with cryptosec HSM but with no hope. Just want to ask if this HSM is supported or not ?
The library they provided with the HSM called "cryptosec.dll"

Find created key tests

Hi.
I have an issue. I create private/public key pair and I need to use them later. I know, that I can find those keys by attributes, but I have a problem with this. Can you provide unit test, that would be mixed those 2 tests:

https://github.com/Pkcs11Interop/Pkcs11Interop/blob/master/src/Pkcs11Interop/Pkcs11InteropTests/HighLevelAPI/_18_GenerateKeyAndKeyPairTest.cs
https://github.com/Pkcs11Interop/Pkcs11Interop/blob/master/src/Pkcs11Interop/Pkcs11InteropTests/HighLevelAPI/_17_ObjectFindingTest.cs

First, generate key pairs, and then use object finding to get them from card.

Kindest regards,
Piotr Rabiniak

Trying to sign a hash like the C# method SignHash

Hi, I'm actually trying to get the same result of the C# RSACSP method "SignHash" in PKCS#11 :

The C# method :

 public static byte[] SignHash(byte[] btHash, string SN)
        {
            string strSignature = string.Empty;
            X509Store x509store = null;
            x509store = new X509Store(StoreLocation.CurrentUser);
            x509store.Open(OpenFlags.ReadOnly);
            byte[] btSignature = null;
            foreach (X509Certificate2 x509 in x509store.Certificates)
            {

                string NomCertif = ToolsNS.Tools.GetCommonName(x509.SubjectName.Name);
                string NomEmetteur = ToolsNS.Tools.GetCommonName(x509.IssuerName.Name);

                if (x509.SerialNumber.ToLower().Contains(SN.ToLower()) ||
                    x509.SerialNumber.Equals(SN,StringComparison.InvariantCultureIgnoreCase))
                {
                    using (RSACryptoServiceProvider key = new RSACryptoServiceProvider())
                    {
                        try
                        {

                            using (RSACryptoServiceProvider rsa = (RSACryptoServiceProvider)x509.PrivateKey)
                            {
                                btSignature = rsa.SignHash(btHash, CryptoConfig.MapNameToOID("SHA256"));
                                return btSignature;
                            }
                        }
                        catch
                        {
                            key.FromXmlString(x509.PrivateKey.ToXmlString(true));
                            btSignature = key.SignHash(btHash, CryptoConfig.MapNameToOID("SHA256"));
                        }

                    }

                }
            }
            return btSignature;

        }

And the PKCS11Interop method I'm trying to make :

public static byte[] SignHash(byte[] btHash, string SN)
        {
            byte[] btResult = null;
            List<Slot> slots = null;
            Pkcs11 pkcs11 = null;
            Session session = null;

            try
            {
                pkcs11 = new Pkcs11(CheminDLL, useOsLocking: false);
                slots = pkcs11.GetSlotList(tokenPresent: true);

                foreach (Slot slot in slots)
                {

                    TokenInfo tokenInfo = null;

                    try
                    {
                        tokenInfo = slot.GetTokenInfo();
                    }
                    catch (Pkcs11Exception ex)
                    {
                        if (ex.RV != CKR.CKR_TOKEN_NOT_RECOGNIZED && ex.RV != CKR.CKR_TOKEN_NOT_PRESENT)
                            throw;
                    }

                    if (tokenInfo == null)
                    {
                        continue;
                    }

                    session = slot.OpenSession(readOnly: false);
                    TokenInfo si = slot.GetTokenInfo();
                    List<ObjectAttribute> searchTemplate = new List<ObjectAttribute>();
                    searchTemplate.Add(new ObjectAttribute(CKA.CKA_CLASS, (uint)CKO.CKO_CERTIFICATE));

                    List<ObjectHandle> certObjectHandles = session.FindAllObjects(searchTemplate);

                    if (certObjectHandles != null)
                    {
                        LogHelper.Debug("Handles trouvés : " + certObjectHandles.Count);
                    }

                    foreach (ObjectHandle certObjectHandle in certObjectHandles)
                    {
                        List<CKA> attributes = new List<CKA>();
                        attributes.Add(CKA.CKA_VALUE);
                        List<ObjectAttribute> objectAttributes = session.GetAttributeValue(certObjectHandle, attributes);
                        byte[] certData = objectAttributes[0].GetValueAsByteArray();

                        string certB64 = Convert.ToBase64String(certData);

                        if (certB64.Equals(SEOHelper.X509Cert))
                        {
                            Mechanism mechanism = new Mechanism(CKM.CKM_RSA_PKCS);

                            objectAttributes = new List<ObjectAttribute>();
                            objectAttributes.Add(new ObjectAttribute(CKA.CKA_CLASS, CKO.CKO_PRIVATE_KEY));
                            List<ObjectHandle> foundObjects = session.FindAllObjects(objectAttributes);
                            ObjectHandle handlePrivateKey = foundObjects[0];
                            btResult = session.Sign(mechanism, handlePrivateKey, btHash);
                            break;
                        } 

                    } // foreach certObjectHandles

                } // foreach slot

            } //try
            finally
            {
                if (slots != null)
                {
                    foreach (Slot slot in slots)
                    {
                        try
                        {
                            slot.CloseAllSessions();
                        }
                        catch
                        {

                        }
                    }
                }
                if (session != null) { try { session.CloseSession(); } catch { } try { session.Dispose(); } catch { } }
                if (pkcs11 != null) { try { pkcs11.Dispose(); } catch { } }
            } // finally

            return btResult;
        }

With the same inputs, the result is different unfortunately. I assume SignHash C# method encrypts the hash with the public key before it's being signed, but I have no certainty. Is there a way to sign a hash with PKCS11Interop that will be equal to the SignHash C# method ?

Thanks in advance

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.