RC4 PHP解密失败

时间:2014-11-03 04:37:38

标签: php encryption rc4-cipher

我使用rc4加密加密了字符串。我可以解密我加密的第一个字符串。但我无法成功解密第二个字符串。任何的想法?

我的代码

$dpl = 256;
$file = fopen( 'log', "w");
$key = 'sjhdjhd';
$content1 = rc4($key,str_repeat(" ",$dpl).'ABC');
$content1 = substr($content1,$dpl);
$content2 = rc4($key,str_repeat(" ",$dpl).'DEFG');
$content2 = substr($content2,$dpl);
fwrite($file, $content1);
fwrite($file, $content2);
fclose( $file );

$file = fopen( 'log', "r");
while ( $buff = fread( $file, 256 ) ) {
    $plaintext = rc4($key,str_repeat(" ",$dpl).$buff);
    echo substr($plaintext,$dpl).PHP_EOL;
}

fclose( $file );


function rc4($key, $data)
{
    // Store the vectors "S" has calculated
    static $SC;
    // Function to swaps values of the vector "S"
    $swap = create_function('&$v1, &$v2', '
        $v1 = $v1 ^ $v2;
        $v2 = $v1 ^ $v2;
        $v1 = $v1 ^ $v2;
    ');
    $ikey = crc32($key);
    if (!isset($SC[$ikey])) {
        // Make the vector "S", basead in the key
        $S    = range(0, 255);
        $j    = 0;
        $n    = strlen($key);
        for ($i = 0; $i < 255; $i++) {
            $char  = ord($key{$i % $n});
            $j     = ($j + $S[$i] + $char) % 256;
            $swap($S[$i], $S[$j]);
        }
        $SC[$ikey] = $S;
    } else {
        $S = $SC[$ikey];
    }
    // Crypt/decrypt the data
    $n    = strlen($data);
    $data = str_split($data, 1);
    $i    = $j = 0;
    for ($m = 0; $m < $n; $m++) {
        $i        = ($i + 1) % 256;
        $j        = ($j + $S[$i]) % 256;
        $swap($S[$i], $S[$j]);
        $char     = ord($data[$m]);
        $char     = $S[($S[$i] + $S[$j]) % 256] ^ $char;
        $data[$m] = chr($char);
    }
    return implode('', $data);
}

0 个答案:

没有答案