c语言编程实现凯撒算法,能够实现加密和解密
时间: 2023-11-10 14:11:44 浏览: 67
好的,关于你的问题,C语言编程实现凯撒算法可以实现加密和解密。以下是一个实现加密和解密的C语言代码示例:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void encrypt(char *plaintext, int key)
{
int i = 0;
while (plaintext[i] != '\0') {
if ((plaintext[i] >= 'A') && (plaintext[i] <= 'Z')) {
plaintext[i] = ((plaintext[i] - 'A') + key) % 26 + 'A';
} else if ((plaintext[i] >= 'a') && (plaintext[i] <= 'z')) {
plaintext[i] = ((plaintext[i] - 'a') + key) % 26 + 'a';
}
i++;
}
printf("Encrypted text: %s\n", plaintext);
}
void decrypt(char *ciphertext, int key)
{
int i = 0;
while (ciphertext[i] != '\0') {
if ((ciphertext[i] >= 'A') && (ciphertext[i] <= 'Z')) {
ciphertext[i] = ((ciphertext[i] - 'A') - key + 26) % 26 + 'A';
} else if ((ciphertext[i] >= 'a') && (ciphertext[i] <= 'z')) {
ciphertext[i] = ((ciphertext[i] - 'a') - key + 26) % 26 + 'a';
}
i++;
}
printf("Decrypted text: %s\n", ciphertext);
}
int main()
{
char text[100];
int key;
printf("Enter text: ");
fgets(text, sizeof(text), stdin);
text[strcspn(text, "\n")] = '\0';
printf("Enter key: ");
scanf("%d", &key);
encrypt(text, key);
decrypt(text, key);
return 0;
}
```
在这个示例代码中, `encrypt` 函数使用凯撒算法加密输入的明文,并 `decrypt` 函数使用相同的凯撒算法解密密文。函数中的 `key` 参数是用于加密和解密的偏移量。程序首先要求用户输入要加密的文本和加密/解密偏移量,最后显示加密后的文本和解密后的文本。
希望能够帮到你,如果你有更多问题,可以继续问我!