今天上午要上信安基礎課了,所以在上課之前復習了下
看到了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; }