凯撒加解密算法C语言实现

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

如果是将移动的位数用随机数进行代替,并且记录下该随机数,则破解密码的难度将大大增加。

//linux c 代码

#include<stdlib.h>
#include<string.h>
#include<stdio.h>
//加密
int kaisa_encrypt(const char *str1,char *str2,const  int len)
{
    int i;
    if(str1 == NULL || str2 == NULL || len <= 0){
        return -1;
    }
    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
            str2[i]=str1[i];                                                                                 
    }
    return 0;
}
//解密
int kaisa_decrypt(const char *str2,char *str3, const int len)
{
    int i;
    char all_letter[26]="abcdefghijklmnopqrstuvwxyz";
    if(str3 == NULL || str2 == NULL || len <=0){
        return -1;
    }
    int m = strlen(str2);
    if(m <= 0){
        return -1;
    }
    for(i=0;i<m;i++)
    {
        if(str2[i]>=all_letter[len]&&str2[i]<='z')
            str3[i]=str2[i]-len;
        else if(str2[i]>='a'&&str2[i]<=all_letter[len-1])
            str3[i]=str2[i]+(26-len);
        else
            str3[i]=str2[i];
    }
    return 0;
}

int main()
{
    char str1[20]="binbin";
    char str2_encrypt[20]="";
    char str3_decrypt[20]="";
    /***加密****/
    kaisa_encrypt(str1,str2_encrypt,3);
    printf("原文%s-->密文%s\n",str1,str2_encrypt);
    /***解密****/
    kaisa_decrypt(str2_encrypt,str3_decrypt,3);
    printf("密文%s-->原文%s\n",str2_encrypt,str3_decrypt);

    return 0;
} 
  • 4
    点赞
  • 34
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值