views:

34

answers:

2

I have a public key and I want to use it to encrypt a piece of data. I'm trying to import the public key in order to use it, but CryptImportKey gives me an 'invalic parameter' error.

What's the problem?

Here's my code:

if( !CryptAcquireContext(&hProv, NULL, NULL, PROV_RSA_AES, CRYPT_VERIFYCONTEXT) )
{
    /*
     * Print error and return
     */
}
pblob->header->bType = PUBLICKEYBLOB;
pblob->header->aiKeyAlg = CALG_AES_128;
pblob->header->bVersion = CUR_BLOB_VERSION;
pblob->header->reserved = 0;
pblob->key_len = key_len;

memcpy(pblob->key, key , key_len);

if( !CryptImportKey( &hProv,
    (LPCBYTE)pblob,
    sizeof(*pblob),
    0,
    CRYPT_EXPORTABLE,
    &hKey ) )
{
    // Print error and return
}
A: 

Windows CryptoAPI doesn't work directly with plain text keys; you have to jump through a bit of a hoop to do this. Here is the knowledge base article describing how to do this.

Luke
Quite a hoop indeed! But I'm not sure this is what I need. First of all I have realized that in fact the public key I want to import is used to encrypt another key, and so for key exchange, so I changed the ALG_ID to CALG_RSA_KEYX, but still get the error. As to the plaintext session keys - I'm importing a public key, and MSDN says that such keys are not encrypted, which is what I want. So I don't think I need the hoop...
rimono
Are you sure your key blob is in the correct format? See http://msdn.microsoft.com/en-us/library/aa375601.aspx
Luke
Well, after reading the link you gave, I'm not at all sure! In fact it made me realize that I might be missing even more here. The point is that the public key I'm trying to import came from a .pem file. I now understand that its not enough to remove the header and footer in the .pem file. So I base64-decoded the contents, but now I am starting to think that's not enough either. I understand that the contents are in DER format, and I don't know how to convert that into something I can import into CryptoApi. Any idea?
rimono
Here's another question that seems to be asking the same thing; maybe you can give that solution a try. http://stackoverflow.com/questions/1231178/load-an-x509-pem-file-into-windows-cryptoapi
Luke
That solution is indeed exactly what I need, and it appears to be the perfect answer. Still, for some reason, when I implement it the last CryptDecodeObjectEx, which should be from the DER format to the RSA structure, returns an error indicating "ASN.1 bad tag value met", and I have yet to find out what that means. :-(
rimono
A: 

Thanks to all that was said here, and a lot of searching, I found the answer in: http://www.ms-news.net/f2748/problem-importing-public-key-4052577.html

And used it to create my own program which I posted on the other thread at: http://stackoverflow.com/questions/1231178/load-an-x509-pem-file-into-windows-cryptoapi/3803333#3803333

rimono