Tuesday, February 21, 2017

Converting binary packing c# code to PHP

Leave a Comment

I am trying to convert the following c# code to PHP but I don't know which pack() arguments to use.

var xorkey = BitConverter.ToUInt32(filedata, 0) >> 8; xorkey *= 0x8083; 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(); 

Edit - Been working on it, what I have so far appears to work.

$xorkey = unpack("L", $filedata)[1] >> 8; $xorkey *= 32899; // 32899 == 0x8083  for ($i = 8; $i < strlen($filedata); $i += 4) {     $bytes = unpack("L", substr($filedata, $i))[1] ^ $xorkey;      // left to do: BitConverter.GetBytes($bytes).CopyTo(filedata, i);      // this doesn't work: $xorkey ^= unpack("L", substr($filedata, $i))[1]; } 

1 Answers

Answers 1

I'm not sure what you're trying to do there, but if you are trying to encrypt any data, you should get rid of that (at least weak) xor loop and use some strong cipher encryption algorithms. Besides this, the for loop you have, may result in array indexing errors if the data are not of multiply-4 length.

If you still want to convert this piece of code to PHP, then here how you can do it:

C# code and result

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 code and result

$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 
If You Enjoyed This, Take 5 Seconds To Share It

0 comments:

Post a Comment