我不知道你想在那裏做什麼,但如果你想加密的任何數據,你應該擺脫的那個(至少弱)XOR迴路,並使用一些強cipher encryption algorithms。除此之外,如果數據不是乘以4的長度,則for循環可能會導致數組索引錯誤。
如果你仍然想這段代碼到PHP的轉換,那麼在這裏你可以怎麼做:
C#代碼,並導致
byte[] filedata = new byte[] { 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88 };
var xorkey = BitConverter.ToUInt32(filedata, 0) >> 8;
//xorkey *= 0x8083;
/* It's important to convert the result to UInt32,
* because the multiplication of a 32bit integer with an other big integer,
* may result in a 64bit integer
*/
xorkey = Convert.ToUInt32(xorkey * 0x8083);
//Console.WriteLine("xorkey == {0}", xorkey); // xorkey == 4473666
for (var i = 8; i < filedata.Length; i += 0x4)
{
BitConverter.GetBytes(BitConverter.ToUInt32(filedata, i)^xorkey).CopyTo(filedata, i);
xorkey ^= BitConverter.ToUInt32(filedata, i);
}
filedata = filedata.Skip(4).ToArray();
// Result filedata will contain the following data
// 45 46 47 48 8f 20 c4 8 4 4 4 1c 1c 1c 1c 4 4 4 4 c
PHP代碼,並導致
$filedata = pack('C*', 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88);
$xorkey = unpack("L", $filedata)[1] >> 8;
$xorkey = (int)($xorkey * 0x8083);
// echo '$xorkey == '.$xorkey.PHP_EOL; // $xorkey == 4473666
for ($i = 8; $i < strlen($filedata); $i += 4) {
$n = unpack("L", substr($filedata, $i, 4))[1];
$filedata = substr_replace($filedata, pack('L', $n^$xorkey), $i, 4);
$xorkey ^= unpack("L", substr($filedata, $i, 4))[1];
}
$filedata = substr($filedata, 4);
// Result $filedata will contain the following data
//45 46 47 48 8f 20 c4 8 4 4 4 1c 1c 1c 1c 4 4 4 4 c
非常感謝! – Pierre