views:

893

answers:

3

Hi coders, I'm new to the whole Crypto thing, so I beg some basic pointers.

I need to load .PEM (X509) "-----BEGIN RSA XXX KEY----- -----END RSA XXX KEY-----" into a Windows Crypto Api context to use with C++ (I found examples for Python and .NET but they use specific functions I can't relate to the plain Windows Crypto Api)

I understand how to encrypt/decrypt once I've got a HCRYPTKEY. BUT, I just don't get how to import the Base64 blob in the .PEM file(s) and get a HCRYPTKEY that I can use out of it.

I have that stange feeling that there is more to it than simply calling CryptDecodeObject().

Any pointers that can put me on track? I've already lost 2 days doing "trial & error" programming and getting nowhere.

A: 

I'm currently facing the same difficulty. I haven't finished coding a solution but as I understand it you need to strip off the ----- BEGIN etc ----- and ----- END etc ------ tags and decode the Base64.

This leaves you with a DER encoded string, which you need to parse to get the modulus and public exponent. From those you can populate the PUBLICKEYSTRUC and RSAPUBKEY structures. Good luck ;-)

jarmond
Look into CryptDecodeObjectEx with X509_ASN_ENCODING and RSA_CSP_PUBLICKEYBLOB options. Seems to decode and fill the structure correctly, but you may still need to swap the byte-order of some parts.
jarmond
+1  A: 

I discovered the "magic" sequence of calls to import a RSA public key in PEM format. Here you go:

  1. decode the key into a binary blob with CryptStringToBinary; pass CRYPT_STRING_BASE64HEADER in dwFlags
  2. decode the binary key blob into a CERT_PUBLIC_KEY_INFO with CryptDecodeObjectEx; pass X509_ASN_ENCODING in dwCertEncodingType and X509_PUBLIC_KEY_INFO in lpszStructType
  3. decode the PublicKey blob from the CERT_PUBLIC_KEY_INFO into a RSA key blob with CryptDecodeObjectEx; pass X509_ASN_ENCODING in dwCertEncodingType and RSA_CSP_PUBLICKEYBLOB in lpszStructType
  4. import the RSA key blob with CryptImportKey
KJKHyperion
A: 
rimono