问题描述
- RC4编程为何加密结果是乱码,而且求逆解码的结果与明文不同,多谢~
-
#include
#include
using namespace std;void main()
{
char k[256];
int s[256],t[256];cout<<"please input key"<<endl; cin>>k; cout<<endl; for(int i=0;i<256;i++) { s[i]=i; t[i]=k[i%strlen(k)]; //将输入的密钥扩展为256位 } int j=0; for(i=0;i<256;i++) { int temp; j=(j+s[i]+t[i])%256; temp=s[i]; s[i]=s[j]; s[j]=temp; //s-box的变换,打乱原有的顺序 } cout<<"please input plaintext"<<endl; char plaintext[256],ciphertext[256]; int static key[256]; cin>>plaintext; for(i=0;i<256;i++) { cout<<s[i]<<" "; } cout<<endl; cout<<strlen(plaintext); cout<<endl; j=0; int m,n,q; m=n=0; for(i=0;i<strlen(plaintext);i++) //循环产生和明文一样长的key密钥流 { int temp; m=(m+1)%256; n=(n+s[m])%256; temp=s[m]; s[m]=s[n]; s[n]=temp; int q; q=(s[i]+s[j])%256; key[i]=s[q]; cout<<plaintext[i]<<"("; ciphertext[i]=plaintext[i]^key[i]; cout<<ciphertext[i]; } cout<<endl; cout<<"/n密钥流是:"; for(i=0;i<strlen(plaintext);i++) { cout<<key[i]<<" "<<plaintext[i]; cout<<endl; } cout<<"密文是:"; for(i=0;i<strlen(plaintext);i++) { cout<<int(ciphertext[i]); }
cout<<endl;
cout<<"解密后明文为:"<<endl;
int a[256];
for(i=0;i<strlen(plaintext);i++)
{
a[i]=ciphertext[i]^key[i];
cout<<a[i];
}}
时间: 2024-10-01 14:32:52