To encrypt a text string in Delphi is fairly straight forward. The XOR
method of encryption makes things particularly easy as the same routine
used to encrypt the data is also used to decrypt the data.
XOR encryption relies on a 'key', supplied by either the program, or user.
This key is used to encrypt and decrypt the data.
The routine works by taking each letter of the string and the key and
performing an XOR operation on them, storing the result. XOR (eXclusive
OR) operations work at the bit level, comparing individual bits. If both
bits are ON or both bits are OFF, the XOR function returns 0, otherwise
it returns 1.
eg. 110010 xor 100110 =
1 xor 1 = 0
1 xor 0 = 1
0 xor 0 = 0
0 xor 1 = 1
1 xor 1 = 0
0 xor 0 = 0
= 010100
The beautiful thing about this method means that if I now XOR the result
with the key (100110) again, we will end up with the original number.
010100 xor 100110 = 110010
To ensure that we do not get any NULL characters in the returned string, each
byte value of each character has 128 added to it. This is important as
NULL values in a string can cause unexpected and undesired results.
If the key is reached before the end of the input string, we simply return
to the beginning of the key again. In this manner, we are not restricted
to keys that MUST be equal to or longer than the input string.
The full commented source for this routine is below. You may copy this
routine and do with it what you will. I should point out though, I designed
this routine for textual data only, not binary data.
function XOR_encryption(const InStr, KeyStr : string) : string;
var C1, C2 : integer;
OutStr : string;
Ch1, Ch2 : byte;
begin
//First initialise the counters to zero
C1 := 0;
C2 := 0;
//initialise the returning string to an empty string
OutStr := '';
//We want to loop for as many characters in the Input String
while (C1 < Length(InStr)) do
begin
//first of all, increment the both counters
inc(C1);
inc(C2);
//if the second counter is greater than the length of the
//Key String, then set ot back to 1
if (C2 > Length(KeyStr)) then
C2 := 1;
//get the byte value of the character at the current position
//of the Input String
Ch1 := Ord(InStr[C1]);
//get the byte value of the character at the current position
//of the Key String. To ensure we do not get any NULL
//characters during encryption, we add 128 to this value
Ch2 := Ord(KeyStr[C2]) + 128;
//Add the XOR'd value of the current Input String position
//and the current Key String position to the end of the
//returning string
OutStr := OutStr + Chr(Ch1 xor Ch2);
end;
//return the encrypted/decrypted string
Result := OutStr;
end;
|