我需要在 PHP 中创建一个函数,它从 Delphi 中的函数返回相同的结果。在 PHP 中用“/ /”注释的 excerpts 函数中,我无法替代那些返回相同结果的行。
德尔福代码:
function Crypt_(Action, Src: String): String;
Label Fim;
var KeyLen : Integer;
KeyPos : Integer;
OffSet : Integer;
Dest, Key : String;
SrcPos : Integer;
SrcAsc : Integer;
TmpSrcAsc : Integer;
Range : Integer;
begin
if (Src = '') Then
begin
Result:= '';
Goto Fim;
end;
Key :=
'YUQL23KL23DF90WI5E1JAS467NMCXXL6JAOAUWWMCL0AOMM4A4VZYW9KHJUI2347EJHJKDF3424SKL K3LAKDJSL9RTIKJ';
Dest := '';
KeyLen := Length(Key);
KeyPos := 0;
SrcPos := 0;
SrcAsc := 0;
Range := 256;
if (Action = UpperCase('C')) then
begin
Randomize;
OffSet := Random(Range);
Dest := Format('%1.2x',[OffSet]);
for SrcPos := 1 to Length(Src) do
begin
SrcAsc := (Ord(Src[SrcPos]) + OffSet) Mod 255;
if KeyPos < KeyLen then KeyPos := KeyPos + 1 else KeyPos := 1;
SrcAsc := SrcAsc Xor Ord(Key[KeyPos]);
Dest := Dest + Format('%1.2x',[SrcAsc]);
OffSet := SrcAsc;
end;
end
Else if (Action = UpperCase('D')) then
begin
OffSet := StrToInt('$'+ copy(Src,1,2));
SrcPos := 3;
repeat
SrcAsc := StrToInt('$'+ copy(Src,SrcPos,2));
if (KeyPos < KeyLen) Then KeyPos := KeyPos + 1 else KeyPos := 1;
TmpSrcAsc := SrcAsc Xor Ord(Key[KeyPos]);
if TmpSrcAsc <= OffSet then TmpSrcAsc := 255 + TmpSrcAsc - OffSet
else TmpSrcAsc := TmpSrcAsc - OffSet;
Dest := Dest + Chr(TmpSrcAsc);
OffSet := SrcAsc;
SrcPos := SrcPos + 2;
until (SrcPos >= Length(Src));
end;
Result:= Dest;
Fim:
end;
PHP代码:
<?php
function Crypt_($Action, $Src) {
$Key = 'YUQL23KL23DF90WI5E1JAS467NMCXXL6JAOAUWWMCL0AOMM4A4VZYW9KHJUI2347EJHJKDF3424SKL K3LAKDJSL9RTIKJ';
$KeyLen = strlen($Key);
$KeyPos = 0;
if ($Action == 'C') {
$OffSet = rand(0,256);
// Dest := Format('%1.2x',[OffSet]); //I tried to replace the function "sprintf", but the result is null
$SrcPos = 1;
while ($SrcPos <= strlen($Src)) {
$SrcAsc = (ord($Src[$SrcPos]) + $OffSet) % 255;
if ($KeyPos < $KeyLen) $KeyPos = $KeyPos + 1; else $KeyPos = 1;
$SrcAsc = $SrcAsc xor ord($Key[$KeyPos]);
// Dest := Dest + Format('%1.2x',[SrcAsc]); //I tried to replace the function "sprintf", but the result is null
$OffSet = $SrcAsc;
$SrcPos = $SrcPos + 1;
}
} else {
// OffSet := StrToInt('$'+ copy(Src,1,2));
$Dest = '';
$SrcPos = 3;
while ($SrcPos >= strlen($Src)) {
// SrcAsc := StrToInt('$'+ copy(Src,SrcPos,2));
if ($KeyPos < $KeyLen) $KeyPos = $KeyPos + 1; else $KeyPos = 1;
$TmpSrcAsc = $SrcAsc xor ord($Key[$KeyPos]);
if ($TmpSrcAsc <= $OffSet) $TmpSrcAsc = 255 + $TmpSrcAsc - $OffSet;
else $TmpSrcAsc = $TmpSrcAsc - $OffSet;
$Dest = $Dest + chr($TmpSrcAsc);
$OffSet = $SrcAsc;
$SrcPos = $SrcPos + 2;
}
}
return $Dest;
}
?>
我还想知道“xor”、“ord”和“chr” PHP 是否会与 Delphi 有相同的结果。
感谢大家的关注!