1 //Virginia密码 2 /*理解算法最重要,最好自己动手实现试试看,可以使用MFC写一个简单的交互界面*/ 3 #include<iostream> 4 #include<cstring> 5 6 using namespace std; 7 #define MINCHAR 32 8 #define CHARSUM 94 9 char table[CHARSUM][CHARSUM]; 10 bool Init(); 11 bool Encode(char* key, char* source, char* dest); 12 bool Dncode(char* key, char* source, char* dest); 13 int main() 14 { 15 if(!Init()) 16 { 17 cout << "初始化错误!" << endl; 18 return 1; 19 } 20 char key[256]; 21 char str1[256]; 22 char str2[256]; 23 int operation; 24 while(1) 25 { 26 do 27 { 28 cout << "请选择一个操作:1. 加密; 2. 解密; -1. 退出\n"; 29 cin >> operation; 30 }while(operation != -1 && operation != 1 && operation != 2); 31 if(operation == -1) 32 return 0; 33 else if(operation == 1)//加密 34 { 35 cout << "请输入密钥:"; 36 cin >> key; 37 cout << "请输入待加密字符串:"; 38 cin >> str1; 39 Encode(key, str1, str2); 40 cout << "加密后的字符串:" << str2 << endl; 41 } 42 else if(operation == 2)//解密 43 { 44 cout << "请输入密钥:"; 45 cin >> key; 46 cout << "请输入待解密字符串:"; 47 cin >> str1; 48 Dncode(key, str1, str2); 49 cout << "解密后的字符串:" << str2 << endl; 50 } 51 cout << endl; 52 } 53 return 0; 54 } 55 // 初始化维吉尼亚方阵 56 bool Init() 57 { 58 int i, j; 59 for(i = 0; i < CHARSUM; i++) 60 { 61 for(j = 0; j < CHARSUM; j++) 62 { 63 table[i][j] = MINCHAR + (i + j) % CHARSUM; 64 } 65 } 66 return true; 67 } 68 // 加密 69 // key:密钥 70 // source:待加密的字符串 71 // dest:经过加密后的字符串 72 bool Encode(char* key, char* source, char* dest) 73 { 74 char* tempSource = source; 75 char* tempKey = key; 76 char* tempDest = dest; 77 do 78 { 79 *tempDest = table[(*tempKey) - MINCHAR][(*tempSource) - MINCHAR]; 80 tempDest++; 81 if(!(*(++tempKey))) 82 tempKey = key; 83 }while(*tempSource++); 84 dest[strlen(source)] = 0; 85 return true; 86 } 87 // 解密 88 // key:密钥 89 // source:待解密的字符串 90 // dest:经过解密后的字符串 91 bool Dncode(char* key, char* source, char* dest) 92 { 93 char* tempSource = source; 94 char* tempKey = key; 95 char* tempDest = dest; 96 char offset; 97 do 98 { 99 offset = (*tempSource) - (*tempKey); 100 offset = offset >= 0 ? offset : offset + CHARSUM; 101 *tempDest = MINCHAR + offset; 102 tempDest++; 103 if(!(*(++tempKey))) 104 tempKey = key; 105 }while(*++tempSource); 106 dest[strlen(source)] = 0; 107 return true; 108 }