c++实现凯撒密码算法及UDP网络传输接收显示
时间: 2024-10-13 20:05:18 浏览: 31
凯撒密码算法实验
4星 · 用户满意度95%
凯撒密码是一种简单的加密技术,通过将明文字符按照固定的偏移量替换来实现加密。在C++中,你可以这样实现:
```cpp
#include <iostream>
#include <string>
// 函数用于加密
std::string caesar_cipher_encrypt(const std::string& plaintext, int shift) {
std::string ciphertext;
for (char c : plaintext) {
if (isalpha(c)) { // 检查是否为字母
char encrypted_c = static_cast<char>((c + shift - 'A') % 26 + 'A'); // 加密处理
ciphertext += encrypted_c;
} else {
ciphertext += c; // 非字母字符不变
}
}
return ciphertext;
}
// 函数用于解密
std::string caesar_cipher_decrypt(const std::string& ciphertext, int shift) {
return caesar_cipher_encrypt(ciphertext, -shift);
}
int main() {
std::string message = "Hello, World!";
int shift = 3; // 密钥
std::cout << "Original Message: " << message << std::endl;
std::string encrypted = caesar_cipher_encrypt(message, shift);
std::cout << "Encrypted Message: " << encrypted << std::endl;
// 解密示例
std::string decrypted = caesar_cipher_decrypt(encrypted, shift);
std::cout << "Decrypted Message: " << decrypted << std::endl;
return 0;
}
```
至于UDP网络传输和接收到的数据显示,首先你需要创建一个UDP套接字并监听数据。这里是一个基本的例子:
```cpp
#include <sys/socket.h>
#include <arpa/inet.h>
#include <unistd.h>
void send_data(char* data, const char* ip, int port) {
// 创建socket
int sock = socket(AF_INET, SOCK_DGRAM, 0);
struct sockaddr_in server_address;
server_address.sin_family = AF_INET;
server_address.sin_port = htons(port);
inet_pton(AF_INET, ip.c_str(), &server_address.sin_addr);
sendto(sock, data, strlen(data), 0, (struct sockaddr*)&server_address, sizeof(server_address));
close(sock);
}
void receive_and_display() {
int sock = socket(AF_INET, SOCK_DGRAM, 0);
struct sockaddr_in client_address;
socklen_t addr_size = sizeof(client_address);
char buffer[1024];
while (true) {
ssize_t bytes_received = recvfrom(sock, buffer, sizeof(buffer), 0, (struct sockaddr*)&client_address, &addr_size);
if (bytes_received > 0) {
std::cout << "Received: " << buffer << " from " << inet_ntoa(client_address.sin_addr) << ":" << ntohs(client_address.sin_port) << std::endl;
} else {
break;
}
}
close(sock);
}
int main() {
char message[] = "This is a UDP message.";
std::string encrypted = caesar_cipher_encrypt(message, shift); // 将上面的message替换成加密后的字符串
send_data(encrypted.c_str(), "your_server_ip", your_server_port); // 发送到服务器
receive_and_display(); // 接收并显示接收到的数据(注意这需要服务器端配合)
return 0;
}
```
阅读全文