zoukankan      html  css  js  c++  java
  • RC4加密解密算法的简单实现

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

    看到了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;
    }
  • 相关阅读:
    yum只下载不安装的方法
    在VS2008下编译Qt4.4.x
    Linux sh脚本异常:bad interpreter: No such file or directory
    动态链接库dll,静态链接库lib, 导入库lib 转
    Accumulation Buffer(累积缓存)
    mysql中ip和整数的转换
    开车撞人了!
    windows 下getc()返回0x1A表示EOF
    NPC问题
    关于普华永道、麦肯锡和IBM的笑话
  • 原文地址:https://www.cnblogs.com/louzhang/p/2490755.html
Copyright © 2011-2022 走看看