JS RC4加解密报文

JS RC4加解密

RC4(来自Rivest Cipher 4的缩写)是一种流加密算法,密钥长度可变。它加解密使用相同的密钥,因此也属于对称加密算法。RC4加密算法原理 , 对明文使用同一个密钥异或两次最后是得到原文。
这个不是加解密字符串,它是用于协议数据传输过程中通信报文的加密

const RC4_KEY_LEN_MAX = 256;

var rc4CalcTemplate = {
	Rc4Key : "65osdbsfidcxza", // 自己约定的密钥
	Keylen : 0,
	Rc4Sbox : new Array(256),
};

/*初始化函数*/
function rc4_init(){
	rc4CalcTemplate.Keylen = rc4CalcTemplate.Rc4Key.length;
	var j=0;
	var k = new Array(256);
	var tmp = 0;

	for(let i = 0; i < 256; i++){
		rc4CalcTemplate.Rc4Sbox[i] = i;
		k[i] = String(rc4CalcTemplate.Rc4Key[i%rc4CalcTemplate.Keylen]).charCodeAt(0);
	}

	for(let i = 0;i < 256; i++){
		j = (j + rc4CalcTemplate.Rc4Sbox[i] + k[i]) % 256;
        tmp = rc4CalcTemplate.Rc4Sbox[i];
        rc4CalcTemplate.Rc4Sbox[i]= rc4CalcTemplate.Rc4Sbox[j];//交换s[i]和s[j]
        rc4CalcTemplate.Rc4Sbox[j] = tmp;
	}
}
/*加解密*/
function rc4_crypt(Data, Len){
	var i = 0, j = 0, t = 0,sLen = 0;
    var k = 0;
    var tmp;
    var s = new Array(RC4_KEY_LEN_MAX);
    var result = new Array(Len);
    for (sLen = 0; sLen < RC4_KEY_LEN_MAX; sLen++)
    {
        s[sLen] = rc4CalcTemplate.Rc4Sbox[sLen];
    }
    for (k = 0; k < Len; k++)
    {
        i = (i + 1) % 256;
        j = (j + s[i]) % 256;
        tmp = s[i];
        s[i] = s[j];//交换s[x]和s[y]
        s[j] = tmp;
        t = (s[i] + s[j]) % 256;
        result[k] = Data[k] ^ s[t];
    }
    return result;
}
/* 初始化 */
rc4_init();
var input = [0x75, 0x9A, 0xC0, 0x89, 0x18, 0x06, 0x76, 0xC9, 0x52, 0x0C, 0x49, 0x76, 0x3B, 0x35, 0xA9, 0x13, 0x81, 0x48, 0xBE, 0x9C, 0xE1, 0x08, 0xA7, 0x01, 0x9A, 0xD9, 0xB4, 0x57, 0xA4, 0xDE, 0x42, 0x7E, 0x99, 0x55, 0x05, 0x63, 0x78, 0xC7, 0xB8];
var result= rc4_crypt(input, input.length);

你可能感兴趣的:(JavaScript基础知识)