title: RC4 decryption line by line
body: <p>I have to convert some files that may eventually go to 250 mb with a php script. They are encrypted with an rc4 encryption with a key and a description contained in the first 266 bytes of the file. I have an encryption function that is working and that I have to keep as is. Here it is:</p>
  
  <pre><code>function rc4($key, $str) {
      $s = array();
      for ($i = 0; $i &lt; 256; $i++) {
          $s[$i] = $i;
      }
  
      $j = 0;
  
      for ($i = 0; $i &lt; 256; $i++) {
          $j = ($j + $s[$i] + ord($key[$i % strlen($key)])) % 256;
          $x = $s[$i];
          $s[$i] = $s[$j];
          $s[$j] = $x;
      }
  
      $i = 0;
      $j = 0;
      $res = '';
  
      for ($y = 0; $y &lt; strlen($str); $y++) {
          $i = ($i + 1) % 256;
          $j = ($j + $s[$i]) % 256;
          $x = $s[$i];
          $s[$i] = $s[$j];
          $s[$j] = $x;
          $res .= $str[$y] ^ chr($s[($s[$i] + $s[$j]) % 256]);
      }
  
      return $res;
  }
  </code></pre>
  
  <p>And my file reading / decryption code is here:</p>
  
  <pre><code>$fin = fopen("input.txt", "rb");
  $fout = fopen("output.txt", "wb");
  
  $contents = fgets($fin,10);
  $mykey = fgets($fin,256);
  
  if($contents =="dump"){
      while(!feof($fin))
      {
          $line = fgets($fin);
          fwrite($fout, rc4($mykey, $line));
      }
      fclose($fin);
      fclose($fout);      
  }
  </code></pre>
  
  <p>Previously, the code was accepting some small files and was converting them by reading the hole content of it and by passing it to the rc4 function... Now that the code needs to handle some larger file, I have to do it by line by line.</p>
  
  <p>The file that is generated is corrupted... Is it because an rc4 encryption needs the hole "string" to be decrypted? Am I doing something that is wrong?</p>
  
  <p>Thank you!</p>