PKCS#11Interop.X509Store unable to find Private Key

627 Views Asked by At

Pkcs11X509Certificate is unable to find the private key in some tokens.

Pkcs11X509Certificate.GetRSAPrivateKey() yields null. Then, when I run SignedXml.ComputeSignature(), I get the following error:

System.Security.Cryptography.CryptographicException: 'Signing key is not loaded.'

1

There are 1 best solutions below

2
Dalmo On

Adding the code below (proof of concept) to the Pkcs11X509Certificate.FindKey works. Basically I removed CKA.CKA_LABEL from the search template attributes and it finds the certificate Private Key.

// Contrary to what PKCS#11 specification suggests, subject of the private key is not readable even after login.
// So if we cannot find private key with subject, we will search for private keys without subject. 
if (keyHandle == null)
{
    searchTemplate = new List<IObjectAttribute>()
    {
        session.Factories.ObjectAttributeFactory.Create(CKA.CKA_CLASS, keyClass),
        session.Factories.ObjectAttributeFactory.Create(CKA.CKA_TOKEN, true),
        session.Factories.ObjectAttributeFactory.Create(CKA.CKA_ID, ckaId),
        //session.Factories.ObjectAttributeFactory.Create(CKA.CKA_LABEL, ckaLabel),
    };

    foreach (IObjectHandle foundObjectHandle in session.FindAllObjects(searchTemplate))
    {
        keyHandle = foundObjectHandle;
        break;
    }
}