Skip to content

Instantly share code, notes, and snippets.

@mikesmullin
Last active August 29, 2015 14:00
Show Gist options
  • Save mikesmullin/11105741 to your computer and use it in GitHub Desktop.
Save mikesmullin/11105741 to your computer and use it in GitHub Desktop.
A CoffeeScript implementation of RC4
# A CoffeeScript implementation of RC4
class ARC4
i: 0
j: 0
psize: 256
S: null
constructor: (key=null) ->
@S = new Buffer(@psize)
if key
@init key
init: (key) ->
i = j = t = 0
for i in [0...@psize]
@S[i] = i
for i in [0...@psize]
j = (j + @S[i] + key[i%key.length]) & 255
t = @S[i]
@S[i] = @S[j]
@S[j] = t
@i=0
@j=0
next: ->
@i = (@i+1)&255
@j = (@j+@S[@i])&255
t = @S[@i]
@S[@i] = @S[@j]
@S[@j] = t
return @S[(t+@S[@i])&255]
encrypt: (block) ->
i = 0
while (i<block.length)
block[i++] ^= @next()
decrypt: (block) ->
@encrypt block # the beauty of XOR
key = "hello"
keyBuffer = new Buffer key
cipher = new ARC4 keyBuffer
input = "encrypt this"
inputBuffer = new Buffer input
outputBuffer = new Buffer input
cipher.encrypt outputBuffer
console.log key: key, keyBuffer: keyBuffer, input: input, inputBuffer: inputBuffer, outputBuffer: outputBuffer
decryptBuffer = outputBuffer # TODO: .clone()
cipher = new ARC4 keyBuffer
cipher.decrypt decryptBuffer
console.log decryptBuffer: decryptBuffer, decrypt: decryptBuffer.toString()
@mikesmullin
Copy link
Author

{ key: 'hello',
  input: 'encrypt this',
  inputBuffer: <Buffer 65 6e 63 72 79 70 74 20 74 68 69 73>,
  outputBuffer: <Buffer 80 8b 86 97 9c 95 91 c5 91 8d 8c 96> }
{ decryptBuffer: <Buffer 65 6e 63 72 79 70 74 20 74 68 69 73>,
  decrypt: 'encrypt this' }

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