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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8412838/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-15 18:36:51  来源:igfitidea点击:

How to import private key in PEM format using WinCrypt and C++?

c++windowscryptographycryptoapipem

提问by nikloskoda

I'm trying to use the WinCrypt APIin C++.

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

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.

我的应用程序需要加密、解密、签名和验证文件,一旦我拥有正确的密钥,我就知道如何做到这一点。但我的问题实际上是生成这些密钥的应用程序不同。

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

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

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

And :

和 :

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

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

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

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

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

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

回答by Mounir IDRASSI

A PEM private key can be imported into CAPI by using CryptDecodeObjectExwith PKCS_RSA_PRIVATE_KEYand then calling CryptImportKey.

可以通过使用CryptDecodeObjectExPKCS_RSA_PRIVATE_KEY然后调用CryptImportKey将 PEM 私钥导入 CAPI 。

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

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

I hope this will help.

我希望这将有所帮助。