c语言凯撒密码前后端代码
时间: 2023-09-24 12:09:11 浏览: 53
Sure! Here's an example of the Caesar Cipher encryption and decryption code in C language:
```c
#include <stdio.h>
// Function to encrypt the message using Caesar Cipher
void encrypt(char message[], int key) {
char ch;
int i;
for(i = 0; message[i] != '\0'; ++i) {
ch = message[i];
if(ch >= 'a' && ch <= 'z') {
ch = ch + key;
if(ch > 'z') {
ch = ch - 'z' + 'a' - 1;
}
message[i] = ch;
}
else if(ch >= 'A' && ch <= 'Z') {
ch = ch + key;
if(ch > 'Z') {
ch = ch - 'Z' + 'A' - 1;
}
message[i] = ch;
}
}
printf("Encrypted message: %s\n", message);
}
// Function to decrypt the message using Caesar Cipher
void decrypt(char message[], int key) {
char ch;
int i;
for(i = 0; message[i] != '\0'; ++i) {
ch = message[i];
if(ch >= 'a' && ch <= 'z') {
ch = ch - key;
if(ch < 'a') {
ch = ch + 'z' - 'a' + 1;
}
message[i] = ch;
}
else if(ch >= 'A' && ch <= 'Z') {
ch = ch - key;
if(ch < 'A') {
ch = ch + 'Z' - 'A' + 1;
}
message[i] = ch;
}
}
printf("Decrypted message: %s\n", message);
}
int main() {
char message[100];
int key;
printf("Enter a message: ");
scanf("%[^\n]s", message);
printf("Enter key: ");
scanf("%d", &key);
encrypt(message, key);
decrypt(message, key);
return 0;
}
```
In this code, the `encrypt` function takes a message and a key as input and encrypts the message using the Caesar Cipher algorithm. The `decrypt` function takes an encrypted message and the same key as input and decrypts the message.
The `main` function prompts the user to enter a message and a key, and then calls the `encrypt` and `decrypt` functions accordingly. Finally, it prints the encrypted and decrypted messages.
Please note that this is a basic implementation of the Caesar Cipher and may not include error handling or additional features.