RC4 implementation in PHP and Javascript


In cryptography, RC4 (Rivest Cipher 4 also known as ARC4 or ARCFOUR meaning Alleged RC4, see below) is a stream cipher.

We provide some function RC4 in PHP and Javascript
PHP:

/**
 * @author www.Tutorialspots.com
 * @copyright 2012
 */

/* Stream cipher CR4 */
function rc4($str, $key)
{
    //Key-scheduling algorithm (KSA)
    for ($s = array(), $i = 0; $i < 256; $i++)
        $s[$i] = $i;

    for ($j = 0, $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;
    }
    //Pseudo-random generation algorithm (PRGA)
    for ($i = 0, $j = 0, $res = '', $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;
}

JS:

function rc4(t, e) {
  var i, n, r, a, s, o;
  for (i = [], n = 0, a = "", s = 0; s < 256; s++) i[s] = s;
  for (s = 0; s < 256; s++)
    n = (n + i[s] + e.charCodeAt((s % e.length))) % 256,
    r = i[s],
    i[s] = i[n],
    i[n] = (r);
  for (s = 0, n = 0, o = 0; o < t.length; o++)
    s = ((s + 1) % 256),
    n = ((n + i[s]) % 256),
    r = i[s],
    i[s] = i[n],
    i[n] = r,
    a += String.fromCharCode(t.charCodeAt(o) ^ i[(i[s] + i[n]) % 256]);
  return a
}

Example:

alert(rc4(rc4('www.tutorialspots.com', 'tutorialspots'), 'tutorialspots'))

Result:

www.tutorialspots.com

Try it yourself

Some RC4 variants
RC4A cipher implement in PHP and Javascript
VMPC stream cipher implement in PHP and Javascript
RC4+ stream cipher implement in PHP and Javascript
Spritz stream cipher implement in PHP and Javascript

Related Post

, ,

No comments yet.

Leave a Reply