add encryption

This commit is contained in:
2024-09-11 15:44:02 +03:00
parent 0d94699206
commit b24b5a1346
5 changed files with 25 additions and 6 deletions

View File

@@ -71,6 +71,15 @@ int PIClientServer::Client::write(const void * d, const size_t s) {
}
void PIClientServer::Client::enableSymmetricEncryption(const PIByteArray & key) {
if (key.isNotEmpty()) {
stream.setCryptEnabled(true);
stream.setCryptKey(key);
} else
stream.setCryptEnabled(false);
}
void PIClientServer::Client::createForServer(PIEthernet * tcp_) {
tcp = tcp_;
tcp->setParameter(PIEthernet::KeepConnection, false);

View File

@@ -91,6 +91,11 @@ void PIClientServer::Server::setMaxClients(int new_max_clients) {
}
void PIClientServer::Server::enableSymmetricEncryption(const PIByteArray & key) {
crypt_key = key;
}
void PIClientServer::Server::stopServer() {
if (!tcp_server) return;
tcp_server->stopAndWait();
@@ -98,8 +103,9 @@ void PIClientServer::Server::stopServer() {
void PIClientServer::Server::newClient(Client * c) {
c->readed_func = [this, c](PIByteArray ba) { readed(c, ba); };
clients << c;
c->enableSymmetricEncryption(crypt_key);
c->readed_func = [this, c](PIByteArray ba) { readed(c, ba); };
c->tcp->startThreadedRead();
c->connected();
piCout << "New client";

View File

@@ -54,6 +54,8 @@ public:
int write(const void * d, const size_t s);
int write(const PIByteArray & ba) { return write(ba.data(), ba.size()); }
void enableSymmetricEncryption(const PIByteArray & key);
protected:
virtual void readed(PIByteArray data) {}
virtual void connected() {}

View File

@@ -49,7 +49,7 @@ public:
void setClientFactory(std::function<Client *()> f) { client_factory = f; }
void write(Client * c, const PIByteArray & data);
void enableSymmetricEncryption(const PIByteArray & key);
protected:
virtual void readed(Client * c, PIByteArray data) {}
@@ -61,6 +61,7 @@ private:
std::function<Client *()> client_factory;
PIEthernet * tcp_server = nullptr;
PIThread * clean_thread = nullptr;
PIByteArray crypt_key;
PIVector<Client *> clients;
PIMutex clients_mutex;

View File

@@ -28,7 +28,7 @@ protected:
send_thread.start(
[this] {
// write((PIString::fromNumber(++counter)).toUTF8());
PIByteArray ba(64_MiB);
PIByteArray ba(64_KiB);
write(ba);
},
2_Hz);
@@ -41,20 +41,21 @@ protected:
int main(int argc, char * argv[]) {
kbd.enableExitCapture();
piCout << argc;
PIClientServer::Server * s = nullptr;
PIClientServer::Client * c = nullptr;
if (argc > 1) {
// server
piCout << "Server";
s = new PIClientServer::Server();
s->setClientFactory([] { return new MyClient(); });
s->enableSymmetricEncryption("1122334455667788"_hex);
s->listenAll(12345);
} else {
// client
piCout << "Client";
c = new MyClient();
c->createNew();
c->enableSymmetricEncryption("1122334455667788"_hex);
c->connect(PINetworkAddress::resolve("127.0.0.1", 12345));
}