I am trying to create a PHP script, and a Delphi program to “talk” with it. In order to keep it secure, I want to encrypt the outgoing text from both sides, so it makes to use the same encryption function on both ends.
This is the function I found for PHP:
function convert($str,$ky=''){
if($ky=='')return $str;
$ky=str_replace(chr(32),'',$ky);
if(strlen($ky)<8)exit('key error');
$kl=strlen($ky)<32?strlen($ky):32;
$k=array();
for($i=0;$i<$kl;$i++){
$k[$i]=ord($ky{$i})&0x1F;
}
$j=0;
for($i=0;$i<strlen($str);$i++){
$e=ord($str{$i});
$str{$i}=$e&0xE0?chr($e^$k[$j]):chr($e);
$j++;
$j=$j==$kl?0:$j;
}
return $str;
}
I cant seem to be able to convert it to Delphi. Help is greatly apreciated!
Thanks, Jeff
It’s a function that receives two strings and returns another string. I’ll include variable declarations in comments as they’re introduced in the code; put them at the top of the function.
If the key is empty, then the result is simply
str:The first parameter is the value to be “encrypted,” and the second is the key to use for that encryption. The key needs to be at least eight non-space characters long; anything beyond 32 is ignored. If the key is too short, the PHP script would terminate; we’ll use Delphi’s
Assertstatement instead since it’s clear that the code should never even have executed if the key is wrong. (Script-termination is not a recoverable error that the user would be expected to fix.) The PHP code uses the?:operator to select the desired value for the length, but Delphi’sMinfunction (from the Math unit) expresses the desire more clearly.The array
kis used to hold numbers representing the lower five bits of each character in the key. In PHP, an array will automatically grow to whatever size it needs based on the index used. In Delphi, we need to allocate the space in advance. Since it’s set in a loop that goes over each character of the key, we know the array will be the same length.Next, each character in the string that has its seventh bit set gets modified according to each successive byte in the
karray. Thejvariable keeps track of which key byte we’ll use next.Finally, we return the new value of
str: