Как исправить метод C_GenerateKeyPair, возвращенный CKR_FUNCTION_FAILED - PullRequest
1 голос
/ 24 марта 2019

Я пытаюсь использовать библиотеку Pkcs11Interop, чтобы получить свой собственный сертификат от HSM (Safenet inc), когда я сгенерировал открытый / закрытый ключ, я получил ошибку "Метод C_GenerateKeyPair возвратил CKR_FUNCTION_FAILED"

Мой код

if (Net.Pkcs11Interop.Common.Platform.Uses64BitRuntime)
{
    loggerLibraryPath = @"C:\inetpub\wwwroot\ETPkcs11\ETPkcsII\libs\pkcs11-logger-x64.dll";
}
else
{
    loggerLibraryPath = @"C:\inetpub\wwwroot\ETPkcs11\ETPkcsII\libs\pkcs11-logger-x86.dll";
}
System.Environment.SetEnvironmentVariable("PKCS11_LOGGER_LIBRARY_PATH", pkcs11LibraryPath);
System.Environment.SetEnvironmentVariable("PKCS11_LOGGER_LOG_FILE_PATH", loogerLogFilePath);
System.Environment.SetEnvironmentVariable("PKCS11_LOGGER_FLAGS", "64");

if (System.IO.File.Exists(loogerLogFilePath))
{
    System.IO.File.Delete(loogerLogFilePath);
}

using (Pkcs11 pkcs11 = new Pkcs11(loggerLibraryPath, AppType.SingleThreaded))
{
    LibraryInfo libraryInfo = pkcs11.GetInfo();
    var aviSlot = pkcs11.GetSlotList(SlotsType.WithTokenPresent).Where(slot => slot.GetSlotInfo().SlotFlags.TokenPresent).FirstOrDefault();

    using (Session session = aviSlot.OpenSession(SessionType.ReadWrite))
    {
        // Login as normal user
        session.Login(CKU.CKU_USER, "xxxxxxxx");
        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, Settings.ApplicationName));
        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, Settings.ApplicationName));
        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);

        // Do something interesting with generated key pair
        // Destroy keys
        session.DestroyObject(privateKeyHandle);
        session.DestroyObject(publicKeyHandle);

        session.Logout();
    }
}

Вот некоторые из журналов

0x00002478: 0x00001af8: Атрибут 7
0x00002478: 0x00001af8: Атрибут: 265 (CKA_SIGN_RECOVER)
0x00002478: 0x00001af8: pValue: 0597E850
0x00002478: 0x00001af8: ulValueLen: 1
0x00002478: 0x00001af8: * pValue: HEX (01)
0x00002478: 0x00001af8: Атрибут 8
0x00002478: 0x00001af8: Атрибут: 263 (CKA_UNWRAP)
0x00002478: 0x00001af8: pValue: 0597E830
0x00002478: 0x00001af8: ulValueLen: 1
0x00002478: 0x00001af8: p Значение: HEX (01)
0x00002478: 0x00001af8:
Конечный шаблон атрибута *
0x00002478: 0x00001af8: phPublicKey: 0643EA74
0x00002478: 0x00001af8: * phPublicKey: 0
0x00002478: 0x00001af8: phPrivateKey: 0643EA70
0x00002478: 0x00001af8: * phPrivateKey: 0
0x00002478: 0x00001af8: возвращается 6 (CKR_FUNCTION_FAILED)
0x00002478: 0x00001af8: ****************************** 2019-03-22 16:37:32 *
0x00002478: 0x00001af8: вызов C_CloseSession
0x00002478: 0x00001af8: ввод
0x00002478: 0x00001af8: hSession: 2490369
0x00002478: 0x00001af8: Возвращает 0 (CKR_OK)
0x00002478: 0x00001af8: ****************************** 2019-03-22 16:37:32 *

0x00002478: 0x00001af8: вызов C_Finalize
0x00002478: 0x00001af8: ввод
0x00002478: 0x00001af8: p Зарезервировано: 00000000
0x00002478: 0x00001af8: Возвращает 0 (CKR_OK)

1 Ответ

0 голосов
/ 08 апреля 2019

К сожалению, API PKCS # 11 не предоставляет каких-либо подробностей о причине сбоя функции C_GenerateKeyPair, но многие библиотеки PKCS # 11 поддерживают какой-то внутренний механизм ведения журнала, который может выявить реальную причину ошибки.Точные шаги, необходимые для включения ведения журнала, должны присутствовать в документации, предоставленной поставщиком библиотеки PKCS # 11.

...