Optimize simple file XOR code

From: Date: Thu, 24 Jun 2004 11:13:52 +0000
Subject: Optimize simple file XOR code
Groups: php.general 
Request: Send a blank email to php-general+get-188939@lists.php.net to get a copy of this message
Hi! I'm using a very simple algorithm to encrypt files sent from the server "On Demand". The algorithm uses XOR for the encryption. My problem is that the code is very slow, it can only process about 40 KB per second on my system, so my question is, is there any more speed optimized way to write this code? Here is my function: function CryptFile($hash, $filename) { // The current position in the key generated below $key_pos = 0; // The key used is generated using another function. // Since this function is only called once it has // nothing to do with the performance of this function $key = GenerateKey($hash); $handle=fopen($filename, "r"); while (!feof($handle)) { // Set the time limit or the script will time out // on large files set_time_limit(30); $data = fread($handle,8192); for ($i=0; $i<strlen($data); $i++) { // Change the data read from the file by using // XOR with the key $data[$i] = $data[$i] ^ $key[$key_pos]; // Calculate the next position in the key $key_pos=($key_pos+1) % count($key); } // Return the encrypted version to the browser echo $data; } } My guess is that if one should start optimizing the code anywhere, it would be within the for-loop. Any ideas? Thanks in advance! Regards, Marcus

« previous php.general (#188939) next »