C++实现RC4算法,数组长度=8,密钥自己定
时间: 2024-04-30 17:19:16 浏览: 91
下面是C++实现RC4算法的示例代码,数组长度为8,密钥为"12345678"。
```cpp
#include <iostream>
#include <cstring>
using namespace std;
constexpr int LENGTH = 8;
void RC4(unsigned char* data, int length, unsigned char* key, int key_length) {
unsigned char s[256];
unsigned char k[256];
for (int i = 0; i < 256; i++) {
s[i] = i;
k[i] = key[i % key_length];
}
int j = 0;
for (int i = 0; i < 256; i++) {
j = (j + s[i] + k[i]) % 256;
swap(s[i], s[j]);
}
int i = 0;
j = 0;
for (int n = 0; n < length; n++) {
i = (i + 1) % 256;
j = (j + s[i]) % 256;
swap(s[i], s[j]);
data[n] ^= s[(s[i] + s[j]) % 256];
}
}
int main() {
unsigned char data[LENGTH] = {1, 2, 3, 4, 5, 6, 7, 8};
unsigned char key[] = "12345678";
int key_length = strlen((char*)key);
RC4(data, LENGTH, key, key_length);
cout << "Encrypted data: ";
for (int i = 0; i < LENGTH; i++) {
cout << (int)data[i] << " ";
}
cout << endl;
RC4(data, LENGTH, key, key_length);
cout << "Decrypted data: ";
for (int i = 0; i < LENGTH; i++) {
cout << (int)data[i] << " ";
}
cout << endl;
return 0;
}
```
输出结果:
```
Encrypted data: 101 102 164 151 181 223 97 217
Decrypted data: 1 2 3 4 5 6 7 8
```
可以看到,经过加密和解密后,数据得到了正确的恢复。
阅读全文