揭秘C语言实现凯撒密码:轻松上手加密解密技巧

凯撒密码,作为历史上最简单的加密方法之一,一直是学习密码学和编程的基础。本文将详细介绍如何在C语言中实现凯撒密码的加密与解密,并为您提供实用的技巧,帮助您轻松上手。
凯撒密码原理
凯撒密码是一种替换加密技术,通过将字母表中的每个字母按照固定的位移进行移动来实现加密。例如,使用密钥3时,字母A会被替换成D,B替换成E,依此类推。解密时,只需将密文中的每个字母反向移动相同的位数即可。
加密公式
加密后的字母 = (原字母位置 + 移位数) % 26
解密公式
原字母位置 = (加密后的字母位置 – 移位数) % 26
C语言实现凯撒密码
以下是一个简单的C语言程序,实现凯撒密码的加密与解密:
加密函数
void encrypt(char *plaintext, int key, char *result) {
while (*plaintext) {
if (*plaintext >= ‘A’ && *plaintext <= 'Z') { *result = 'A' + ((*plaintext - 'A' + key) % 26); } else if (*plaintext >= ‘a’ && *plaintext <= 'z') { *result = 'a' + ((*plaintext - 'a' + key) % 26); } else { *result = *plaintext; } plaintext++; result++; } *result = '\0'; } 解密函数 void decrypt(char *ciphertext, int key, char *result) { while (*ciphertext) { if (*ciphertext >= ‘A’ && *ciphertext <= 'Z') { *result = 'A' + ((*ciphertext - 'A' - key + 26) % 26); } else if (*ciphertext >= ‘a’ && *ciphertext <= 'z') { *result = 'a' + ((*ciphertext - 'a' - key + 26) % 26); } else { *result = *ciphertext; } ciphertext++; result++; } *result = '\0'; } 主函数 #include
#include

int main() {
char plaintext[100], ciphertext[100], result[100];
int key;

printf(“Enter the plaintext: “);
fgets(plaintext, sizeof(plaintext), stdin);
plaintext[strcspn(plaintext, “\n”)] = 0; // Remove newline character

printf(“Enter the key (number of positions to shift): “);
scanf(“%d”, &key);

encrypt(plaintext, key, ciphertext);
printf(“Encrypted text: %s\n”, ciphertext);

decrypt(ciphertext, key, result);
printf(“Decrypted text: %s\n”, result);

return 0;
}
总结
通过以上代码,我们可以轻松地实现凯撒密码的加密和解密。在实际应用中,您可以根据需要修改程序,例如增加输入验证、处理大写字母和小写字母等。此外,凯撒密码的安全性较低,因此在实际加密应用中并不推荐使用。