| 1 | |
| 2 | function RC4(key) { |
| 3 | this.privateKey = keySetup(key); |
| 4 | this.byteStream = byteStreamGenerator(this.privateKey.slice(0)); |
| 5 | } |
| 6 | |
| 7 | /** |
| 8 | * Converts the text into an array of the characters numeric Unicode values |
| 9 | * @param {String} text, the text to convert |
| 10 | * @return {Array} the array of Unicode values |
| 11 | */ |
| 12 | function convert(text) { |
| 13 | var codes = []; |
| 14 | for (var i = 0, ii = text.length; i < ii; i++) { codes.push(text.charCodeAt(i)); } |
| 15 | return codes; |
| 16 | } |
| 17 | |
| 18 | /** |
| 19 | * Sets up the key to use with the byte stream |
| 20 | * @param {String} key, The key that you want to use |
| 21 | * @return {Array}, the key stream which with be used in the byteStreamGenerator |
| 22 | */ |
| 23 | function keySetup(key) { |
| 24 | var K = [...Array(256).keys()], j = 0, key = convert(key); |
| 25 | for (var i = 0, ii = K.length; i < ii; i++) { |
| 26 | j = (j + K[i] + key[i % key.length]) % 256; |
| 27 | [K[i], K[j]] = [K[j], K[i]]; |
| 28 | } |
| 29 | return K; |
| 30 | } |
| 31 | |
| 32 | /** |
| 33 | * byteStreamGenerator uses ES6 generators which will be 'XOR-ed' to encrypt and decrypt |
| 34 | * @param {Array} K, the array generated from the keySetup |
| 35 | * @yield {Integer}, the current value which will be 'XOR-ed' to encrypt or decrypt |
| 36 | */ |
| 37 | var byteStreamGenerator = function* (K) { |
| 38 | var i = 0, j = 0; |
| 39 | while (true) { |
| 40 | i = (i + 1) % 256; |
| 41 | j = (j + K[i]) % 256; |
| 42 | [K[i], K[j]] = [K[j], K[i]]; |
| 43 | yield (K[(K[i] + K[j]) % 256]); |
| 44 | } |
| 45 | } |
| 46 | |
| 47 | /** |
| 48 | * Encrypts the input text |
| 49 | * @param {String} input, the text to encrypt |
| 50 | * @return {String}, the encrypted text |
| 51 | */ |
| 52 | RC4.prototype.encrypt = function (input) { |
| 53 | var outputText = ''; |
| 54 | for (var i = 0, ii = input.length; i < ii; i++) { outputText += ('00' + (input.charCodeAt(i) ^ this.byteStream.next().value).toString(16)).substr(-2); } |
| 55 | return outputText; |
| 56 | } |
| 57 | |
| 58 | /** |
| 59 | * Decrypts the input text |
| 60 | * @param {String} input, the text to decrypt |
| 61 | * @return {String}, the decrypted text (if the same key was used) |
| 62 | */ |
| 63 | RC4.prototype.decrypt = function (input) { |
| 64 | var outputText = ''; |
| 65 | input = input.match(/[a-z0-9]{2}/gi); |
| 66 | for (var i = 0, ii = input.length; i < ii; i++) { outputText += String.fromCharCode((parseInt(input[i], 16) ^ byteStream.next().value)); } |
| 67 | return outputText; |
| 68 | } |
| 69 | |
| 70 | module.exports = RC4; |