Why does my CryptDecrypt fail with error code 0x80090005 (NTE_BAD_DATA)?

3

I wrote this piece of code to decrypt a given cipher using a given key and iv. It works fine until CryptDecrypt which returns false and GetLastError() returns 0x80090005 (which should be NTE_BAD_DATA).

#include <Windows.h>
#include <wincrypt.h>

struct AesKey
{
    BLOBHEADER Header;
    DWORD dwKeyLength;
    BYTE cbKey[16];

        AesKey()
    {
        ZeroMemory(this, sizeof(*this));
        Header.bType = PLAINTEXTKEYBLOB;
        Header.bVersion = CUR_BLOB_VERSION;
        Header.reserved = 0;
        Header.aiKeyAlg = CALG_AES_128;
        dwKeyLength = 16;
    }
};

void AesDecrypt(unsigned char *output, unsigned char *input, int inLen, unsigned char *key, unsigned char *iv, int &plainSize)
{
    HCRYPTPROV provider;
    AesKey rawKey;
    HCRYPTKEY cKey;

    BOOL hr = CryptAcquireContext(&provider, NULL, MS_ENH_RSA_AES_PROV, PROV_RSA_AES, 0);
    if (hr == FALSE)
        throw "Unable to acquire AES Context";

    for (int i = 0; i < 16; i++)
        rawKey.cbKey[i] = key[i];

    hr = CryptImportKey(provider, (BYTE *) &rawKey, sizeof(AesKey), NULL, 0, &cKey);
    if (hr == FALSE)
        throw "Unable to import given key";

    hr = CryptSetKeyParam(cKey, KP_IV, (BYTE *) iv, 0);
    if (hr == FALSE)
        throw "Unable to set IV";

    DWORD dwMode = CRYPT_MODE_CBC;
    hr = CryptSetKeyParam(cKey, KP_MODE, (BYTE*) &dwMode, 0);
    if (hr == FALSE)
        throw "Unable to set mode";

    memcpy(output, input, inLen);

    DWORD d = (DWORD) inLen;
    hr = CryptDecrypt(cKey, NULL, TRUE, 0, output, &d);
    if (hr == FALSE)
    {
        int err = GetLastError();
        throw "Error during Decryption";
    }

    plainSize = d;
}

If you have any idea, please share :)

Thanks in advance...

c++
windows
cryptoapi
asked on Stack Overflow Nov 25, 2011 by Francesco Boffa

0 Answers

Nobody has answered this question yet.


User contributions licensed under CC BY-SA 3.0