凯撒(caesar)密码加解密方法

凯撒加密(Caesarcipher)是一种简单的消息编码方式:它根据字母表将消息中的每个字母移动常量位k。
举个例子如果k等于3,则在编码后的消息中,每个字母都会向前移动3位:
a会被替换为d;b会被替换成e;依此类推。字母表末尾将回卷到字母表开头。
于是,w会被替换为z,x会被替换为a
如果是将移动的位数用随机数进行代替,并且记录下该随机数,则破解密码的难度将大大增加。

一、加密解密的方法

这里写图片描述

二、C语言程序实现

#include <stdio.h> 
#include <stdlib.h>
int main (){
char small_letter[26]={'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'};
char big_letter[26]={'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'};
char text[1000],result[1000];
int c,count=0,k,p;
char function;
printf("Insert Text:");
c=getchar();
while(1) //读取字符串
    {
        if(c == '\n') break;
                text[count]=c;
        printf("%c",text[count]);
        count++;
        c=getchar();
    }

printf("\n");
printf("Encrypt or Decrypt? E or D :");
scanf("%c",&function);
if (function == 'E'){

    printf("Insert Key :" );
    scanf("%d",&k);
        for(int i=0;i<count;i++){
        if(text[i]>='A'&&text[i]<='Z')
        {
            result[i]=big_letter[((text[i]-'A')+k)%26];
        }
        //找出加密后字符在字符数组里的对应位置
        else if (text[i]>='a'&&text[i]<='z')
        {
            result[i]=small_letter[((text[i]-'a')+k)%26];
        }
        else result[i]=text[i];
        printf("%c",result[i]);
    }
}

else {
    printf("Insert Key :" );
    scanf("%d",&k);
        for(int i=0;i<count;i++){
        if(text[i]>='A'&&text[i]<='Z')
        {
            p=((text[i]-'A')-k);
            while(p<0)p+=26;
            result[i]=big_letter[p];
        }
        //找出解密后字符在字符数组里的对应位置
        //这里要注意不要让它超出范围(下表位置为负数)
        else if (text[i]>='a'&&text[i]<='z')
        {
            p=((text[i]-'a')-k);
            while(p<0)p+=26;
            result[i]=small_letter[p];
        }
        else result[i]=text[i];
        printf("%c",result[i]);
    }
    printf("\n");
}
return 0;
}

三、程序结果

这里写图片描述

四、参考文献

【1】维基百科
【2】凯撒密码
【3】凯撒密码c语言实现

发布了32 篇原创文章 · 获赞 32 · 访问量 4万+

猜你喜欢

转载自blog.csdn.net/Evan_love/article/details/80360212