RC4加密解密算法的简单实现

来源:互联网 发布:网络贷款不还会怎么样 编辑:程序博客网 时间:2024/05/01 20:48

资料出处:http://www.cnblogs.com/louzhang/archive/2012/05/08/2490755.html

今天上午要上信安基础课了,所以在上课之前复习了下

看到了RC4,就想实现一遍,顺便当作复习咯

只不过太挫了,有一个地方理解错了

就是加密解密得用同一个S[]

这个S[]在加密或者解密的结束之后是改变了的

我一直没有注意到这个结果,所以一直在悲剧

下面就上代码了,写的极其的挫,也不想改了,反正已经了解了算法的流程了

不过这种风格也是我要改变的风格了(觉得之前符号什么的全写一起太难看了。。。)

注明:s和t数组用int或者char都可以的

#include<cstdio>#include<cstring>#include<cstdlib>#include<algorithm>#include<iostream>using namespace std;const int maxn=256+10;void init(char *s, char *t, int len, char *key){    for(int i = 0; i < maxn; i++){        s[i] = i;        t[i] = key[i % len];    }    for(int i = 0, j = 0; i < maxn; i++){        j = (j + s[i] + t[i]) % maxn;        swap(s[i], s[j]);    }}void RC4(char *s, char *data, char *ans){    int i = 0, j = 0;    int l = strlen(data);    //printf("%d\n",l);    for(int k = 0; k < l; k ++){        i = (i + 1) % maxn;        j = (j + s[i]) % maxn;        swap(s[i], s[j]);        int t = (s[i] + s[j]) % maxn;        ans[k] = s[t] ^ data[k];        cout<<ans[k];    }    puts("");    ans[l] = '\0';}int main(){    char key[maxn];    puts("input key");    scanf("%s", key);    char keys[maxn];    strcpy(keys,key);    char s[maxn], t[maxn];    //init(s, t, strlen(key), key);    while(true){        init(s, t, strlen(keys), keys);        puts("select it:");        puts("1: Encryption");        puts("2: Decryption");        int sel;        scanf("%d", &sel);        if(sel != 1 && sel != 2) break;        switch(sel){            case 1:puts("inputs your message");break;            case 2:puts("inputs your Ciphertext");        }        char data[maxn];        char ans[maxn];        //scanf("%s", data);        getchar();        gets(data);        RC4(s, data, ans);        printf("\n%s\n", ans);    }    return 0;}


原创粉丝点击