凯撒加密

1、凯撒加密(Caesarcipher)
凯撒加密是一种简单的消息编码方式:它根据字母表将消息中的每个字母移动常量位k(密钥)。
例如:如果k等于3,则在编码后的消息中,每个字母都会向前移动3位:a(明文)会被替换为d(密文);b会被替换成e;依此类推。字母表末尾将回卷到字母表开头。于是,w会被替换为z,x会被替换为a。
如果是将移动的位数用随机数进行代替,并且记录下该随机数,则破解密码的难度将大大增加。
请同学们自己设计移位的次数和方法,实现对任意输入的字符串实现加密和解密。要求:
(1)定义加密函数:encrypt( )实现加密。
(2)定义解密函数:decrypt( )实现解密。
(3)定义main( )函数:输入任意字符串,调用加密和解密函数完成加密与解密功能。
2、文件移位加密与解密
理解上面的凯撒加密之后,再实现对文件的加密与解密。将某一已知文件的内容(仅限于英文字母)以字符形式读出,根据密钥(用户从键盘输入)将对应字符进行移位操作即可,解密时移动相反。
例如:加密:设原文为abcdef,密钥为5,则有abcdef每个字母按字母表向后移动5们(注:z后接a)可得到密文(乱码)fghijkl;对该文件解密:文件内容为fghijk1,密钥为5,则有fghijk1每个字母向前移动5位(注a后接z),可得到原文abcdef。
要求同上实现:
(1)文件加密;( 2)文件解密;(3)main()测试。

源代码:

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<time.h>
int kaisa_encrypt(const char *str1,char *str2,const  int len);
int kaisa_decrypt(const char *str2,char *str3,const int len);
int main()
{
    char str1[20];
    char str2_encrypt[20]="";
    char str3_decrypt[20]="";
    printf("产生随机密匙:") ;
    int k;
    srand(time(0));
    k=rand()%26+1;
    printf("%d\n",k);
    /*scanf("%d",&k);*/ 
    printf("请输入原文:") ; 
    getchar();
    gets(str1);
    /***加密***/
    kaisa_encrypt(str1,str2_encrypt,k);
    printf("原文%s-->密文%s\n",str1,str2_encrypt);
    /***解密***/
    kaisa_decrypt(str2_encrypt,str3_decrypt,k);
    printf("密文%s-->原文%s\n",str2_encrypt,str3_decrypt);

    return 0;
} 
//加密
int kaisa_encrypt(const char *str1,char *str2,const  int len)
{
    int i;
    int m = strlen(str1);
    if(m <= 0){
        return -1;
    }
    for(i=0;i<m;i++)
    {
        if(str1[i]>='a'&&str1[i]<='z')
            str2[i]='a'+(str1[i]-'a'+len)%26;
        else if(str1[i]>='A'&&str1[i]<='Z')
            str2[i]='A'+(str1[i]-'A'+len)%26;
        else
            str2[i]=str1[i];                                                                                 
    }
    return 0;
}
//解密
int kaisa_decrypt(const char *str2,char *str3, const int len)
{
    int i;
    char small_letter[26]="abcdefghijklmnopqrstuvwxyz";
    char big_letter[26]="ABCDEFGHIJKLMNOPQRSTUVWXYZ";

    int m = strlen(str2);
    if(m <= 0){
        return -1;
    }//若字符串长度小于等于0则不继续进行 
    for(i=0;i<m;i++)
    {
        if((str2[i]>=small_letter[len]&&str2[i]<='z')||(str2[i]>=big_letter[len]&&str2[i]<='Z'))
            str3[i]=str2[i]-len;
        else if((str2[i]>='a'&&str2[i]<=small_letter[len-1])||(str2[i]>='A'&&str2[i]<=big_letter[len-1]))
            str3[i]=str2[i]+(26-len);
        else
            str3[i]=str2[i];
    }
    return 0;
}





  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值