سؤال

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!

هل كانت مفيدة؟

المحلول

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.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top