凯撒密码加密解密c语言
时间: 2023-09-13 18:11:33 浏览: 146
凯撒密码是一种简单的加密方式,它将明文中的每个字符按照一定规律进行移位,从而得到密文。解密时,将密文中的每个字符按照相反的规律进行移位,就可以得到原文。
以下是C语言实现凯撒密码加密解密的示例代码:
```c
#include <stdio.h>
#include <string.h>
#define MAX_LEN 100
// 加密函数
void encrypt(char *str, int key) {
int len = strlen(str);
for (int i = 0; i < len; i++) {
if (str[i] >= 'a' && str[i] <= 'z') {
str[i] = 'a' + ((str[i] - 'a' + key) % 26);
} else if (str[i] >= 'A' && str[i] <= 'Z') {
str[i] = 'A' + ((str[i] - 'A' + key) % 26);
}
}
}
// 解密函数
void decrypt(char *str, int key) {
int len = strlen(str);
for (int i = 0; i < len; i++) {
if (str[i] >= 'a' && str[i] <= 'z') {
str[i] = 'a' + ((str[i] - 'a' - key + 26) % 26);
} else if (str[i] >= 'A' && str[i] <= 'Z') {
str[i] = 'A' + ((str[i] - 'A' - key + 26) % 26);
}
}
}
int main() {
char str[MAX_LEN];
int key;
// 获取用户输入
printf("请输入要加密的字符串:");
fgets(str, MAX_LEN, stdin);
printf("请输入加密密钥:");
scanf("%d", &key);
// 加密
encrypt(str, key);
printf("加密后的字符串为:%s", str);
// 解密
decrypt(str, key);
printf("解密后的字符串为:%s", str);
return 0;
}
```
在上面的代码中,我们定义了两个函数encrypt和decrypt,分别用于加密和解密操作。加密和解密的过程都是通过遍历明文或密文中的每个字符,并按照一定规律进行移位来实现的。在这里,我们规定只对英文字符进行加密和解密,忽略其他字符(如空格、数字等)。同时,我们假设输入的密钥是一个整数。在实际应用中,可能需要对输入的密钥进行一些限制,例如限制密钥的范围或长度等。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)