3

I am trying to decode the rc4 encoded value using follwong function.

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 $data; implode('', $data);
}

If i use this function to decode simple text it works fine, but when i go for bigger key, it gives something like this

Œù©>Ç ¾¾óÅ,ŒŒ£f®ãápXŽ×{

Which i am not getting what it is??? Can you please explain whats wrong with it?

My Key is f033b52440607260e131d4f4a0f55cae and data is: 4522261326835a46d78099e0

Sid
  • 108
  • 1
  • 1
  • 5
  • I don't know the algorithm, but there are plenty of implementations, eg: https://gist.github.com/farhadi/2185197 – Erwin Moller Nov 16 '15 at 14:30
  • Thank you for sharing this, but the implementation i have done is as per the RC4 algorithm. I am not getting what exactly the output returned by function? like is it something ASCII or hex or something else. – Sid Nov 16 '15 at 14:54
  • Aha, then you are like me and love to roll your own code. :-) The downside is, of course, you have to debug it on your own, too, most of the time. ;-) Sorry, I cannot help. – Erwin Moller Nov 16 '15 at 15:01

0 Answers0