How to export EC private key as PKCS#1 or PKCS#8 format from certificate store by CNG?

二次信任 提交于 2020-04-18 05:47:56

问题


I tried to export private key from certificate store by CNG API. It work fine when export RSA private key, but failed in EC private key.

The code failed in NCryptExportKey() with 0x80090029.

Is there any document from MS said: Export EC private key not support? or any sample code?

Here is my code:

    NCRYPT_KEY_HANDLE       hKey = NULL;
    SECURITY_STATUS         secStatus = ERROR_SUCCESS;
    NTSTATUS                status = STATUS_UNSUCCESSFUL;
    DWORD                   dwKeySpec, cbData = 0, cbBlob = 0, KeyPolicy = 0;
    PBYTE                   pbHash = NULL, pbBlob = NULL;
    PCCERT_CONTEXT          pSignerCert = NULL;
    unsigned char           *MessagePrivKey;
    Struct_Return ExportMessage = { NULL, 0 };
    bool bStatus;

    pSignerCert = GetCert(MY_CERT_NAME);

    if (!CryptAcquireCertificatePrivateKey(
        pSignerCert,
        CRYPT_ACQUIRE_ONLY_NCRYPT_KEY_FLAG,
        NULL,
        &hKey,
        &dwKeySpec,
        NULL))
    {
        goto End;
    }

    if (FAILED(secStatus = NCryptExportKey(
        hKey,
        NULL,
        NCRYPT_PKCS8_PRIVATE_KEY_BLOB,
        NULL,
        NULL,
        0,
        &cbBlob,
        0)))
    {
        wprintf(L"**** Error 0x%x returned by NCryptExportKey\n", secStatus);
        goto End;
    }

    pbBlob = (PBYTE)HeapAlloc(GetProcessHeap(), 0, cbBlob);
    if (NULL == pbBlob)
    {
        wprintf(L"**** memory allocation failed\n");
        goto End;
    }


    if (FAILED(secStatus = NCryptExportKey(
        hKey,
        NULL,
        NCRYPT_PKCS8_PRIVATE_KEY_BLOB,
        NULL,
        pbBlob,
        cbBlob,
        &cbBlob,
        0)))
    {
        wprintf(L"**** Error 0x%x returned by NCryptExportKey\n", secStatus);
        goto End;
    }

I also tried to call NCryptSetProperty() before export, but it failed with 0x8009000b.

KeyPolicy =  NCRYPT_ALLOW_PLAINTEXT_EXPORT_FLAG | NCRYPT_ALLOW_EXPORT_FLAG;

    if (FAILED(secStatus = NCryptSetProperty(
        hKey,
        NCRYPT_EXPORT_POLICY_PROPERTY,
        (PBYTE)&KeyPolicy,
        sizeof(KeyPolicy),
        NCRYPT_PERSIST_FLAG)))
    {
        wprintf(L"**** Error 0x%x returned by NCryptSetProperty\n", secStatus);
        goto End;
    }

来源:https://stackoverflow.com/questions/61073106/how-to-export-ec-private-key-as-pkcs1-or-pkcs8-format-from-certificate-store-b

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!