Spritz stream cipher implement in PHP and Javascript


Ron Rivest and Jacob Schuldt have proposed replacing RC4 with an improved and slightly modified version dubbed Spritz.

<?php

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

function spritz($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)
    $w = 1;
    for ($z = 0, $k = 0, $i = 0, $j = 0, $res = '', $y = 0; $y < strlen($str); $y++)
    {
        $i = ($i + $w) % 256;
        $j = ($k + $s[($j + $s[$i]) % 256]) % 256;
        $k = ($k + $i + $s[$j]) % 256;
        $x = $s[$i];
        $s[$i] = $s[$j];
        $s[$j] = $x;
        $z = $s[($j + $s[($i + $s[($z + $k) % 256]) % 256]) % 256];
        $res .= $str[$y] ^ chr($z);
    }
    return $res;
}

?>

The value w, is relatively prime to the size of the S array (256). We choose w=1. You can choose any odd value like 1,3,5,7,9…

Javascript:

function spritz(t, e) {
  var i, n, r, a, s, o, z, k, w;
  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 (w = 1, z = 0, k = 0, s = 0, n = 0, o = 0; o < t.length; o++)
    s = (s + w) % 256,
    n = (k + i[(n + i[s]) % 256]) % 256,
    k = (k + s + i[s]) % 256,
    r = i[s],
    i[s] = i[n],
    i[n] = r,
    z = i[(n + i[(s + i[(z + k) % 256]) % 256]) % 256],
    a += String.fromCharCode(t.charCodeAt(o) ^ z);
  return a
}

Example:

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

Result:

www.tutorialspots.com

Try it yourself

Leave a Reply