Search code examples
delphiencryptionhexxor

Delphi: XOR, HEX, encryption


Is there a way to encrypt with XOR and represent in HEX (and the reverse). (I suppose not, couldn't find that).

Is there an alternative? I don't want to use Base64.

So I need to encrypt and represent the result in a readable form.


Solution

  • Here is a function applying a XOR to a string, then return the result as hexadecimal:

    function XorToHex(const Source: string; Code: char): string;
    const
      HexChars: array[0..15] of char = '0123456789ABCDEF';
    var i: Integer;
        c: Integer;
    begin
      SetLength(Result,Length(Source)*(sizeof(char)*2));
      for i := 1 to Length(Source) do begin
        c := Ord(Source[i]) xor Ord(Code);
        {$IFDEF UNICODE}
        result[i*4-3] := HexChars[(c and 7) shr 4];
        result[i*4-2] := HexChars[(c and 7) and 15];
        c := c shr 8;
        result[i*4-1] := HexChars[c shr 4];
        result[i*4]   := HexChars[c and 15];
        {$ELSE}
        result[i*2-1] := HexChars[c shr 4];
        result[i*2]   := HexChars[c and 15];
        {$ENDIF}
      end;
    end;
    

    Such basic XOR is not strong at all. It's very easy to guess the key code, which is only one Char.

    But this function will work with both Unicode and not Unicode strings.