【資訊保安】Caesar加密
阿新 • • 發佈:2018-11-22
#include<stdio.h> #include<iostream> #include<stdlib.h> #include <string.h> #define N 100 using namespace std; //凱撒密碼 //加密公式 f(a)=(a+3) mod 26 //解密公式 f(a)=(a+23) mod 26 void Encry(char *strI,int numB,int model);//加密公式函式 void Decry(char *strI,int numB,int model);//解密公式函式 int FileOut(char *strI); int main() { char str[N];//加密的字串 int model; int numB;//偏移量 while(1) { cout<<"凱撒密碼:請選擇模式:\n"; cout<<"1.加密\n"; cout<<"2.解密\n"; cout<<"3.退出\n"; cin>>model; cout<<endl; switch(model) { case 1: cout<<"請輸入要加密的字串:"; cin>>str; cout<<"請輸入該密碼演算法的偏移數量:"; cin>>numB; Encry(str,numB,model); cout<<endl; break; case 2: cout<<"請輸入要解密的字串:"; cin>>str; cout<<"請輸入原密碼演算法的偏移數量:"; cin>>numB; Decry(str,numB,model); cout<<endl; break; case 3: return 0; break; default: break; } } return 0; } void Encry(char *strI,int numB,int model) {//明文串 祕鑰 功能模式 if(model==1)//加密還是解密模式 { for(int i=0; i<strlen(strI); i++)//strlen確定字串長度 { if(strI[i] >= 'A' && strI[i] <= 'Z') { strI[i] = (strI[i]+numB)%26;//numB為偏移量 // f(a)=(a+3) mod 26 } else if(strI[i] >= 'a' && strI[i] <= 'z') { strI[i] = ((strI[i]-'a')+numB)%26+'a'; } } cout<<"加密完成:"<<strI<<endl; FileOut(strI); cout<<"已輸出到檔案!"<<endl; } else { cout<<"該模式不支援此項功能!"<<endl; } } void Decry(char *strI,int numB,int model) { if(model==2) { int num; num=26-numB; for(int i=0; i<strlen(strI); i++) { if(strI[i] >= 'A' && strI[i] <= 'Z') { strI[i] = ((strI[i]-'A')+num)%26+'A'; } else if(strI[i] >= 'a' && strI[i] <= 'z') { strI[i] = ((strI[i]-'a')+num)%26+'a'; } } cout<<"解密完成:"<<strI<<endl; } else { cout<<"該模式不支援此項功能!"<<endl; } } int FileOut(char *strI)//void Decry(char *strI,int numB,int model) { FILE *fp = NULL; int iWrite=0; int len=strlen(strI); if( strI == NULL || len ==0 ) return false; //! 開啟檔案控制代碼 if( (fp = fopen( "密文.txt","w" )) == NULL ) // 文字模式寫 return false; iWrite = fwrite(strI, 1, len, fp ); fclose(fp); if( iWrite>0 ) return true; else return false; }