1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81
| <?php
// Stream files and encrypt the data on-the-fly
// Settings
// -- File to stream
$file = "bin-in";
// -- Reading buffer
$bufferlength = 3840;
// -- Key in hex
$keychar = "9cdfb439c7876e703e307864c9167a15";
// Function: Convertion hex key in a string into binary
function hex2bin($h) {
if (!is_string($h)) return null;
$r = array();
for ($a=0; ($a*2)<strlen($h); $a++) {
$ta = hexdec($h[2*$a]);
$tb = hexdec($h[(2*$a+1)]);
$r[$a] = (int) (($ta << 4) + $tb);
//echo "a=".$ta." , b=".$tb." , r[".$a."]=".$r[$a]." <br />";
}
return $r;
}
// Headers
$headers = "";
$headers .= "Content-Type: application/octet-stream; ";
$headers .= "Content-Length: " . filesize($file) ."; ";
$headers .= "filename=\"".$file."\"; ";
header($headers);
flush(); // this doesn't really matter.
// Convert key and set the size of the key
$key = hex2bin($keychar);
$keylength = 16;
// Opening the file in read-only
$fp = fopen($file, "r");
while (!feof($fp))
{
// Read a buffer size of the file
$buffer = fread($fp, $bufferlength);
$j=0;
for ($i=0; $i < $bufferlength; $i++) {
// The key is read in loop to crypt the whole file
if ($i%$keylength == 0) {
$j=0;
}
// Apply a xor operation between the key and the file to crypt
// This operation eats a lots of CPU time (Stream at 0.5MiB/s on my server; Intel E2180 !!!)
$tmp = pack("C", $key[$j]);
$bufferE = ( $buffer[$i]^$tmp); // <==== Le fameux XOR
/*
echo "<br />key[".$j."]: ";
var_dump($tmp);
echo "<br />buffer[".$i."]: ";
var_dump($buffer[$i]);
echo "<br />bufferE: ";
var_dump($bufferE);
echo "<br />";
//*/
// Send the encrypted data
echo $bufferE;
// Clean the memory
$bufferE = "";
$j++;
}
$buffer = "";
flush(); // this is essential for large downloads
/*
fclose($fp);
exit();
//*/
}
// Close the file and it's finished
fclose($fp);
?> |
Partager