Click here to Skip to main content
15,886,816 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have been trying to decrypt a string that has been encrypted (DPAPI) with c++ for a while now, but I cant seem to figure it out. Right now when I try to decrypt a string with the CryptUnprotectData function, I only get back the unencrypted string that I put into the function. Here is my code:

<pre>#include <stdio.h>
#include <windows.h>
#include <Wincrypt.h>
#include <string>
#include <vector>
#include <fstream>
#include <iostream>
using namespace std;

#define MY_ENCODING_TYPE  (PKCS_7_ASN_ENCODING | X509_ASN_ENCODING)

#pragma comment (lib, "Crypt32.lib")

int main()
{

    string data = ("data I want to decode \n");
    cout << data;

    LPWSTR pDescrOut = NULL;


    DATA_BLOB DataBytes;
    BYTE* pbDataOutput = (BYTE*)data.data();
    DWORD cbDataOutput = strlen((char*)pbDataOutput) + 1;
    DataBytes.pbData = pbDataOutput;
    DataBytes.cbData = cbDataOutput;

    HRESULT res = CryptUnprotectData(
        &DataBytes,
        NULL,
        NULL,                 // Optional entropy
        NULL,                 // Reserved
        NULL,                 // Here, the optional
        // prompt structure is not
        // used.
        0,
        &DataBytes);

        printf("The decrypted data is: %s\n", DataBytes.pbData);



    LocalFree(pDescrOut);

}


Any help would be appreciated.

What I have tried:

I have tried whittling down some code from the documentation of the function here but only for it to stop working when i remove the encryption function.
Posted
Updated 28-Jan-23 4:03am

1 solution

Start by checking what is returned by the call - I'm guessing it's False indicating the decryption didn't happen.

And if I had to guess why, I'd start by looking at the actual parameters it expects and you give it: CryptUnprotectData function (dpapi.h) - Win32 apps | Microsoft Learn[^] - you are passing the same data blob as both input and output and I suspect that that would very likely be a problem.
 
Share this answer
 
Comments
Member 15904859 28-Jan-23 15:47pm    
Thanks for the reply! I have tried to use two DATA_BLOBS now (one for input and one for output) but it is still doing the same thing :/
Member 15904859 29-Jan-23 10:16am    
hello?

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900