Wednesday, 4 September 2013

CryptImportKey return "Bad Version of provider." error

CryptImportKey return "Bad Version of provider." error

i crate a certificate and private key file by makecert.exe with below command
makecert.exe -n "CN=test" -pe -ss my -sr LocalMachine -sky exchange -m 96
-a sha1 -len 2048 -r test.cer -sv test.pvk
and i have a test.pvk file
now i want use private key in my program
CryptImportKey function return "Bad Version of provider." error
#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;
}

No comments:

Post a Comment