1
0
forked from 0ad/0ad
0ad/source/ps/Encryption.cpp
janwas 2ebc9e2cb6 Initial revision
This was SVN commit r5.
2003-09-21 21:24:53 +00:00

87 lines
2.8 KiB
C++
Executable File

// last modified Friday, May 09, 2003
#include "Encryption.h"
//--------------------------------------------------------------------
// EncryptData - Takes A pointer to data in memory, the length of that data,
// Along with a key in memory and its length. It will allocated space
// for the encrypted copy of the data via new[], It is the responsiblity of the user
// to call delete[].
//--------------------------------------------------------------------
_byte *EncryptData(_byte *Data, _long DataLength, _byte *Key, _long KeyLength)
{
// Allocate space for new Encrypted data
_byte *NewData = new _byte[DataLength];
// A counter to hold our absolute position in data
_long DataOffset = 0;
// Loop through Data until end is reached
while (DataOffset < DataLength)
{
// Loop through the key
for (_long KeyOffset = 0; KeyOffset < KeyLength; KeyOffset++)
{
// If were at end of data break and the the while loop should end as well.
if (DataOffset >= DataLength)
break;
// Otherwise Add the previous element of the key from the newdata
// (just something a little extra to confuse the hackers)
if (KeyOffset > 0) // Don't mess with the first byte
NewData[DataOffset] += Key[KeyOffset - 1];
// Xor the Data byte with the key byte and get new data
NewData[DataOffset] = Data[DataOffset] ^ Key[KeyOffset];
// Increase position in data
DataOffset++;
}
}
// return the new data
return NewData;
}
//--------------------------------------------------------------------
// DecryptData - Takes A pointer to data in memory, the length of that data,
// Along with a key in memory and its length. It will allocated space
// for the decrypted copy of the data via new[], It is the responsiblity of the user
// to call delete[].
//--------------------------------------------------------------------
_byte *DecryptData(_byte *Data, _long DataLength, _byte *Key, _long KeyLength)
{
// Allocate space for new Decrypted data
_byte *NewData = new _byte[DataLength];
// A counter to hold our absolute position in data
_long DataOffset = 0;
// Loop through Data until end is reached
while (DataOffset < DataLength)
{
// Loop through the key
for (_long KeyOffset = 0; KeyOffset < KeyLength; KeyOffset++)
{
// If were at end of data break and the the while loop should end as well.
if (DataOffset >= DataLength)
break;
// Otherwise Xor the Data byte with the key byte and get new data
NewData[DataOffset] = Data[DataOffset] ^ Key[KeyOffset];
// Subtract the previous element of the key from the newdata
// (just something a little extra to confuse the hackers)
if (KeyOffset > 0) // Don't mess with the first byte
NewData[DataOffset] -= Key[KeyOffset - 1];
// Increase position in data
DataOffset++;
}
}
// return the new data
return NewData;
}