又叫循环移位密码.它的加密方法是将明文中的每个字母用此字符在字母表中后面第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("请填写明文或者密文:
");
scanf("%s", plaintext);
printf("请选择加密方式,输入1加密,输入2解密
");
scanf("%d", &type);
if (type == 1) {
//加密
printf("请输入密钥k:
");
scanf("%d", &k);
encrypt(plaintext, ciphertext, k);
printf("明文%s的密文为:%s
", plaintext, ciphertext);
}
else if (type == 2) {
//解密
printf("请输入密钥k:
");
scanf("%d", &k);
decrypt(plaintext, ciphertext, k);
printf("密文%s的明文为:%s
", plaintext, ciphertext);
}
return 0;
}运行结果:


版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
如需转载请保留出处:https://bianchenghao.cn/bian-cheng-ri-ji/42935.html