信息安全試驗二——DES加密算法c++
本渣表示沒有理解原理,照着書上敲了一發,運行無誤!算法
吐槽:手動S盒簡直喪心病狂,擴展置換表全是手動輸入,加密原理仍是很好理解,兩次異或,先混淆。數組
此代碼數據由老師給出,r[]與k[]數組可變。安全
#include<bits/stdc++.h> using namespace std; const int N=100+10; int r[N]= {1,0,0,0,0,0, 0,0,0,0,0,1, 0,1,1,1,1,1, 1,1,1,1,1,0, 1,0,0,0,0,0, 0,0,1,1,0,1, 0,1,0,0,0,0, 0,0,0,1,1,0 };//E擴展直接由表寫出 int k[N]= {1,1,1,1,0,0, 0,0,1,0,1,1, 1,1,1,0,0,1, 1,0,1,1,1,0, 0,1,1,1,0,1, 0,1,0,0,1,0, 1,0,0,0,0,0, 1,1,0,0,0,0 }; int a[N];//祕鑰加的結果 int len=0,s_boox[N];//s盒代換結果 int ans[N];//p置換後的結果 void ch(int tmp) { int temp[6],l=0; while(tmp) { temp[l++]=tmp%2; tmp/=2; } for(int i=l-1; i>=0; i--) s_boox[len++]=temp[i]; } void add()//祕鑰加 { for(int i=0; i<48; i++) a[i]=r[i]^k[i]; } int s1[4][16]= {{14,4,13,1,2,15,11,8,3,10,6,12,5,9,0,7},{0,15,7,4,14,2,13,1,10,6,12,11,9,5,3,8},{4,1,14,8,13,6,2,11,15,12,9,7,3,10,5,0},{15,12,8,2,4,9,1,7,5,11,3,14,10,0,6,13}}; int s2[4][16]= {{15,1,8,14,6,11,3,4,9,7,2,13,12,0,5,10},{3,13,4,7,15,2,8,14,12,0,1,10,6,9,11,5},{0,14,7,11,10,4,13,1,5,8,12,6,9,3,2,15},{13,8,10,1,3,15,4,2,11,6,7,12,0,5,14,9}}; int s3[4][16]= {{10,0,9,14,6,3,15,5,1,13,12,7,11,4,2,8},{13,7,0,9,3,4,6,10,2,8,5,14,12,11,15,1},{13,6,4,9,8,15,3,0,11,1,2,12,5,10,14,7},{1,10,13,0,6,9,8,7,4,15,14,3,11,5,2,12}}; int s4[4][16]= {{7,13,14,3,0,6,9,10,1,2,8,5,11,12,4,15},{13,8,11,5,6,15,0,3,4,7,2,12,1,10,14,9},{10,6,9,0,12,11,7,13,15,1,3,14,5,2,8,4},{3,15,0,6,10,1,13,8,9,4,5,11,12,7,2,14}}; int s5[4][16]= {{2,12,4,1,7,10,11,6,8,5,3,15,13,0,14,9},{14,11,2,12,4,7,13,1,5,0,15,10,3,9,8,6},{4,2,1,11,10,13,7,8,15,9,12,5,6,3,0,14},{11,8,12,7,1,14,2,13,6,15,0,9,10,4,5,3}}; int s6[4][16]= {{12,1,10,15,9,2,6,8,0,13,3,4,14,7,5,11},{10,15,4,2,7,12,9,5,6,1,13,14,0,11,3,8},{9,14,15,5,2,8,12,3,7,0,4,10,1,13,11,6},{4,3,2,13,9,5,15,10,11,14,1,7,6,0,8,13}}; int s7[4][16]= {{4,11,2,14,15,0,8,13,3,12,9,7,5,10,6,1},{13,0,11,7,4,9,1,10,14,3,5,12,2,15,8,6},{1,4,11,13,12,3,7,14,10,15,6,8,0,5,9,2},{6,11,13,8,1,4,10,7,9,5,0,15,14,2,3,12}}; int s8[4][16]= {{13,2,8,4,6,15,11,1,10,9,3,14,5,0,12,7},{1,15,13,8,10,3,7,4,12,5,6,11,0,14,9,2},{7,11,4,1,9,12,14,2,0,6,10,13,15,3,5,8},{2,1,14,7,4,10,8,13,15,12,9,0,3,5,6,11}}; int P[100]= {16,7,20,21,2,8,24,14,29,12,28,17,32,27,3,9,1,15,23,26,19,13,30,6,5,18,31,10,22,11,4,25}; void s_box() { len=0; int f=1; for(int i=0; i<48; i+=6,f++) { int x=0,r=(a[i]==1?2:0)+(a[i+5]==1?1:0);//行 int c=(a[i+1]==1?8:0)+(a[i+2]==1?4:0)+(a[i+3]==1?2:0)+(a[i+4]==1?1:0);//列 if(f==1) x=s1[r][c]; if(f==2) x=s2[r][c]; if(f==3) x=s3[r][c]; if(f==4) x=s4[r][c]; if(f==5) x=s5[r][c]; if(f==6) x=s6[r][c]; if(f==7) x=s7[r][c]; if(f==8) x=s8[r][c]; ch(x); } } void P_zhihuan() { for(int i=0; i<32; i++) ans[i]=s_boox[P[i]]; } void work()//實際上調用不少函數很費時間 { add(); s_box(); P_zhihuan();r printf("加密結果:"); for(int tt=1,i=0; i<32; i++,tt++) //32bit { printf("%d",ans[i]); if(tt==4) { printf(" "); tt=0; } } } void happy() { puts("\n What does the fox say?"); puts("Hatee-hatee-hatee-ho!"); puts("Joff-tchoff-tchoffo-tchoffo-tchoff!"); } int main() { work(); happy(); }