C语言实现字符加密解密时,常采用简单的ASCII码偏移法:加密时将字符码值加上固定数值,解密时再减去同一数值,这一操作直观易懂,为后续代码示例奠定基础。

以下是一个简单的加密和解密字符的示例代码:
#include <stdio.h>// 加密字符函数void encrypt(char *str, int key) {for(int i=0; str[i] != ' '; i++) {str[i] = str[i] + key;}}// 解密字符函数void decrypt(char *str, int key) {for(int i=0; str[i] != ' '; i++) {str[i] = str[i] - key;}}int main() {char message[] = "Hello, World!";int key = 10;printf("Original message: %sn", message);// 加密encrypt(message, key);printf("Encrypted message: %sn", message);// 解密decrypt(message, key);printf("Decrypted message: %sn", message);return 0;}
在这个示例中,我们定义了一个加密函数encrypt和一个解密函数decrypt,并在main函数中使用这两个函数对字符进行加密和解密操作。加密时将字符的ASCII码值加上一个固定的值,解密时将其减去相同的值。最终输出原始消息、加密后的消息和解密后的消息。
该示例演示了基础加解密原理,但并非安全方案;在实际开发中,需采用更为复杂严谨的加密算法,才能切实保障数据的安全性。