Skip to content

Instantly share code, notes, and snippets.

@dchest
Last active August 29, 2015 14:08
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save dchest/826465a3bc85100caaef to your computer and use it in GitHub Desktop.
Save dchest/826465a3bc85100caaef to your computer and use it in GitHub Desktop.
function rc4(f,F,g,G){for(var U=256,b=[],c=a=0,d;U>a;a++)b[a]=a;for(a=0;U>a;a++)c=(c+b[a]+f[a%F])%U,d=b[a],b[a]=b[c],b[c]=d;for(var e=c=a=0;e<G;e++)a++,a%=U,c+=b[a],c%=U,d=b[a],b[a]=b[c],b[c]=d,g[e]=b[(b[a]+b[c])%U]}
// Usage:
//
var key = [75, 101, 121]; // input bytes: "Key"
var out = new Array(10); // place for keystream bytes
rc4(key, key.length, out, out.length); // out now contains keystream: [235, 159, 119, 129, 183, 52, 202, 114, 167, 25]
@Tilka
Copy link

Tilka commented Oct 22, 2014

m=255;s=[];for(i=0;256>i;)s[i]=i++;for(i=j=0;256>i;)j=j+s[i]+b[i%c]&m,t=s[i],s[i++]=s[j],s[j]=t;i=j=0;for(q in d)j=j+s[i=i+1&m]&m,t=s[i],s[i]=s[j],s[j]=t,o(q^s[s[i]+t&m])

170 chars

(I have no idea if this even works...)

@lifthrasiir
Copy link

function rc4(f,F,g,G){for(var U=255,b=[],c=0,a=U,d;b[a]=a--;);for(;U-a++;b[a]=d)d=b[c=c+b[a]+f[a%F]&U],b[c]=b[a];for(f=c=a=0;f<G;g[f++]=b[d+b[c]&U])d=b[c=c+b[a=a+1&U]&U],b[c]=b[a],b[a]=d}

187 bytes with the matching signature and no scope leakage.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment