Serializing encrypted data






4.85/5 (8 votes)
Nov 1, 2001
1 min read

81188

1432
How to serialize encrypted data using CArchive
Introduction
I've recently discovered the CArchive
class. I've never used it
before. I had to save my application's preferences and I thought I would try to
serialize it to a file using the CArchive
class. Then only problem is
that I need to encrypt the data.
So I sat down and wrote a CFile
derived class to encrypt data while
saving it.
In the demo project I've used the Rijndael algorithm. The implementation was written by Szymon Stefanek.
Description
The most important functions of the CFile
class are Read
and
Write
. Since these are virtual functions, you can override them with your
own functions.
In the class, there are 2 callback functions. The class uses both to encrypt and to decrypt the data.
typedef UINT (FileEncryptProc)(const BYTE *pBuffer,UINT dwSize,BYTE *pDestination,DWORD
dwParam);
Parameters:
pBuffer
- Pointer to the datadwSize
- Data length in bytespDestination
- Pointer to a destination bufferdwParam
- User defined parameter
Return value:
New data length.
Usage
You set the callbacks using the SetEncryption
function
// These are the encryption and decryption functions UINT Encrypt(const BYTE *pBufIn, UINT nSize, BYTE *pBufOut, DWORD dwParam) { return ((Rijndael*)dwParam)->padEncrypt(pBufIn, nSize, pBufOut); } UINT Decrypt(const BYTE *pBufIn, UINT nSize, BYTE *pBufOut, DWORD dwParam) { return ((Rijndael*)dwParam)->padDecrypt(pBufIn, nSize, pBufOut); } f.SetEncryption(&Encrypt, (DWORD)&rijEncrypt, &Decrypt, (DWORD)&rijDecrypt); // Set the encryption callbacks
Conclusion
In the demo project, I've created two Rijndael objects. One for encryption
and one for decryption. Both objects were initialized using the same key. I've
also created a CFileEx
object and set it's callbacks to my defined
functions.
From that point, I can create a CArchive
object and use it as normal
with my file. As you can see in the demo, I am writing and reading various data
types to and from the archive.