key为密钥~
#include<iostream>
#include<string>
using namespace std;
int s[256];
int t[256];
string key="0123456789";
void swap(int* s1,int* s2){
int temp=*s1;
*s1=*s2;
*s2=temp;
}
void init(){
//初始化s和t数组
for(int i=0;i<256;i++){
s[i]=i;
t[i]=atoi(&(const char)(key.at(i%key.length())));
}
int j=0;
for(int i=0;i<256;i++){
j=(j+s[j]+t[j])%256;
swap(s+i,s+j);
}
}
void encode(int* start,int length){
int pos=0;
int i=0,j=0;
while(pos++<length){
i=(i+1)%256;
j=(j+s[i])%256;
swap(s+i,s+j);
int temp=(s[i]+s[j])%256;
int k=s[temp];
*start^=k;
start++;
}
}
void decode(int* start,int length){
encode(start,length);
}
void print(int* a,int length,string startMessage=""){
cout<<startMessage<<" ";
for(int i=0;i<length;i++){
cout<<*(a+i)<<" ";
}
cout<<endl;
}
int main(){
init();
int a[10]={0,1,2,3,4,5,6,7,8,9};
print(a,10,"原数组");
encode(a,10);
print(a,10,"加密后");
init();
decode(a,10);
print(a,10,"解密后");
}
#include<string>
using namespace std;
int s[256];
int t[256];
string key="0123456789";
void swap(int* s1,int* s2){
int temp=*s1;
*s1=*s2;
*s2=temp;
}
void init(){
//初始化s和t数组
for(int i=0;i<256;i++){
s[i]=i;
t[i]=atoi(&(const char)(key.at(i%key.length())));
}
int j=0;
for(int i=0;i<256;i++){
j=(j+s[j]+t[j])%256;
swap(s+i,s+j);
}
}
void encode(int* start,int length){
int pos=0;
int i=0,j=0;
while(pos++<length){
i=(i+1)%256;
j=(j+s[i])%256;
swap(s+i,s+j);
int temp=(s[i]+s[j])%256;
int k=s[temp];
*start^=k;
start++;
}
}
void decode(int* start,int length){
encode(start,length);
}
void print(int* a,int length,string startMessage=""){
cout<<startMessage<<" ";
for(int i=0;i<length;i++){
cout<<*(a+i)<<" ";
}
cout<<endl;
}
int main(){
init();
int a[10]={0,1,2,3,4,5,6,7,8,9};
print(a,10,"原数组");
encode(a,10);
print(a,10,"加密后");
init();
decode(a,10);
print(a,10,"解密后");
}