Tuesday, September 15, 2009

Text encryption with XOR

Ever wanted to encrypt a text message?
In order to do that we need some helper functions like transforming the string to it's hex representation after encryption so we don't loose any characters plus it looks very good:
function StringToHexStr(const value: string): string;
begin
  SetLength(Result, Length(value) *2);
  if Length(value) > 0 then
    BinToHex(PChar(value), PChar(Result), Length(value));
end;

function HexStrToString(const value: string): string;
begin
  SetLength(Result, Length(value) div 2);
  if Length(value) > 0 then
    HexToBin(PChar(value), PChar(Result), Length(value));
end;

ok... now we need a hash function so we hash our password string
function hashKey(const Key: String): Integer;
var
  Index: Integer;
begin
  Result := 0;;
  for Index := 1 to Length(Key) do
    Result := ((Result shl 7) or (Result shr 25)) + Ord(Key[Index]);
end;

Note that you can use any hash functions you like as long as it's result type is Cardinal or Integer(unsigned long or signed long) this hash function is taken from (RemObjects Software) PascalScript's "uPSUtils.pas" unit, now we need the algorithm
function __encrypt(const Key, Source: String): String;
// this function should not be used directly
// use EncryptText and DecryptText
const
  szBuffer = SizeOf(Integer); (* 4 bytes *)
  szByteBuffer = SizeOf(Byte); (* 1 byte *)
var
  byteBuffer,
  buffer,
  index,
  theKey: Integer;
  StreamOut,
  StreamIn: TStringStream;
begin
  (* hash the key and store it on local integer variable *)
  theKey := hashKey(Key);
  (* create two TStringStream's:
     - one for the actual data
     - the other one for the encrypted/decrypted data *)
  StreamIn := TStringStream.Create(Source);
  StreamOut := TStringStream.Create('');
  (* make sure position is set to ZERO !! *)
  StreamIn.Position := 0;
  StreamOut.Position := 0;

  (* now loop WHILE number of bytes read is less than
     number of total bytes AND the difference between
     position and size is greater or equal to szBuffer
     which is 4 bytes *)
  while (StreamIn.Position < StreamIn.Size) and
    ((StreamIn.Size -StreamIn.Position) >= szBuffer) do begin
    (* read 4 bytes at a time into a local integer variable *)
    StreamIn.ReadBuffer(buffer, szBuffer);
    (* the XOR encryption/decryption *)
    buffer := buffer xor theKey;
    buffer := buffer xor $E0F;
    (* write data to output stream *)
    StreamOut.WriteBuffer(buffer, szBuffer);
  end;

  (* check if we have some bytes left, there's a fat
     chance we do... *)
  if (StreamIn.Size -StreamIn.Position) >= 1 then
    for index := StreamIn.Position to StreamIn.Size -1 do begin
      (* we should have 1, 2 or 3 bytes left MAX, so we
         read 1 byte at a time *)
      StreamIn.ReadBuffer(byteBuffer, szByteBuffer);
      (* the XOR encryption/decryption *)
      byteBuffer := byteBuffer xor $F;
      (* write data to output stream *)
      StreamOut.WriteBuffer(byteBuffer, szByteBuffer);
    end;

  (* set output stream's postion to ZERO so we can
     read it's data *)
  StreamOut.Position := 0;
  (* read data from output stream and return it's value *)
  Result := StreamOut.ReadString(StreamOut.Size);

  (* free allocated memory *)
  FreeAndNil(StreamIn);
  FreeAndNil(StreamOut);
end;

the encryption and decryption functions
(* this function should be used ONLY for encryption *)
function EncryptText(const Key, Source: String): String;
begin
  (* return the encrypted data *)
  Result := __encrypt(Key, Source);
  (* convert string to hex string *)
  Result := StringToHexStr(Result);
end;

(* this function should be used ONLY for decryption *)
function DecryptText(const Key, Source: String): String;
begin
  (* convert each hex string to string *)
  Result := HexStrToString(Source);
  (* return the decrypted data *)
  Result := __encrypt(Key, Result);
end;

Here's the encryption result of string "http://delphigeist.blogspot.com"

124CE8194017B30D1F54EC01135FF900094CB20B1657FB1A0A57E8476C6062


using "delphigeist" as password.
Note that when you press Encrypt button the Text box is used as source and Encrypted box as output and vice-versa.
Screenshot of demo application taken with TurboSS

Demo application can be downloaded as:
binary
or
source code
I really hope this helps you in any way, even as a toy :).
P.S. the StringToHexStr and HexStrToString function are taken from Delphi PRAXIS the guy that posted is called "EDatabaseError", I'm too lazy...

4 comments:

  1. there are problems in Delphi 2010, StringToHex and HexToString work as expected only if parameter is redefined as AnsiString

    ReplyDelete
  2. Well yes, because AnsiString is made up of single byte characters while String(in d2010) allocates 2 bytes per character, the above example is made in delphi 7(in Delphi 7 string = AnsiString).
    You can create a new unit in which you define:
    TMYString = {$IFDEF UNICODE}AnsiString{$ELSEIF}string{$ENDIF};
    and replace each occurence of "string" with "TMYString" and add the unit in which you define "TMYString" to uses clause.

    ReplyDelete
  3. This isn't a very clever encryption method. Though the result looks good, it can be easily cracked.
    A xor Key = X
    B xor Key = Y
    C xor Key = Z
    The ABC is encrypted into Hex(XYZ)

    However, (X xor Y) = (A xor B). Having (A xor B) and (B xor C) and (C xor A), the original text can easily be retrieved (presuming ABC is plaintext). And having A and X, the Key is immediately found as well. This is known as the "reused key attack".

    ReplyDelete
  4. it seems not to work in delphi xe2.. Still looking for a simple encryption/decryption routine which produceds human readable strings..

    ReplyDelete

Blogroll(General programming and Delphi feeds)