Wednesday, July 7, 2010

Unicode file encryption/decryption

Here is an overview of how we will encrypt/decrypt an unicode file


Encryption:

1. Open the file as binary mode and read the content of file to a byte array.

2. Encrypt the byte array.

3. Write the byte array to a file.

Decryption:

1. Open the encrypted file as binary mode and read content of the file to a byte array.

2. Decrypt the byte array.

3. Write the byte array to a file.


The encryption and decryption functions are:


void EncryptBytes
(
unsigned char* pByte, // Bytes passed in, encrypted bytes passed out.
int iSize, // Size of the byte array
int* pKey // Encrypting key. (in/out)

)

{
int ii = 0;
unsigned char iNew = 0;
for(ii = 0; ii < iSize; ii++)
{
// Encrypt the character.
iNew = pByte[ii] ^ ((*pKey >> 8));
*pKey = ((iNew + *pKey) & 0xFFFF)*EncryptConst1 - EncryptConst2;
pByte[ii] = iNew;
}
}

void DecryptBytes
(
unsigned char* pByte, // Bytes passed in, decrypted bytes passed out.
int iSize, // Size of the byte array
int* pKey // Encrypting key. (in/out)

)

{
int ii = 0;
unsigned char iNew = 0, iVal;

for(ii = 0; ii < iSize; ii++)
{
iVal = pByte[ii];
iNew = iVal ^ ((*pKey >> 8));

*pKey = ((iVal + *pKey) & 0xFFFF)*EncryptConst1 - EncryptConst2;
pByte[ii] = iNew;
}
}