0

I'm trying to call CryptProtectData from the Data Protection API (DPAPI):

DATA_BLOB dataIn;
DATA_BLOB dataEncrypted;
BYTE *phrase = (BYTE *)plain.c_str();
DWORD length = strlen((char *)phrase) + 1;
dataIn.pbData = phrase;
dataIn.cbData = length;
if(CryptProtectData(&dataIn, NULL, NULL, NULL, NULL, 
                CRYPTPROTECT_LOCAL_MACHINE, &dataEncrypted))
{
    file.open(filePath, std::ios_base::binary);
    if(!file.is_open())
    {
        return false;
    }
    file.write(reinterpret_cast<char *>(dataEncrypted.pbData),
                dataEncrypted.cbData);
    file.close();
    LocalFree(dataEncrypted.pbData);
    return true;
}

And I'm randomly getting the error:

Exception thrown at 0x77457E67 (ntdll.dll) in test.exe: 0xC00000005:

Access violation reading location 0x24146304

PFA

Error Image

It's happening seemingly randomly on one machine (Windows Server2012), but seems to work fine on any other machine without error.

7
  • Are you both encrypting and decrypting on the same machine? Or are you encrypting it on one machine and trying to decrypt it on another? When you use CRYPTPROTECT_LOCAL_MACHINE, it can only be decrypted on the same machine that it was originally encrypted on. I ask because this sometimes is a common bug when using web-servers in a load-balancing arrangement; the other server happens to be called to service a request, and when it tries to decrypt the data: it can't - because it was originially encrypted on the "main" server.
    – Ian Boyd
    Commented Apr 1 at 16:13
  • You haven't provided enough information to diagnose the issue. For example what is the declaration of plain, when debugging the error what is at the address shown in the exception. Your example is more or less the same as the MSDN example except for the std::string usage, so I would suggest that is the area to look at. Commented Apr 1 at 17:22
  • look/show complete callstack with symbols. and you fail free dataEncrypted.pbData in case !file.is_open()
    – RbMm
    Commented Apr 1 at 18:29
  • @IanBoyd, yes, Iam encrypting and decrypting on the same machien and its not failing on all the time. Randomly getting this exception, not sure when this occurs
    – Gokul
    Commented Apr 2 at 6:20
  • @Nickd'Alterio I've updated the image with call stack, pls check .
    – Gokul
    Commented Apr 2 at 6:24

0