KJKHyperion在他的回答中说:
我发现了以 PEM 格式导入 RSA 公钥的“神奇”调用序列。干得好:
- 使用CryptStringToBinary将密钥解码为二进制 blob ;在 dwFlags 中传递CRYPT_STRING_BASE64HEADER
- 使用CryptDecodeObjectEx将二进制密钥 blob 解码为 CERT_PUBLIC_KEY_INFO ;通过 dwCertEncodingType 中的 X509_ASN_ENCODING 和lpszStructType中的 X509_PUBLIC_KEY_INFO
- 使用CryptDecodeObjectEx将来自 CERT_PUBLIC_KEY_INFO 的 PublicKey blob 解码为 RSA 密钥 blob ;通过 dwCertEncodingType 中的 X509_ASN_ENCODING 和lpszStructType中的 RSA_CSP_PUBLICKEYBLOB
- 使用CryptImportKey导入 RSA 密钥 blob
这个序列确实帮助我理解了发生了什么,但它并没有按原样工作。第二次调用给CryptDecodeObjectEx
了我一个错误:“ASN.1 bad tag value met”。经过多次尝试理解微软文档,我终于意识到第一次解码的输出不能再解码为ASN,实际上已经准备好导入了。有了这种理解,我在以下链接中找到了答案:
http://www.ms-news.net/f2748/problem-importing-public-key-4052577.html
以下是我自己的程序,它将 .pem 文件中的公钥导入到 CryptApi 上下文中:
int main()
{
char pemPubKey[2048];
int readLen;
char derPubKey[2048];
size_t derPubKeyLen = 2048;
CERT_PUBLIC_KEY_INFO *publicKeyInfo;
int publicKeyInfoLen;
HANDLE hFile;
HCRYPTPROV hProv = 0;
HCRYPTKEY hKey = 0;
/*
* Read the public key cert from the file
*/
hFile = CreateFileA( "c:\\pub.pem", GENERIC_READ, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL );
if ( hFile == INVALID_HANDLE_VALUE )
{
fprintf( stderr, "Failed to open file. error: %d\n", GetLastError() );
}
if ( !ReadFile( hFile, pemPubKey, 2048, &readLen, NULL ) )
{
fprintf( stderr, "Failed to read file. error: %d\n", GetLastError() );
}
/*
* Convert from PEM format to DER format - removes header and footer and decodes from base64
*/
if ( !CryptStringToBinaryA( pemPubKey, 0, CRYPT_STRING_BASE64HEADER, derPubKey, &derPubKeyLen, NULL, NULL ) )
{
fprintf( stderr, "CryptStringToBinary failed. Err: %d\n", GetLastError() );
}
/*
* Decode from DER format to CERT_PUBLIC_KEY_INFO
*/
if ( !CryptDecodeObjectEx( X509_ASN_ENCODING, X509_PUBLIC_KEY_INFO, derPubKey, derPubKeyLen,
CRYPT_ENCODE_ALLOC_FLAG, NULL, &publicKeyInfo, &publicKeyInfoLen ) )
{
fprintf( stderr, "CryptDecodeObjectEx 1 failed. Err: %p\n", GetLastError() );
return -1;
}
/*
* Acquire context
*/
if( !CryptAcquireContext(&hProv, NULL, NULL, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT) )
{
{
printf( "CryptAcquireContext failed - err=0x%x.\n", GetLastError() );
return -1;
}
}
/*
* Import the public key using the context
*/
if ( !CryptImportPublicKeyInfo( hProv, X509_ASN_ENCODING, publicKeyInfo, &hKey ) )
{
fprintf( stderr, "CryptImportPublicKeyInfo failed. error: %d\n", GetLastError() );
return -1;
}
LocalFree( publicKeyInfo );
/*
* Now use hKey to encrypt whatever you need.
*/
return 0;
}