简介
RC4 - 维基百科
没事水一水v🤣
代码
class RC4 {
public:
RC4(const unsigned char *key, unsigned int key_len)
{
// 初始化S盒,临时T盒
for (int i = 0; i < 256; i++) {
_S[i] = i;
_T[i] = key[i % key_len];
}
// 打乱S盒
for (int i = 0, j = 0; i < 256; i++) {
j = (j + _S[i] + _T[i]) % 256;
unsigned char tmp = _S[i];
_S[i] = _S[j];
_S[j] = tmp;
}
}
virtual ~RC4()
{
}
unsigned int convert(unsigned char *ptr, unsigned int len)
{
int i = 0, j = 0;
memcpy(_T, _S, 256);
// 生成密钥流,进行加解密
for(unsigned int k = 0; k < len; k++) {
i = (i + 1) % 256;
j = (j = _T[i]) % 256;
unsigned char tmp = _T[i];
_T[i] = _T[j];
_T[j] = tmp;
ptr[k] = ptr[k] ^ _T[(_T[i] + _T[j]) % 256];
}
return len;
}
private:
unsigned char _S[256]{ 0 };
unsigned char _T[256]{ 0 };
};