title: Why does my CryptDecrypt fail with error code 0x80090005 (NTE_BAD_DATA)?
body: <p>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).</p>
  
  <pre><code>#include &lt;Windows.h&gt;
  #include &lt;wincrypt.h&gt;
  
  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 &amp;plainSize)
  {
      HCRYPTPROV provider;
      AesKey rawKey;
      HCRYPTKEY cKey;
  
      BOOL hr = CryptAcquireContext(&amp;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 &lt; 16; i++)
          rawKey.cbKey[i] = key[i];
  
      hr = CryptImportKey(provider, (BYTE *) &amp;rawKey, sizeof(AesKey), NULL, 0, &amp;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*) &amp;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, &amp;d);
      if (hr == FALSE)
      {
          int err = GetLastError();
          throw "Error during Decryption";
      }
  
      plainSize = d;
  }
  </code></pre>
  
  <p>If you have any idea, please share :)</p>
  
  <p>Thanks in advance...</p>