如何使用 WinCrypt 和 C++ 导入 PEM 格式的私钥?

2022-01-10 00:00:00 windows cryptography c++ pem cryptoapi

我正在尝试在 C++ 中使用 WinCrypt API.

I'm trying to use the WinCrypt API in C++.

我的应用程序需要对文件进行加密、解密、签名和验证,一旦我拥有正确的密钥,我就知道该怎么做.但我的问题实际上是生成这些密钥的应用程序不同.

My application need to cipher, decipher, sign and verify files, and I know how to do that once I have the correct keys. But my problem is actually that that is NOT the same application which generates those keys.

我拥有的是 PEM 格式文件中的公钥和私钥:

What I have is public and private keys in files in PEM format :

-----BEGIN RSA PRIVATE KEY-----
[Base64 encoded]
-----END RSA PRIVATE KEY-----

还有:

-----BEGIN RSA PUBLIC KEY-----
[Base64 encoded]
-----END RSA PUBLIC KEY-----

经过一番研究,我找到了如何导入公钥:这里和这里,使用以下方法:

After some research, I have found how to import the public key : here and here, using the following methods :

  • 创建文件 &ReadFile 读取文件内容
  • CryptStringToBinary,使用 CRYPT_STRING_BASE64HEADER 从 PEM 格式转换为 DER 格式(删除页眉和页脚并从 base64 解码)
  • CryptDecodeObjectEx 与 X509_PUBLIC_KEY_INFO
  • CryptImportPublicKeyInfo,导入密钥
  • CreateFile & ReadFile to read the file content
  • CryptStringToBinary, with CRYPT_STRING_BASE64HEADER to convert from PEM format to DER format (remove header and footer and decode from base64)
  • CryptDecodeObjectEx with X509_PUBLIC_KEY_INFO
  • CryptImportPublicKeyInfo, to import the key

但现在,我的问题是用 私钥 做同样的事情.任何帮助都会非常感激:)谢谢.

But now, my problem is to do the same thing whith the private key. Any help would be really really appreciated :) Thank you.

推荐答案

使用CryptDecodeObjectEx和PKCS_RSA_PRIVATE_KEY,然后调用可以将PEM私钥导入CAPI>CryptImportKey.

我编写了一个示例,展示了如何使用 PEM 编码的 RSA 私钥使用 CAPI 对数据进行签名.这是一个链接:http://www.idrix.fr/Root/Samples/capi_pem.cpp

I have written a sample that shows how to use a PEM encoded RSA private key for signing data using CAPI. Here is a link to it : http://www.idrix.fr/Root/Samples/capi_pem.cpp

我希望这会有所帮助.

相关文章