0

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:

function rc4($key, $str) {
    $s = array();
    for ($i = 0; $i < 256; $i++) {
        $s[$i] = $i;
    }

    $j = 0;

    for ($i = 0; $i < 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 < 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;
}

And my file reading / decryption code is here:

$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);      
}

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.

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?

Thank you!

0x9BD0
  • 1,542
  • 18
  • 41

1 Answers1

1

You need to read the file and feed it to rc4 routine using a buffer whose size is a multiple of the key length (e.g. read and pass 512, 1024 bytes at a time etc.).

Not line by line, otherwise the key and the encrypted text are not "aligned" and you will get garbage as result.

Stefano Sanfilippo
  • 32,265
  • 7
  • 79
  • 80
  • I got an update, there is some line breaks at the end of specific lines... fgets will stop it's selection at the break line... I can't seem to see how to fix this... – 0x9BD0 Feb 27 '14 at 19:55
  • I made the same thing with fread... Now it is the right size, but it still doesn't work – 0x9BD0 Feb 27 '14 at 20:08