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

后端 未结 2 1058
你的背包
你的背包 2020-12-18 09:14

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. B

相关标签:
2条回答
  • 2020-12-18 09:39

    A PEM private key can be imported into CAPI by using CryptDecodeObjectEx with PKCS_RSA_PRIVATE_KEY and then calling CryptImportKey.

    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

    I hope this will help.

    0 讨论(0)
  • 2020-12-18 09:50

    I ran into this problem with an encrypted private key in PEM format. Here is the process I followed to decrypt and import it:

    1. Decode the PEM using CryptStringToBinaryA with CRYPT_STRING_BASE64HEADER
    2. Decode the ASN.1 data using CryptDecodeObject with PKCS_7_ASN_ENCODING and PKCS_ENCRYPTED_PRIVATE_KEY_INFO
      • This produces some information about how the key is encrypted and the actual encrypted data. In my case, the key came from OpenSSL, and the encryption is described by RFC 8018, Appendix A.4.
      • I had to manually write some code to parse out this structure as it's not natively supported by CryptDecodeObject. You can find that code here.
    3. Once you have the encryption of the private key and the information about how to derive the symmetric key and which algorithm to decrypt it (in my case PBKDF2 and AES-256-CBC):
      1. Use BCryptDeriveKeyPBKDF2 to derive the encryption key from the password
      2. Use BCryptDecrypt to decrypt the private key using the symmetric key derived from the password.
    4. Use CryptDecodeObject with PKCS_7_ASN_ENCODING and PKCS_PRIVATE_KEY_INFO
    5. Use CryptDecodeObject with PKCS_7_ASN_ENCODING and PKCS_RSA_PRIVATE_KEY on the PrivateKey data member produced in the previous step.

    The output of this last step is an RSA Private Key BLOB. This can be imported with BCryptImportKeyPair and LEGACY_RSAPRIVATE_BLOB. Again, code demonstrating all of this can be found here.

    0 讨论(0)
提交回复
热议问题