编写程序实现凯撒密码加密函数。
凯撒密码加密实现原理:
英文字母循环左移3位,Er(m)= m+3(mod26)4
参考格式:J
明文:how
密文:KRZ
#include <stdio.h>
#include <string.h>
int main()
{
char passwd[100];
int i;
printf("输入原文:");
scanf("%s",&passwd);
for(i=0; i<strlen(passwd); i++)
{
if(passwd[i] >= 'A' && passwd[i] <= 'Z')
{
passwd[i] = ((passwd[i]-'A')+3)%26+'A';
}
else if(passwd[i] >= 'a' && passwd[i] <= 'z')
{
passwd[i] = ((passwd[i]-'a')+3)%26+'a';
}
}
printf("加密后的密文:");
printf("%s",passwd);
return 0;
}
?密钥呢?
#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;
}
望采纳
不知道你这个问题是否已经解决, 如果还没有解决的话: