Last active
August 29, 2015 14:00
-
-
Save mikesmullin/11105741 to your computer and use it in GitHub Desktop.
A CoffeeScript implementation of RC4
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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() |
Author
mikesmullin
commented
Apr 20, 2014
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment