Jake Evans
Jake Evans

Reputation: 1048

Delphi <> PHP XOR Encryption

I am trying to do encryption and decryption between PHP and Delphi.

My PHP code is;

<?php
error_reporting(E_ALL);
$key = "5y';syhl0ngl4st1ngdfvt5tt";

function decrypt1($string, $key){

    $y = 1;
    for ($x = 1;$i < strlen($string); $i++) {
        $a = (ord($string[$x]) and 0x0f) ^ (ord($key[$y]) and 0x0f);
        $string[$x] = chr((ord($string[$x]) and 0xf0) + $a);

        $y++;
        if ($y > strlen($key)) $y = 1;
    }
    return $string;
}

echo decrypt1(base64_decode("cWx0fw=="),$key);
?>

My Delphi is;

function Decrypt1(Str : String; Key: string): AnsiString;
var
  X, Y : Integer;
  A : Byte;
begin
  Y := 1;
  for X := 1 to Length(Str) do
  begin
    A := (ord(Str[X]) and $0f) xor (ord(Key[Y]) and $0f);
    Str[X] := char((ord(Str[X]) and $f0) + A);

    Inc(Y);
    If Y > length(Key) then Y := 1;
  end;
  Result := Str;
end;

function Encrypt(Str : String; Key: string): String;
begin
result:= Decrypt1(str,key);
result:= EncodeBase64(result);
end;

The encryption / decryption doesn't work. When attempting to decode encoded value from Delphi in PHP, I get a load of rubbish.

I have a feeling it might be something to do with the character encoding?

Upvotes: 0

Views: 1047

Answers (2)

David Heffernan
David Heffernan

Reputation: 612964

There are a few problems here:

  • String indexing in PHP is zero-based and not one-based as your code assumes.
  • Delphi strings (well, in modern Delphi) are UTF-16 encoded. Your code assumes some unspecified 8 bit encoding.
  • Encryption/decryption operates on binary data rather than text and you fail to recognise this.

You should encrypt like this:

  1. Encode the text in a specific, well-defined encoding. For instance, UTF-8. This gives a byte array. In Delphi that is TBytes.
  2. Encrypt this byte array to yield another byte array.
  3. Encode that byte array using base64 to get a text representation.

Decryption simply reverses these steps. The key thing to absorb is that encryption/decryption operates on binary data rather than text.

Upvotes: 4

Mason Wheeler
Mason Wheeler

Reputation: 84550

I'm going to take a guess here and say you're using a Delphi version where string is a UnicodeString. PHP generally uses some ANSI encoding, which can be configured. The best way to deal with this is to have your Delphi code save to UTF-8 and load from UTF-8, and make sure your PHP loads from UTF-8. Standardize on one encoding across the board and then issues like this won't happen.

Upvotes: 1

Related Questions