Caesar加密与解密简单实现

默认密钥K=3,

加密程序

#include 
#include 
#include 
using namespace std;

int main(){
        freopen("Caesar1.txt","r",stdin);
        freopen("Caesar2.txt","w",stdout);
        string s;
        int k = 3;
        while(getline(cin,s)){
                for(int i=0;iif(s[i]>='a' && s[i]<='z'){
                                printf("%c",97 + (s[i]-97+3)%26);
                        }
                        else if(s[i]>='A' && s[i]<='Z'){
                                printf("%c",65 + (s[i]-65+3)%26);
                        }
                        else{
                                cout << s[i];
                        }
                }
                cout << endl;
        }
        fclose(stdin);//关闭重定向输入
        fclose(stdout);//关闭重定向输出
        return 0;
}

解密程序

#include

int main(){
    FILE *fp = fopen("Caesar2.txt", "rt");
    FILE *res = fopen("Caesar3.txt", "wt+");
    char ch;
    int k = 3;
    char r;


    if(fp == NULL)
        printf("Cannot open file\n");
    if(res == NULL)
        printf("Cannot open file\n");
    ch = fgetc(fp);
    while(ch != EOF){
        if(ch >= 65 && ch <= 90){
                r = (char)65 + (ch-65+26-3)%26;
                fputc(r, res);
        }
        else if(ch >= 97 && ch <= 122){
                r = (char)97+ (ch-97+26-3)%26;
                fputc(r, res);
        }
        else
                fputc(ch ,res);
        ch = fgetc(fp);
    }
    fclose(fp);
    fclose(res);
}

待加密文本

GYPQJLRQGPYLJRGQYPL
GQYPRGQPYJRGQYPGY
mj O lezi e hvieq
wpvkn vjg gpf qh yqtnf

加密后文本

JBSTMOUTJSBOMUJTBSO
JTBSUJTSBMUJTBSJB
pm R ohcl h kylht
zsynq ymj jsi tk btwqi

你可能感兴趣的:(▶︎计算机网络安全)