Skip to content

Instantly share code, notes, and snippets.

@jonelf
Last active April 29, 2016 07:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jonelf/b1148d2f4c44c848f7ed to your computer and use it in GitHub Desktop.
Save jonelf/b1148d2f4c44c848f7ed to your computer and use it in GitHub Desktop.
Code golfing of the cipher RC4 in Ruby, 140 characters.
def e(k,t);s=*((j=q=w=0)..l=256);k*=l;(0..l).map{|i|j+=s[i]+k[i];s[i],s[j%=l]=s[j%=l],s[i]};(0...t.size).map{|i|q+=1;w=(w+s[q%=l])%l;s[q],s[w]=s[w],s[q];t[i]=t[i]^s[(s[q]+s[w])%l]};t;end
key = "test".chars.map(&:ord)
text = "test".chars.map(&:ord)
e(key, text) == [218, 234, 84, 101]
# e=->k,t{k*=l=256;j=q=w=0;s=*0..l;l.times{|i|j+=s[i]+k[i];s[i],s[j]=s[j%=l],s[i]};t.map{|c|w+=s[q+=1];s[q],s[w]=s[w%=l],s[q];c^s[(s[q]+s[w])%l]}}
e=->k,t{j=q=w=0;s=*0..l=256;l.times{|i|j+=s[i]+k[i];s[i],s[j]=s[j%=l],s[i]};t.map{|c|w+=s[q+=1];s[q],s[w]=s[w%=l],s[q];c^s[(s[q]+s[w])%l]}}
e[key, text] == [218, 234, 84, 101]
@jonelf
Copy link
Author

jonelf commented May 3, 2015

$ e([116, 101, 115, 116],[116, 101, 115, 116])
=> [218, 234, 84, 101]

@jonelf
Copy link
Author

jonelf commented Sep 10, 2015

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