Creating a secure chat application in C++ using RSA encryption involves several steps, including setting up networking, key generation, encryption/decryption, and message handling. Below is a comprehensive guide to building such an application using Asio for networking and OpenSSL for cryptographic operations. We'll use Code::Blocks as the IDE on Windows.
Table of Contents
- Prerequisites
- Setting Up the Development Environment
- Project Structure Overview
- Implementing the Server
- Implementing the Client
- Compiling and Running the Application
- Complete Source Code
Prerequisites
Before diving into the implementation, ensure you have the following installed on your Windows machine:
Setting Up the Development Environment
1. Install OpenSSL
-
Download OpenSSL: Choose the appropriate version (e.g., Win64) from Shining Light Productions.
-
Install OpenSSL: Follow the installer instructions. Note the installation directory (e.g., C:\OpenSSL-Win64).
-
Set Environment Variables:
- Add
C:\OpenSSL-Win64\bin to your system's PATH to access OpenSSL DLLs.
2. Install Asio
-
Download Asio: Standalone Asio Download
-
Extract Asio: Extract the contents to a known directory (e.g., C:\asio-1.18.2).
3. Configure Code::Blocks
-
Open Code::Blocks.
-
Create a New Project: For both server and client.
-
Set Include and Library Paths:
-
Include Directories:
- OpenSSL headers:
C:\OpenSSL-Win64\include
- Asio headers:
C:\asio-1.18.2\include
-
Library Directories:
- OpenSSL libraries:
C:\OpenSSL-Win64\lib
-
Link Libraries:
- Add the following libraries:
libssl.lib
libcrypto.lib
Ws2_32.lib (Windows Sockets)
Crypt32.lib (Cryptographic functions)
Note: Ensure that the compiler can find these libraries by setting them in the project's linker settings.
Project Structure Overview
We'll create two separate applications:
- Server: Handles client connections, stores public keys, and routes messages.
- Client: Connects to the server, manages RSA keys, sends/receives encrypted messages.
1. Server
- Responsibilities:
- Accept multiple client connections.
- Receive and store each client's public key.
- Handle requests for other clients' public keys.
- Forward encrypted messages to the intended recipients.
2. Client
- Responsibilities:
- Generate RSA key pair on startup.
- Connect to the server and send the public key.
- Request other users' public keys to encrypt messages.
- Decrypt received messages using the private key.
- Provide a user interface for sending and receiving messages.
Implementing the Server
The server will use Asio to handle asynchronous networking and manage multiple client connections. It will maintain a map of usernames to their public keys and manage message forwarding.
Server Steps:
-
Initialize Asio: Create an IO service and acceptor to listen for incoming connections.
-
Handle New Connections: Assign each client connection to a session.
-
Manage Client Sessions: In each session, handle incoming data such as public keys, public key requests, and messages.
-
Store Public Keys: Maintain a thread-safe map of usernames to their RSA public keys.
-
Forward Messages: When a message is received destined for another user, forward the encrypted message to the appropriate session.
Sample Server Code
Below is a simplified version of the server implementation. For brevity, error handling and some Asio async patterns are simplified.
// server.cpp
#include <iostream>
#include <string>
#include <unordered_map>
#include <asio.hpp>
#include <mutex>
using asio::ip::tcp;
// Structure to hold client information
struct ClientInfo {
std::string username;
std::string public_key;
std::shared_ptr<tcp::socket> socket;
};
// Global storage for clients
std::unordered_map<std::string, ClientInfo> clients;
std::mutex clients_mutex;
void handle_client(std::shared_ptr<tcp::socket> socket) {
try {
asio::streambuf buf;
std::istream is(&buf);
while (true) {
// Read until newline
asio::read_until(*socket, buf, "\n");
std::string line;
std::getline(is, line);
if (line.empty()) continue;
// Simple protocol parsing
// Commands: REGISTER, GETKEY, MESSAGE
if (line.substr(0, 8) == "REGISTER") {
// Format: REGISTER username public_key
size_t pos1 = line.find(' ', 9);
std::string username = line.substr(9, pos1 - 9);
std::string public_key = line.substr(pos1 + 1);
std::lock_guard<std::mutex> lock(clients_mutex);
clients[username] = ClientInfo{ username, public_key, socket };
std::cout << "Registered user: " << username << std::endl;
}
else if (line.substr(0, 6) == "GETKEY") {
// Format: GETKEY username
std::string target = line.substr(7);
std::lock_guard<std::mutex> lock(clients_mutex);
if (clients.find(target) != clients.end()) {
std::string response = "KEY " + target + " " + clients[target].public_key + "\n";
asio::write(*socket, asio::buffer(response));
}
else {
std::string response = "ERROR User not found\n";
asio::write(*socket, asio::buffer(response));
}
}
else if (line.substr(0, 7) == "MESSAGE") {
// Format: MESSAGE to_username encrypted_message
size_t pos1 = line.find(' ', 8);
std::string to_user = line.substr(8, pos1 - 8);
std::string encrypted_msg = line.substr(pos1 + 1);
std::lock_guard<std::mutex> lock(clients_mutex);
if (clients.find(to_user) != clients.end()) {
std::string forward = "MESSAGE from " + to_user + ": " + encrypted_msg + "\n";
asio::write(*clients[to_user].socket, asio::buffer(forward));
}
else {
std::string response = "ERROR Recipient not found\n";
asio::write(*socket, asio::buffer(response));
}
}
}
}
catch (std::exception& e) {
std::cerr << "Client disconnected: " << e.what() << std::endl;
// Remove client from the map
std::lock_guard<std::mutex> lock(clients_mutex);
for (auto it = clients.begin(); it != clients.end(); ++it) {
if (it->second.socket == socket) {
clients.erase(it);
break;
}
}
}
}
int main() {
try {
asio::io_service io_service;
tcp::acceptor acceptor(io_service, tcp::endpoint(tcp::v4(), 12345));
std::cout << "Server started on port 12345\n";
while (true) {
std::shared_ptr<tcp::socket> socket = std::make_shared<tcp::socket>(io_service);
acceptor.accept(*socket);
std::cout << "New client connected.\n";
std::thread(handle_client, socket).detach();
}
}
catch (std::exception& e) {
std::cerr << "Server exception: " << e.what() << "\n";
}
return 0;
}
Explanation:
- Client Registration: Clients send a
REGISTER command with their username and public key upon connecting.
- Public Key Retrieval: Clients can request another user's public key using the
GETKEY command.
- Message Forwarding: Encrypted messages are sent using the
MESSAGE command, which includes the recipient's username and the encrypted message.
Implementing the Client
The client will:
- Generate RSA Key Pair: Use OpenSSL to generate RSA keys.
- Connect to Server: Register with the server by sending the public key.
- Send Messages: Request the recipient's public key, encrypt the message, and send it.
- Receive Messages: Decrypt incoming messages using the private key.
Client Steps:
- Generate RSA Keys: On startup, generate or load existing RSA keys.
- Connect and Register: Connect to the server and send a
REGISTER command with the username and public key.
- User Interface: Simple console-based interface to send messages to other users.
- Handle Incoming Messages: Listen for incoming messages and decrypt them.
Sample Client Code
Below is a simplified version of the client implementation.
// client.cpp
#include <iostream>
#include <string>
#include <asio.hpp>
#include <openssl/rsa.h>
#include <openssl/pem.h>
#include <openssl/err.h>
#include <sstream>
#include <vector>
using asio::ip::tcp;
// Function to generate RSA key pair
bool generate_keys(RSA*& rsa, std::string& public_key_pem, std::string& private_key_pem) {
rsa = RSA_generate_key(2048, RSA_F4, NULL, NULL);
if (!rsa) return false;
BIO* pub = BIO_new(BIO_s_mem());
PEM_write_bio_RSA_PUBKEY(pub, rsa);
size_t pub_len = BIO_pending(pub);
std::vector<char> pub_buffer(pub_len + 1);
BIO_read(pub, pub_buffer.data(), pub_len);
public_key_pem = std::string(pub_buffer.data(), pub_len);
BIO_free(pub);
BIO* priv = BIO_new(BIO_s_mem());
PEM_write_bio_RSAPrivateKey(priv, rsa, NULL, NULL, 0, NULL, NULL);
size_t priv_len = BIO_pending(priv);
std::vector<char> priv_buffer(priv_len + 1);
BIO_read(priv, priv_buffer.data(), priv_len);
private_key_pem = std::string(priv_buffer.data(), priv_len);
BIO_free(priv);
return true;
}
// Function to encrypt a message using a public key
std::string encrypt_message(const std::string& pub_key_pem, const std::string& message) {
BIO* pub = BIO_new_mem_buf(pub_key_pem.data(), pub_key_pem.length());
RSA* rsa_pub = PEM_read_RSA_PUBKEY(pub, NULL, NULL, NULL);
BIO_free(pub);
if (!rsa_pub) return "";
std::vector<unsigned char> encrypted(RSA_size(rsa_pub));
int len = RSA_public_encrypt(message.size(), (unsigned char*)message.c_str(),
encrypted.data(), rsa_pub, RSA_PKCS1_OAEP_PADDING);
RSA_free(rsa_pub);
if (len == -1) return "";
return std::string((char*)encrypted.data(), len);
}
// Function to decrypt a message using a private key
std::string decrypt_message(RSA* rsa_priv, const std::string& encrypted) {
std::vector<unsigned char> decrypted(RSA_size(rsa_priv));
int len = RSA_private_decrypt(encrypted.size(), (unsigned char*)encrypted.c_str(),
decrypted.data(), rsa_priv, RSA_PKCS1_OAEP_PADDING);
if (len == -1) return "";
return std::string((char*)decrypted.data(), len);
}
int main() {
// Initialize OpenSSL
OpenSSL_add_all_algorithms();
ERR_load_BIO_strings();
ERR_load_crypto_strings();
std::string username;
std::cout << "Enter your username: ";
std::cin >> username;
// Generate RSA keys
RSA* rsa = nullptr;
std::string public_key_pem, private_key_pem;
if (!generate_keys(rsa, public_key_pem, private_key_pem)) {
std::cerr << "Failed to generate RSA keys.\n";
return 1;
}
std::cout << "RSA keys generated.\n";
// Connect to server
try {
asio::io_service io_service;
tcp::socket socket(io_service);
tcp::resolver resolver(io_service);
asio::connect(socket, resolver.resolve({ "127.0.0.1", "12345" }));
std::cout << "Connected to server.\n";
// Register with server
std::string register_cmd = "REGISTER " + username + " " + public_key_pem + "\n";
asio::write(socket, asio::buffer(register_cmd));
// Function to handle incoming messages
std::thread receive_thread([&socket, rsa]() {
try {
asio::streambuf buf;
std::istream is(&buf);
while (true) {
asio::read_until(socket, buf, "\n");
std::string line;
std::getline(is, line);
if (line.empty()) continue;
if (line.substr(0, 7) == "MESSAGE") {
// Format: MESSAGE from username: encrypted_message
size_t pos1 = line.find(' ', 8);
size_t pos2 = line.find(": ", pos1);
std::string from_user = line.substr(pos1 + 1, pos2 - pos1 -1);
std::string encrypted_msg = line.substr(pos2 + 2);
std::string decrypted = decrypt_message(rsa, encrypted_msg);
if (!decrypted.empty()) {
std::cout << "\nMessage from " << from_user << ": " << decrypted << "\n> ";
}
else {
std::cout << "\nFailed to decrypt message from " << from_user << "\n> ";
}
}
else if (line.substr(0, 3) == "KEY") {
// Handle key response if needed
}
else if (line.substr(0, 5) == "ERROR") {
std::cout << "\nServer error: " << line.substr(6) << "\n> ";
}
}
}
catch (...) {
std::cerr << "Disconnected from server.\n";
}
});
// Main loop for sending messages
std::string input;
while (true) {
std::cout << "> ";
std::cin.ignore(); // To ignore any leftover characters
std::getline(std::cin, input);
if (input.empty()) continue;
// Simple command parsing: send to_username message
size_t space = input.find(' ');
if (space == std::string::npos) {
std::cout << "Usage: send <username> <message>\n";
continue;
}
std::string cmd = input.substr(0, space);
if (cmd != "send") {
std::cout << "Unknown command. Use: send <username> <message>\n";
continue;
}
size_t space2 = input.find(' ', space +1);
if (space2 == std::string::npos) {
std::cout << "Usage: send <username> <message>\n";
continue;
}
std::string to_user = input.substr(space +1, space2 - space -1);
std::string message = input.substr(space2 +1);
// Request recipient's public key
std::string getkey_cmd = "GETKEY " + to_user + "\n";
asio::write(socket, asio::buffer(getkey_cmd));
// Wait for server response
asio::streambuf buf;
std::istream is(&buf);
asio::read_until(socket, buf, "\n");
std::string response;
std::getline(is, response);
if (response.substr(0, 3) == "KEY") {
// Format: KEY username public_key
size_t pos1 = response.find(' ', 4);
std::string recv_user = response.substr(4, pos1 -4);
std::string recv_pub_key = response.substr(pos1 +1);
// Encrypt the message
std::string encrypted = encrypt_message(recv_pub_key, message);
if (encrypted.empty()) {
std::cout << "Encryption failed.\n";
continue;
}
// Send the encrypted message
std::string msg_cmd = "MESSAGE " + to_user + " " + encrypted + "\n";
asio::write(socket, asio::buffer(msg_cmd));
std::cout << "Message sent to " << to_user << ".\n";
}
else {
std::cout << "Failed to get public key for " << to_user << ": " << response << "\n";
}
}
receive_thread.join();
}
catch (std::exception& e) {
std::cerr << "Client exception: " << e.what() << "\n";
}
// Cleanup OpenSSL
RSA_free(rsa);
ERR_free_strings();
EVP_cleanup();
return 0;
}
Explanation:
- RSA Key Generation: Generates a 2048-bit RSA key pair on startup using OpenSSL.
- Registration: Sends the
REGISTER command with the username and public key to the server.
- Sending Messages:
- User inputs a command in the format:
send <username> <message>.
- The client requests the recipient's public key using
GETKEY.
- Upon receiving the public key, the message is encrypted using RSA and sent to the server with the
MESSAGE command.
- Receiving Messages:
- A separate thread listens for incoming messages.
- When a
MESSAGE is received, it decrypts the message using the private key and displays it.
Note: This is a simplified example. In a production environment, consider additional security measures, robust error handling, and protocol enhancements.
Compiling and Running the Application
1. Server
-
Create a New Project: In Code::Blocks, create a new console application project named SecureChatServer.
-
Add server.cpp: Replace the default main.cpp with the provided server.cpp code.
-
Configure Build Settings:
- Ensure that Asio and OpenSSL include and library paths are set.
- Link against
Ws2_32.lib and OpenSSL libraries (libssl.lib, libcrypto.lib).
-
Build the Project: Compile the server.
-
Run the Server: Execute the server application. It will start listening on port 12345.
2. Client
-
Create a New Project: In Code::Blocks, create a new console application project named SecureChatClient.
-
Add client.cpp: Replace the default main.cpp with the provided client.cpp code.
-
Configure Build Settings:
- Ensure that Asio and OpenSSL include and library paths are set.
- Link against
Ws2_32.lib and OpenSSL libraries (libssl.lib, libcrypto.lib).
-
Build the Project: Compile the client.
-
Run the Client: Execute the client application.
- Enter a username when prompted.
- Use the
send <username> <message> command to send messages to other users.
3. Testing the Application
-
Start the Server: Run the server application first.
-
Start Multiple Clients: Open multiple instances of the client application.
- Register with unique usernames.
-
Send Messages: Use the send command in one client to send messages to another.
- Example:
send Alice Hello, Alice!
-
Receive Messages: The recipient client should display the decrypted message.
Example Workflow:
- Client 1:
- Client 2:
- Alice sends a message to Bob:
- Bob receives the decrypted message:
- Output:
Message from Alice: Hi Bob!
Complete Source Code
For convenience, below are the complete source codes for both the server and client applications.
server.cpp
// server.cpp
#include <iostream>
#include <string>
#include <unordered_map>
#include <asio.hpp>
#include <mutex>
#include <thread>
using asio::ip::tcp;
// Structure to hold client information
struct ClientInfo {
std::string username;
std::string public_key;
std::shared_ptr<tcp::socket> socket;
};
// Global storage for clients
std::unordered_map<std::string, ClientInfo> clients;
std::mutex clients_mutex;
void handle_client(std::shared_ptr<tcp::socket> socket) {
try {
asio::streambuf buf;
std::istream is(&buf);
while (true) {
// Read until newline
asio::read_until(*socket, buf, "\n");
std::string line;
std::getline(is, line);
if (line.empty()) continue;
// Simple protocol parsing
// Commands: REGISTER, GETKEY, MESSAGE
if (line.substr(0, 8) == "REGISTER") {
// Format: REGISTER username public_key
size_t pos1 = line.find(' ', 9);
if (pos1 == std::string::npos) continue;
std::string username = line.substr(9, pos1 - 9);
std::string public_key = line.substr(pos1 + 1);
std::lock_guard<std::mutex> lock(clients_mutex);
clients[username] = ClientInfo{ username, public_key, socket };
std::cout << "Registered user: " << username << std::endl;
}
else if (line.substr(0, 6) == "GETKEY") {
// Format: GETKEY username
std::string target = line.substr(7);
std::lock_guard<std::mutex> lock(clients_mutex);
if (clients.find(target) != clients.end()) {
std::string response = "KEY " + target + " " + clients[target].public_key + "\n";
asio::write(*socket, asio::buffer(response));
}
else {
std::string response = "ERROR User not found\n";
asio::write(*socket, asio::buffer(response));
}
}
else if (line.substr(0, 7) == "MESSAGE") {
// Format: MESSAGE to_username encrypted_message
size_t pos1 = line.find(' ', 8);
if (pos1 == std::string::npos) continue;
std::string to_user = line.substr(8, pos1 - 8);
std::string encrypted_msg = line.substr(pos1 + 1);
std::lock_guard<std::mutex> lock(clients_mutex);
if (clients.find(to_user) != clients.end()) {
// Find sender's username
std::string from_user = "Unknown";
for (const auto& pair : clients) {
if (pair.second.socket == socket) {
from_user = pair.first;
break;
}
}
std::string forward = "MESSAGE from " + from_user + ": " + encrypted_msg + "\n";
asio::write(*clients[to_user].socket, asio::buffer(forward));
}
else {
std::string response = "ERROR Recipient not found\n";
asio::write(*socket, asio::buffer(response));
}
}
}
}
catch (std::exception& e) {
std::cerr << "Client disconnected: " << e.what() << std::endl;
// Remove client from the map
std::lock_guard<std::mutex> lock(clients_mutex);
for (auto it = clients.begin(); it != clients.end(); ++it) {
if (it->second.socket == socket) {
std::cout << "User " << it->first << " disconnected.\n";
clients.erase(it);
break;
}
}
}
}
int main() {
try {
asio::io_service io_service;
tcp::acceptor acceptor(io_service, tcp::endpoint(tcp::v4(), 12345));
std::cout << "Server started on port 12345\n";
while (true) {
std::shared_ptr<tcp::socket> socket = std::make_shared<tcp::socket>(io_service);
acceptor.accept(*socket);
std::cout << "New client connected.\n";
std::thread(handle_client, socket).detach();
}
}
catch (std::exception& e) {
std::cerr << "Server exception: " << e.what() << "\n";
}
return 0;
}
client.cpp
// client.cpp
#include <iostream>
#include <string>
#include <asio.hpp>
#include <openssl/rsa.h>
#include <openssl/pem.h>
#include <openssl/err.h>
#include <sstream>
#include <vector>
#include <thread>
using asio::ip::tcp;
// Function to generate RSA key pair
bool generate_keys(RSA*& rsa, std::string& public_key_pem, std::string& private_key_pem) {
rsa = RSA_generate_key(2048, RSA_F4, NULL, NULL);
if (!rsa) return false;
BIO* pub = BIO_new(BIO_s_mem());
PEM_write_bio_RSA_PUBKEY(pub, rsa);
size_t pub_len = BIO_pending(pub);
std::vector<char> pub_buffer(pub_len + 1);
BIO_read(pub, pub_buffer.data(), pub_len);
public_key_pem = std::string(pub_buffer.data(), pub_len);
BIO_free(pub);
BIO* priv = BIO_new(BIO_s_mem());
PEM_write_bio_RSAPrivateKey(priv, rsa, NULL, NULL, 0, NULL, NULL);
size_t priv_len = BIO_pending(priv);
std::vector<char> priv_buffer(priv_len + 1);
BIO_read(priv, priv_buffer.data(), priv_len);
private_key_pem = std::string(priv_buffer.data(), priv_len);
BIO_free(priv);
return true;
}
// Function to encrypt a message using a public key
std::string encrypt_message(const std::string& pub_key_pem, const std::string& message) {
BIO* pub = BIO_new_mem_buf(pub_key_pem.data(), pub_key_pem.length());
RSA* rsa_pub = PEM_read_RSA_PUBKEY(pub, NULL, NULL, NULL);
BIO_free(pub);
if (!rsa_pub) return "";
std::vector<unsigned char> encrypted(RSA_size(rsa_pub));
int len = RSA_public_encrypt(message.size(), (unsigned char*)message.c_str(),
encrypted.data(), rsa_pub, RSA_PKCS1_OAEP_PADDING);
RSA_free(rsa_pub);
if (len == -1) return "";
return std::string((char*)encrypted.data(), len);
}
// Function to decrypt a message using a private key
std::string decrypt_message(RSA* rsa_priv, const std::string& encrypted) {
std::vector<unsigned char> decrypted(RSA_size(rsa_priv));
int len = RSA_private_decrypt(encrypted.size(), (unsigned char*)encrypted.c_str(),
decrypted.data(), rsa_priv, RSA_PKCS1_OAEP_PADDING);
if (len == -1) return "";
return std::string((char*)decrypted.data(), len);
}
int main() {
// Initialize OpenSSL
OpenSSL_add_all_algorithms();
ERR_load_BIO_strings();
ERR_load_crypto_strings();
std::string username;
std::cout << "Enter your username: ";
std::cin >> username;
// Generate RSA keys
RSA* rsa = nullptr;
std::string public_key_pem, private_key_pem;
if (!generate_keys(rsa, public_key_pem, private_key_pem)) {
std::cerr << "Failed to generate RSA keys.\n";
return 1;
}
std::cout << "RSA keys generated.\n";
// Connect to server
try {
asio::io_service io_service;
tcp::socket socket(io_service);
tcp::resolver resolver(io_service);
asio::connect(socket, resolver.resolve({ "127.0.0.1", "12345" }));
std::cout << "Connected to server.\n";
// Register with server
std::string register_cmd = "REGISTER " + username + " " + public_key_pem + "\n";
asio::write(socket, asio::buffer(register_cmd));
// Function to handle incoming messages
std::thread receive_thread([&socket, rsa]() {
try {
asio::streambuf buf;
std::istream is(&buf);
while (true) {
asio::read_until(socket, buf, "\n");
std::string line;
std::getline(is, line);
if (line.empty()) continue;
if (line.substr(0, 7) == "MESSAGE") {
// Format: MESSAGE from username: encrypted_message
size_t pos1 = line.find(' ', 8);
size_t pos2 = line.find(": ", pos1);
if (pos1 == std::string::npos || pos2 == std::string::npos) continue;
std::string from_user = line.substr(pos1 + 1, pos2 - pos1 -1);
std::string encrypted_msg = line.substr(pos2 + 2);
std::string decrypted = decrypt_message(rsa, encrypted_msg);
if (!decrypted.empty()) {
std::cout << "\nMessage from " << from_user << ": " << decrypted << "\n> ";
}
else {
std::cout << "\nFailed to decrypt message from " << from_user << "\n> ";
}
}
else if (line.substr(0, 3) == "KEY") {
// Handle key response if needed
}
else if (line.substr(0, 5) == "ERROR") {
std::cout << "\nServer error: " << line.substr(6) << "\n> ";
}
}
}
catch (...) {
std::cerr << "Disconnected from server.\n";
}
});
// Main loop for sending messages
std::string input;
while (true) {
std::cout << "> ";
std::cin.ignore(); // To ignore any leftover characters
std::getline(std::cin, input);
if (input.empty()) continue;
// Simple command parsing: send to_username message
size_t space = input.find(' ');
if (space == std::string::npos) {
std::cout << "Usage: send <username> <message>\n";
continue;
}
std::string cmd = input.substr(0, space);
if (cmd != "send") {
std::cout << "Unknown command. Use: send <username> <message>\n";
continue;
}
size_t space2 = input.find(' ', space +1);
if (space2 == std::string::npos) {
std::cout << "Usage: send <username> <message>\n";
continue;
}
std::string to_user = input.substr(space +1, space2 - space -1);
std::string message = input.substr(space2 +1);
// Request recipient's public key
std::string getkey_cmd = "GETKEY " + to_user + "\n";
asio::write(socket, asio::buffer(getkey_cmd));
// Wait for server response
asio::streambuf buf;
std::istream is(&buf);
asio::read_until(socket, buf, "\n");
std::string response;
std::getline(is, response);
if (response.substr(0, 3) == "KEY") {
// Format: KEY username public_key
size_t pos1 = response.find(' ', 4);
std::string recv_user = response.substr(4, pos1 -4);
std::string recv_pub_key = response.substr(pos1 +1);
// Encrypt the message
std::string encrypted = encrypt_message(recv_pub_key, message);
if (encrypted.empty()) {
std::cout << "Encryption failed.\n";
continue;
}
// Send the encrypted message
std::string msg_cmd = "MESSAGE " + to_user + " " + encrypted + "\n";
asio::write(socket, asio::buffer(msg_cmd));
std::cout << "Message sent to " << to_user << ".\n";
}
else {
std::cout << "Failed to get public key for " << to_user << ": " << response << "\n";
}
}
receive_thread.join();
}
catch (std::exception& e) {
std::cerr << "Client exception: " << e.what() << "\n";
}
// Cleanup OpenSSL
RSA_free(rsa);
ERR_free_strings();
EVP_cleanup();
return 0;
}
Important Considerations
-
Security:
- Private Key Protection: Ensure the private key remains secure on the client side. In this example, it's stored in memory. For persistence and enhanced security, consider encrypting the private key and storing it securely.
- Authentication: The current implementation does not authenticate users beyond usernames. Implement authentication mechanisms to prevent impersonation.
- Encryption Integrity: Ensure messages are properly encrypted and decrypted. Consider adding message signatures to verify integrity.
-
Protocol Enhancements:
- Define a more robust protocol for communication, possibly using JSON or another structured format.
- Handle different message types and error conditions gracefully.
-
Scalability:
- The server uses a simple thread-per-connection model, which may not scale well. Consider using asynchronous operations or thread pools for better scalability.
-
Error Handling:
- Implement comprehensive error handling to manage network issues, malformed messages, and other potential errors.
-
User Interface:
- Enhance the client interface for better usability, such as adding command history, user lists, and message formatting.
-
Persistence:
- Store users' public keys and other data persistently on the server to maintain state across server restarts.
By following this guide and considering the above points, you can develop a secure C++ chat application with RSA encryption using Asio and OpenSSL on Windows with Code::Blocks.