var JJY = {};//定义模块变量;
JJY.RC4 = function RC4(pwd, data, t) {
    var cipher = "";
    var key = [];
    var box = [];
    var pwd_length = pwd.length;

    if (t == 1) {
        data = hexToString(data);
    }

    var data_length = data.length;

    for (var i = 0; i < 256; i++) {
        key[i] = pwd.charCodeAt(i % pwd_length);
        box[i] = i;
    }

    for (var j = i = 0; i < 256; i++) {
        j = (j + box[i] + key[i]) % 256;
        var tmp = box[i];
        box[i] = box[j];
        box[j] = tmp;
    }

    for (var a = j = i = 0; i < data_length; i++) {
        a = (a + 1) % 256;
        j = (j + box[a]) % 256;
        var tmp = box[a];
        box[a] = box[j];
        box[j] = tmp;
        var k = box[((box[a] + box[j]) % 256)];
        cipher += String.fromCharCode(data.charCodeAt(i) ^ k);
    }

    if (t == 1) {
        return decodeURIComponent(escape(cipher));
    } else {
        return stringToHex(cipher);
    }
}

function hexToString(hex) {
    var string = "";
    for (var i = 0; i < hex.length; i += 2) {
        string += String.fromCharCode(parseInt(hex.substr(i, 2), 16));
    }
    return string;
}

function stringToHex(string) {
    var hex = "";
    for (var i = 0; i < string.length; i++) {
        hex += string.charCodeAt(i).toString(16).padStart(2, '0');
    }
    return hex;
}
module.exports = JJY;
