我需要在PHP中創建一個函數,該函數從Delphi中的函數返回相同的結果。在PHP中用「/ /」表示的摘錄函數是我無法替代的那些返回相同結果的行。函數「德爾福」到「PHP」
Delphi代碼:
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;
}
?>
不知還是否 「異或」, 「ORD」 和 「CHR」 PHP將有相同的結果作爲德爾福。
感謝大家的關注!
'format' - >'sprintf()'。 –
軟件安全101:寫一個人自己的加密程序是一個壞主意。我接受這種情況下,你必須做到與現有程序兼容,但瞭解這個代碼完全沒有機會以任何有意義的方式保證安全是非常重要的。 PHP和Delphi都內置了非常好的加密庫,如果你指定了相同的算法,它應該是兼容的。你有什麼理由不能使用它們嗎? – SDC
不回答你的問題,但'if(Action = UpperCase('C'))then'只是愚蠢的。 'UpperCase('C')'是'C'。這是否意味着'if(UpperCase(Action)='C')then',也許?如果是這樣,也許你應該改變你在PHP中執行比較的方式。 – hvd