3 this.privateKey = keySetup(key);
4 this.byteStream = byteStreamGenerator(this.privateKey.slice(0));
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
12function convert(text) {
14 for (var i = 0, ii = text.length; i < ii; i++) { codes.push(text.charCodeAt(i)); }
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
23function 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]];
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
37var byteStreamGenerator = function* (K) {
42 [K[i], K[j]] = [K[j], K[i]];
43 yield (K[(K[i] + K[j]) % 256]);
48 * Encrypts the input text
49 * @param {String} input, the text to encrypt
50 * @return {String}, the encrypted text
52RC4.prototype.encrypt = function (input) {
54 for (var i = 0, ii = input.length; i < ii; i++) { outputText += ('00' + (input.charCodeAt(i) ^ this.byteStream.next().value).toString(16)).substr(-2); }
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)
63RC4.prototype.decrypt = function (input) {
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)); }