Skip to content

Instantly share code, notes, and snippets.

@imaya
Created October 12, 2012 07:19
Show Gist options
  • Save imaya/3877757 to your computer and use it in GitHub Desktop.
Save imaya/3877757 to your computer and use it in GitHub Desktop.
Arcfour encryption
goog.provide('ArcfourString');
goog.scope(function() {
/**
* Arcfour implementation.
* @param {string} key secret key.
* @param {string} plainString plain text.
* @param {number=} opt_dummyLoop dummy encryption loop count.
* @return {string}
*/
function ArcfourString(key, plainString, opt_dummyLoop) {
/** @type {!(Array.<number>|Uint8Array)} */
var s = new (goog.global.Uint8Array !== void 0 ? Uint8Array : Array)(256);
/** @type {number} */
var i;
/** @type {number} */
var j;
/** @type {number} */
var tmp;
/** @type {number} */
var k;
/** @type {number} */
var kl;
/** @type {number} */
var x;
/** @type {Array.<string>} */
var charArray;
// initialize S-box
for (i = 0; i < 256; ++i) {
s[i] = i;
}
// shuffle S-box
for (i = j = 0, kl = key.length; i < 256; ++i) {
j = (j + s[i] + key.charCodeAt(i % kl) & 0xff) & 0xff;
tmp = s[i];
s[i] = s[j];
s[j] = tmp;
}
// initialize
i = j = 0;
charArray = [];
// dummy loop
if (typeof opt_dummyLoop === 'number') {
for (k = 0, kl = opt_dummyLoop; k < kl; ++k) {
i = (i + 1) & 0xff;
j = (j + s[i]) & 0xff;
tmp = s[i];
s[i] = s[j];
s[j] = tmp;
}
}
// encryption
for (x = -1, k = 0, kl = plainString.length; k < kl;) {
i = (i + 1) & 0xff;
j = (j + s[i]) & 0xff;
tmp = s[i];
s[i] = s[j];
s[j] = tmp;
if (x < 0) {
x = s[(s[i] + s[j]) % 0xff];
} else {
tmp = plainString.charCodeAt(k);
charArray[k] = String.fromCharCode(
(((tmp >> 8) ^ x ) << 8) |
(( tmp & 0xff) ^ s[(s[i] + s[j]) % 0xff])
);
x = -1;
++k;
}
}
// clear
i = j = k = x = tmp = 0;
for (i = 0; i < 256; ++i) {
s[i] = 0;
}
s = null;
return charArray.join('');
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment