views:

713

answers:

2

I need to have a Win32 application load a hard coded AES-256 key, ideally using the WinCrypt.h methods. I've got my key in an unsigned char[32] but I can't find the correct format of a key blob to pass to CryptImportKey. Everything seems to give me invalid parameter errors. Is there any way to do this?

(Also important is how to set IV in WinCrypt. I can't see how to do that at all)

+1  A: 

See this MS Knowledge Base article, How to export and import plain text session keys by using CryptoAPI

Murray
+2  A: 

Solved it. I was using the wrong bType and using 256 for keySize instead of 32.

BYTE privateKey[] = 
    {1,2,3,4,5,6,7,8,9,10,
    11,12,13,14,15,16,17,18,19,20,
    21,22,23,24,25,26,27,28,29,30,
    31,32};
BYTE iv[] = 
    {1,2,3,4,5,6,7,8,9,10,
    11,12,13,14,15,16};

struct aes256keyBlob
{
    BLOBHEADER hdr;
    DWORD keySize;
    BYTE bytes[32];
} blob;

blob.hdr.bType = PLAINTEXTKEYBLOB;
blob.hdr.bVersion = CUR_BLOB_VERSION;
blob.hdr.reserved = 0;
blob.hdr.aiKeyAlg = CALG_AES_256;
blob.keySize = 32;
memcpy(blob.bytes, myPrivateKey, 32);

HCRYPTKEY hKey;
if (CryptImportKey(hCryptProv, (BYTE*)&blob, sizeof(aes256keyBlob), NULL, 0, &hKey))
{
    if(CryptSetKeyParam(hKey, KP_IV, myIV, 0))
    {
     //do decryption here
    }
    else{/*error*/}

    CryptDestroyKey(hKey);
}
else{/*error*/}
Trevor