Skip to content

Instantly share code, notes, and snippets.

@akanieski
Created January 20, 2014 15:48
Show Gist options
  • Save akanieski/8522448 to your computer and use it in GitHub Desktop.
Save akanieski/8522448 to your computer and use it in GitHub Desktop.
RC4 with support for ASCII Extended (Char Codes > 127)
/*
* RC4 symmetric cipher encryption/decryption
*
* @license Public Domain
* @param string key - secret key for encryption/decryption
* @param string str - string to be encrypted/decrypted
* @return string
*/
Number.toASCII = function(i) {
var t = document.createElement('div');
t.innerHTML = '&#' + i;
return t.innerHTML;
}
function rc4(key, str) {
var s = [], j = 0, x, res = '';
for (var i = 0; i < 256; i++) {
s[i] = i;
}
for (i = 0; i < 256; i++) {
j = (j + s[i] + key.charCodeAt(i % key.length)) % 256;
x = s[i];
s[i] = s[j];
s[j] = x;
}
i = 0;
j = 0;
for (var y = 0; y < str.length; y++) {
i = (i + 1) % 256;
j = (j + s[i]) % 256;
x = s[i];
s[i] = s[j];
s[j] = x;
res += Number.toASCII(str.charCodeAt(y) ^ s[(s[i] + s[j]) % 256]);
}
return res;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment