简易Caesar cipher程式撰写

一种最简单且多为人知的加密技术。它是一种替换加密的技术,明文中的所有字母都在字母表上向后或向前按照一个数字进行位移后被替换成密文。

例如,当位移量为4的时候,所有的字母A将被替换成E,B被替换成F,以此类推。凯撒密码通常被作为其他加密方法中的步骤,例如维吉尼亚密码。但碍于英文字母长度有限,凯萨密码非常容易被破解,在实际应用上也无法保证通信安全。

在程式上的编写操作,凯撒密码的加密、解密方法是通过同余的数学方法进行计算。首先将英文字母用数字代替,A=0,B=1,…,Z=25。此时偏移量为n的加密方法即为:

                          f(a)=(a+n) mod 26

解密就是:

                          f(a)=(a-n) mod 26

 

以下为程式码:

/*Caesar cipher*/
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>

int main(){
    char *data;                                      //输入    
    char *target=malloc(100 * sizeof(char));         //输出 
    int key=0;                                       //金钥 
    FILE *fPtr;
    unsigned long leng, count, i;
    int ch;
    
    //读档(须先建立source.txt) 
    fPtr = fopen("source.txt", "r");
    fseek(fPtr, 0, SEEK_END);
    leng = ftell(fPtr);
    fseek(fPtr, 0, SEEK_SET);
    data = (char *) malloc((leng + 1) * sizeof(char));
    fread(data, 1, leng, fPtr);  
    fclose(fPtr);
    data[leng] = '\0';
      
    printf("\n读入档案: %s\n\n", data);
    printf("请选择加密或解密 1.解密(位移向前) 2.加密(位移向后) : ");
    scanf("%d",&ch);
    printf("请输入位移量(范围为0~25) : ");
    scanf("%d",&key);
    
    //转大写
    count = 0;
    for (i=0; i<leng; i++)
    if (isalpha(data[i])) data[count++] = toupper(data[i]);
    data[count] = '\0';
    
    switch(ch){
        case 1:    //向前         
            i = 0; 
            while (data[i] != '\0') {
            if (isalpha(data[i])){
            target[i]=data[i] - 65;
            target[i]=(target[i]+26-key)%26;
            target[i]=target[i]+97;
            } 
            else target[i] = data[i]; 
            i++; 
            }
            target[i] = '\0';
            printf("\n明文 : %s\n\n", target); 
            break;
        case 2:    //向后               
            i = 0; 
            while (data[i] != '\0') {
            if (isalpha(data[i])){
            target[i]=data[i] - 65;
            target[i]=(target[i]+26+key)%26;
            target[i]=target[i]+97;
            } 
            else target[i] = data[i]; 
            i++; 
            }
            target[i] = '\0';
            printf("\n密文 : %s\n\n", target); 
            break;
        default:
            printf("\n错误\n");
            break;    
    }
    
    //输出档案 
    fPtr = fopen("result.txt", "w");
    fwrite(target, 1, count, fPtr);
    fclose(fPtr);
    
    system("pause");
    return 0;
}

 

输出结果:

加密:

 

解密:

相关文章