能否提供一个C语言实现的基本加密代码示例,比如简单的替换加密或者 Caesar Cipher(凯撒密码)?
时间: 2024-10-17 18:04:51 浏览: 48
当然可以,这里是一个简单的Caesar Cipher(凯撒密码)在C语言中的实现例子。这个版本将每个字符向后移动指定的位数。例如,如果偏移量为3,字母A将变为D,B变为其后的E,以此类推。
```c
#include <stdio.h>
#include <string.h>
void caesar_cipher(char* str, int shift) {
int len = strlen(str);
for (int i = 0; i < len; ++i) {
if ('a' <= str[i] && str[i] <= 'z') { // 对小写字母进行处理
str[i] = ((str[i] - 'a' + shift) % 26) + 'a';
} else if ('A' <= str[i] && str[i] <= 'Z') { // 对大写字母进行处理
str[i] = ((str[i] - 'A' + shift) % 26) + 'A';
}
}
}
int main() {
char plaintext[] = "Hello, World!";
int shift_amount = 3;
caesar_cipher(plaintext, shift_amount);
printf("Encrypted text: %s\n", plaintext); // 输出加密后的文本
return 0;
}
```
在这个程序中,`caesar_cipher`函数接受一个字符串和一个偏移量,然后遍历字符串中的每个字符,根据ASCII值将其转换为相应的凯撒密码。注意,这里只对英文字符进行了处理,对于其他非英文字符不做改变。
阅读全文
相关推荐


















