Reputation: 1048
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
Reputation: 612964
There are a few problems here:
You should encrypt like this:
TBytes
. Decryption simply reverses these steps. The key thing to absorb is that encryption/decryption operates on binary data rather than text.
Upvotes: 4
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