-1

CryptUnprotectData returns FALSE, please help me. I try with wstring also, but it returns FALSE too. In which direction to look the error in C++?

#include <wtypes.h>
#include <string>
#include <cstdint>
#include "dpapi.h"

#pragma comment(lib, "Crypt32")

int main()
{   
    string in = "fdggddgsgds";
    LPWSTR pDescrOut = NULL;
    DATA_BLOB inData, outData;
    inData.pbData = (BYTE*)in.data();
    inData.cbData = (DWORD)in.size();

    BOOL ok = CryptUnprotectData(&inData, NULL, NULL, NULL, NULL, 0, &outData);

    if (inData.pbData != NULL)
        LocalFree(inData.pbData);

    if (pDescrOut != NULL)
        LocalFree(pDescrOut);

    if (!ok)
        return NULL;

    char* str = (char*)malloc(outData.cbData + 1);
    memcpy(str, outData.pbData, outData.cbData);
    str[outData.cbData] = '\0';

    if (outData.pbData != NULL)
        LocalFree(outData.pbData);
    return 0;
}

1 Answers1

0
(BYTE*)&in

This does not do what you think it does. in is a std::string. This results in a pointer to a std::string. Which has nothing to do, whatsoever, with the contents of this std::string.

The clear intent here is to obtain a pointer to the contents of the std::string, rather than the std::string itself.

To do that, use (BYTE *)in.data(), instead. This may or may not be the only problem with the shown code, since it fails to meet Stackoverflow's requirements for minimal reproducible example, however it is an obvious error.

Sam Varshavchik
  • 114,536
  • 5
  • 94
  • 148