我使用以下命令通过 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;
}