如何用C语言写一个凯撒密码
时间: 2023-12-29 16:45:07 浏览: 50
凯撒密码是一种古老的加密方式,将明文中的每个字母按照一定的位移量向后(或向前)移动,得到密文。下面是用C语言实现凯撒密码的代码:
```c
#include <stdio.h>
#include <string.h>
void caesar_encrypt(char *text, int shift) {
int length = strlen(text);
for (int i = 0; i < length; i++) {
// 只对字母进行加密,忽略其他字符
if (text[i] >= 'a' && text[i] <= 'z') {
text[i] = 'a' + (text[i] - 'a' + shift) % 26;
}
else if (text[i] >= 'A' && text[i] <= 'Z') {
text[i] = 'A' + (text[i] - 'A' + shift) % 26;
}
}
}
void caesar_decrypt(char *text, int shift) {
// 解密即为加密过程的逆过程
caesar_encrypt(text, 26 - shift);
}
int main() {
char text[100];
int shift;
printf("请输入明文:\n");
fgets(text, sizeof(text), stdin);
printf("请输入位移量:\n");
scanf("%d", &shift);
caesar_encrypt(text, shift);
printf("加密后的密文为:%s\n", text);
caesar_decrypt(text, shift);
printf("解密后的明文为:%s\n", text);
return 0;
}
```
代码中的`caesar_encrypt`函数用于加密,`caesar_decrypt`函数用于解密。其中,`shift`参数表示位移量,可以是任意整数。输入明文和位移量后,程序会先对明文进行加密,然后再对密文进行解密,输出最终的明文。