1)利用C\C++语言实现RC4算法(n=3),利用生成的密钥对“this is a test”进行加/解密(按对应位作模2加运算)。
# include <iostream>
# include<string.h>
# include<stdlib.h>
# include<math.h>
# include<algorithm>
# include<stdio.h>
using namespace std;
int s[256], k[256];
void initsk(int n, string str) //s表初始化,k表赋值
{
for(int i = 0; i < n; i ++)
s[i] = i;
for(int i, j = 0; i < n; i ++)
{
k[i] = (str[j] - '0') % n;
j ++;
if(j == str.length())
{
j = 0;
}
}
for(int i = 0, j = 0; i < n; i ++)
{
j = ( j + s[i] + k[i]) % n;
swap(s[i], s[j]);
}
}
string RC4(int n) //密钥流的产生
{
string str = "";
for(int i = 0, j = 0; i < n; )
{
i ++;
j = (j + s[i]) % n;
swap(s[i], s[j]);
int t = ( s[i] + s[j] ) % n;
str += s[t] + '0';
}
return str;
}
string jiajiemi(string wen, string miyaoliu) //加解密过程
{
int len = wen.length();
int len1 = miyaoliu.length();
string ans = "";
for(int i = 0, j = 0; i < len; i ++)
{
if(wen[i] == ' ')
{
ans += ' ';
continue;
}
int a = wen[i] ;
int b = miyaoliu[j] - '0';
int k =a ^ b;
ans += char(k) ;
j++;
if(j == len1)
{
j = 0;
}
}
return ans;
}
int main()
{
while(1)
{
string st;
int n;
printf("请输入n: ");
scanf("%d", &n);
n = pow(2, n);
printf("请输入密钥:\n");
cin>>st;
getchar();
initsk(n, st); //s表初始化,k表赋值
string str = RC4(n); //密钥流的产生
printf("请输入要加密的字符串:");
string mingwen;
getline(cin, mingwen);
string miwen = jiajiemi(mingwen, str); //加密
printf("加密后的密文为:\n");
cout<<miwen<<endl;
mingwen = jiajiemi(miwen, str); //解密
printf("解密后明文为:\n");
cout<<mingwen<<endl;
}
return 0;
}