Original Post
I want to encyrpt a buffer into a file and decyrpt a file into a buffer using microsofts encrypt and decrypt functions but I don't know how I would go about doing it. How would I set it up so it reads a block of encrypted/decrypted data and then encrypts/decrypts it then appends it to a buffer or writes it to a file? Here are some examples on msdn how they ecrypt and decrypt files. Encrypting Decrypting
dwBlockLen = 1000 - 1000 % ENCRYPT_BLOCK_SIZE;
if(ENCRYPT_BLOCK_SIZE > 1)
dwBufferLen = dwBlockLen + ENCRYPT_BLOCK_SIZE;
else
dwBufferLen = dwBlockLen;
//-------------------------------------------------------------------
// Allocate memory.
if(pbBuffer = (BYTE *)malloc(dwBufferLen))
{
printf("Memory has been allocated for the buffer. \n");
}
else
{
MyHandleError("Out of memory. \n");
}
//-------------------------------------------------------------------
// In a do loop, encrypt the source file,
// and write to the source file.
do
{
//-------------------------------------------------------------------
// Read up to dwBlockLen bytes from the source file.
dwCount = fread(pbBuffer, 1, dwBlockLen, hSource);
if(ferror(hSource))
{
MyHandleError("Error reading plaintext!\n");
}
//-------------------------------------------------------------------
// Encrypt data.
if(!CryptEncrypt(
hKey,
0,
feof(hSource),
0,
pbBuffer,
&dwCount,
dwBufferLen))
{
MyHandleError("Error during CryptEncrypt. \n");
}
//-------------------------------------------------------------------
// Write data to the destination file.
fwrite(pbBuffer, 1, dwCount, hDestination);
if(ferror(hDestination))
{
MyHandleError("Error writing ciphertext.");
}
}
while(!feof(hSource));
dwBlockLen = 1000 - 1000 % ENCRYPT_BLOCK_SIZE;
dwBufferLen = dwBlockLen;
//--------------------------------------------------------------------
// Allocate memory.
if(!(pbBuffer = (BYTE *)malloc(dwBufferLen)))
{
MyHandleError("Out of memory!\n");
}
//--------------------------------------------------------------------
// Decrypt source file, and write to destination file.
do {
//--------------------------------------------------------------------
// Read up to dwBlockLen bytes from source file.
dwCount = fread(
pbBuffer,
1,
dwBlockLen,
hSource);
if(ferror(hSource))
{
MyHandleError("Error reading ciphertext!");
}
//--------------------------------------------------------------------
// Decrypt data.
if(!CryptDecrypt(
hKey,
0,
feof(hSource),
0,
pbBuffer,
&dwCount))
{
MyHandleError("Error during CryptDecrypt!");
}
//--------------------------------------------------------------------
// Write data to destination file.
fwrite(
pbBuffer,
1,
dwCount,
hDestination);
if(ferror(hDestination))
{
MyHandleError("Error writing plaintext!");
}
}
while(!feof(hSource));
status = TRUE;