Link to home
Start Free TrialLog in
Avatar of Reasen0
Reasen0

asked on

Communication Between RC4 Delphi <-> PHP

I'm just trying to translate this RC4 Function (PHP) to Delphi but i don't have any luck, it just corrupt data... Any help is appreciated.

This is the PHP Function:
function RC4($str, $key) {  
	$s = array();
	for ($i = 0; $i < 256; $i++) {
		$s[$i] = $i;
	}
	$j = 0;
	for ($i = 0; $i < 256; $i++) {
		$j = ($j + $s[$i] + ord($key[$i % strlen($key)])) % 256;
		$x = $s[$i];
		$s[$i] = $s[$j];
		$s[$j] = $x;
	}
	$i = 0;
	$j = 0;
	$res = '';
	for ($y = 0; $y < strlen($str); $y++) {
		$i = ($i + 1) % 256;
		$j = ($j + $s[$i]) % 256;
		$x = $s[$i];
		$s[$i] = $s[$j];
		$s[$j] = $x;
		$res .= $str[$y] ^ chr($s[($s[$i] + $s[$j]) % 256]);
	}
	return $res;
}

Open in new window


And here is my try to translate to Delphi but it just corrupt data:
function RC4Delphi(str, key: string): string;
var
  s: array[0..255] of integer;
  i, j, x, y,f: integer;
  res: string;
begin
  for i := 0 to 255 do
    s[i] := i;
  j := 0;
  for i := 0 to 255 do
  begin
    j := (j + s[i] + ord(key[i mod length(key)])) mod 256;
    x := s[i];
    s[i] := s[j];
    s[j] := x;
  end;
  i := 0;
  j := 0;
  res := '';
  for y := 0 to length(str) do
  begin
    i := i mod 256;
    j := (j + s[i] mod 256);
    x := s[i];
    s[i] := s[j];
    s[j] := x;
    f:=  ord(str[y]) xor ord(chr(s[(s[i] + s[j]) mod 256]));

    res := res + chr(f);
  end;
  result := res;

end;

Open in new window

Avatar of Ray Paseur
Ray Paseur
Flag of United States of America image

Since this is not a question with an answer, but more of a requirement for Delphi application development, you might get the quickest results by posting your requirement in E-E Gigs.
ASKER CERTIFIED SOLUTION
Avatar of Sinisa Vuk
Sinisa Vuk
Flag of Croatia image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
I suggest you look at one of the Delphi encryption libraries instead of doing this conversion.