Tech Support > Microsoft Windows > Development Resources > About "CryptProtectData()" function
About "CryptProtectData()" function
Posted by Perro Flaco on September 14th, 2006


Hi!

I've been reading about "CryptProtectData()" function, and I would like
to do the following. I'm trying to encrypt some information, store it
in a file, and then be able to decrypt it, and use it normally. I've
found this piece of code:

DATA_BLOB DataIn;
DATA_BLOB DataOut;
BYTE *pbDataInput =(BYTE *)"Hello world of data protection.";
DWORD cbDataInput = strlen((char *)pbDataInput)+1;

DataIn.pbData = pbDataInput;
DataIn.cbData = cbDataInput;

if(CryptProtectData( &DataIn,
L"This is the description string.",
NULL,
NULL,
NULL,
0,
&DataOut))
{
printf("The encryption phase worked.\n");
} else {
printf("Encryption error using CryptProtectData.\n");
exit(1);
}

This works fine, and I can decrypt it using CryptUnprotectData()
without any problem. What I want to do, and where I've found some
dificulties, is to save the encrypted information to a file, and later
read it, and decrypt it. Is it possible? I've tried to do it but
without any success. I've use "fprintf" to write to the file:

FILE* my_file;
my_file = fopen( "C:\\test.txt", "w" );
fprintf( my_file, "%s", DataOut.pbData );
fclose( my_file );

Any idea? Maybe I'm doing something wrong when I try to write the
encrypted information to the file.

Thank you very much for your help!

Posted by David Lowndes on September 14th, 2006


The encrypted data is not a string - it's an array of bytes which may
contain null characters, but won't have a null terminator, so you
can't treat it as a null terminated string.

Additionally you need to open the file in binary mode ('b') rather
than the default text mode so that any CR LF and Ctrl+Z characters are
not treated specially. Use fread & fwrite.

Dave