CryptImportKey返回“提供商的错误版本”。错误

时间:2013-09-05 05:03:46

标签: c++ rsa cryptoapi

我通过makecert.exe创建证书和私钥文件 使用以下命令

makecert.exe -n“CN = test”-pe -ss my -sr LocalMachine -sky exchange -m 96 -a sha1 -len 2048 -r test.cer -sv test.pvk

我有一个test.pvk文件

现在我想在我的程序中使用私钥

CryptImportKey函数返回“提供程序的错误版本”。错误

#include "stdafx.h"
#include "windows.h"
#include "tchar.h"

#include <wincrypt.h>
#include <cryptuiapi.h>

#pragma comment (lib, "crypt32.lib")
#pragma comment (lib, "cryptui.lib")

int _tmain(int argc, _TCHAR* argv[])
{   
    HANDLE hPrivateKeyFile; 

    HCRYPTPROV hCryptProv;
    HCRYPTKEY hKey;

    BYTE* pbPublicKey ;
    BYTE* pbPrivateKey;

    DWORD dwPublicKeyLen ;
    DWORD dwPrivateKeyLen;

    WCHAR* strFileName=L"test.pvk";

    // Open private key file    
    if ((hPrivateKeyFile = CreateFile(strFileName,GENERIC_READ,FILE_SHARE_READ,NULL,OPEN_EXISTING,FILE_FLAG_SEQUENTIAL_SCAN,NULL)) == INVALID_HANDLE_VALUE)
    {         
          printf(("CreateFile error 0x%x\n")); exit(0);       
    }

    // Get file size    
    if ((dwPrivateKeyLen = GetFileSize(hPrivateKeyFile, NULL)) == INVALID_FILE_SIZE)
    {   
          printf(("GetFileSize error 0x%x\n")); exit(0);               
    }

    // Create a buffer for the private key  
    if (!(pbPrivateKey = (BYTE *)malloc(dwPrivateKeyLen)))
    {         
          printf(("malloc error 0x%x\n"));  exit(0);          
    }

    // Read private key 
    if (!ReadFile(hPrivateKeyFile, pbPrivateKey, dwPrivateKeyLen, &dwPrivateKeyLen, NULL))
    {         
          printf(("ReadFile error 0x%x\n")); exit(0);          
    }

    if (!CryptAcquireContext(&hCryptProv, NULL, NULL, PROV_RSA_FULL, 0)) 
    {          
          printf(("CryptAcquireContext error 0x%x\n")); exit(0);      
    }

    // Import private key   
    if (!CryptImportKey(hCryptProv, pbPrivateKey, dwPrivateKeyLen, 0, CRYPT_EXPORTABLE, &hKey))
    {         
          printf(("CryptImportKey error 0x%x\n"));  
          DWORD lastError=GetLastError();//Bad Version of provider.
          exit(0);              
    }


    return 0;
}

1 个答案:

答案 0 :(得分:0)

  • 在CryptAcquireContext中,将最后一个参数更改为CRYPT_NEWKEYSET | CRYPT_VERIFYCONTEXT

  • 检查hCryptProv的返回值。它应该是非szero。 CryptAcquireContext可以返回TRUE,同时将hCryptProv设置为零。