本篇内容主要讲解“如何用C语言实现凯撒密码加密解密”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“如何用C语言实现凯撒密码加密解密”吧!
又叫循环移位密码.它的加密方法是将明文中的每个字母用此字符在字母表中后面第k个字母替代.它的加密过程可以表示为下面的函数:E(m)=m+k(mod n)
其中:m为明文字母在字母表中的位置数;n为字母表中的字母个数;k为密钥;E(m)为密文字母在字母表中对应的位置数.
#include <stdio.h>
#include <string.h>
//加密
int encrypt(char* plaintext, char* ciphertext, int k)
{
int i, z = 0;
int l = strlen(plaintext); //获取明文的长度
for (i = 0; i < l; i++)
{
//判断大小写
if (plaintext[i] >= 'A' && plaintext[i] <= 'Z') {
ciphertext[z] = ( (plaintext[i] - 'A') + k) % 26 + 'A';
}
else if (plaintext[i] >= 'a' && plaintext[i] <= 'z') {
ciphertext[z] = ((plaintext[i] - 'a') + k) % 26 + 'a';
}
else { //判断是否是空格
ciphertext[z] = plaintext[i];
}
z++;
}
return 0;
}
//解密
int decrypt(char* plaintext, char* ciphertext, int k)
{
int i, z = 0;
int l = strlen(plaintext); //获取明文的长度
for (i = 0; i < l; i++)
{
//判断大小写
if (plaintext[i] >= 'A' && plaintext[i] <= 'Z') {
ciphertext[z] = (((plaintext[i] - 'A') - k)) % 26 + 'A';
if (((plaintext[i] - 'A') - k) < 0) {
ciphertext[z] = ciphertext[z] + 26;
}
}
else if (plaintext[i] >= 'a' && plaintext[i] <= 'z') {
ciphertext[z] = ( ((plaintext[i] - 'a') - k)) % 26 + 'a';
if (((plaintext[i] - 'a') - k) < 0) { //处理负数
ciphertext[z] = ciphertext[z] + 26;
}
}
else { //判断是否是空格
ciphertext[z] = plaintext[i];
}
z++;
}
return 0;
}
int main()
{
char plaintext[50] = "";
char ciphertext[50] = "";
int k;
int type;
printf("请填写明文或者密文:\n");
scanf("%s", plaintext);
printf("请选择加密方式,输入1加密,输入2解密\n");
scanf("%d", &type);
if (type == 1) {
//加密
printf("请输入密钥k:\n");
scanf("%d", &k);
encrypt(plaintext, ciphertext, k);
printf("明文%s的密文为:%s\n", plaintext, ciphertext);
}
else if (type == 2) {
//解密
printf("请输入密钥k:\n");
scanf("%d", &k);
decrypt(plaintext, ciphertext, k);
printf("密文%s的明文为:%s\n", plaintext, ciphertext);
}
return 0;
}
运行结果:
到此,相信大家对“如何用C语言实现凯撒密码加密解密”有了更深的了解,不妨来实际操作一番吧!这里是亿速云网站,更多相关内容可以进入相关频道进行查询,关注我们,继续学习!
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。
原文链接:https://blog.51cto.com/u_15420562/5725450