// SPDX-FileCopyrightText: 2026 Matvey Shcherbinin // SPDX-License-Identifier: GPL-3.0-only OR LicenseRef-KDE-Accepted-GPL // KOutNet - The keys that seal group traffic #include "GroupKeyStore.h" #include "core/security/SecretStore.h" #include #include "koutnet_network_debug.h" namespace koutnet { namespace { QString randomHex(int bytes) { QByteArray buf(bytes, 0); QRandomGenerator::system()->generate(buf.begin(), buf.end()); return QString::fromLatin1(buf.toHex()); } } // namespace GroupKeyStore::GroupKeyStore(QObject *parent) : QObject(parent) { } void GroupKeyStore::setPassphrase(const QString &passphrase) { m_passphrase = passphrase; } QString GroupKeyStore::storeKey(const QString &gid) { return QStringLiteral("group_key/") + gid; } QString GroupKeyStore::keyFor(const QString &gid) const { const auto it = m_groupKeys.constFind(gid); if (it != m_groupKeys.constEnd()) return it.value(); QString key; if (SecretStore::read(storeKey(gid), &key) && !key.isEmpty()) { m_groupKeys.insert(gid, key); return key; } return QString(); } QString GroupKeyStore::cipherKeyFor(const QString &gid) const { // A conversation with a gid of its own seals under its key; anything else // (including the shared broadcasts) under the shared passphrase. if (!gid.isEmpty()) { const QString key = keyFor(gid); if (!key.isEmpty()) return key; } return m_passphrase; } void GroupKeyStore::setKey(const QString &gid, const QString &key) { if (key.isEmpty()) { m_groupKeys.remove(gid); SecretStore::remove(storeKey(gid)); return; } m_groupKeys.insert(gid, key); SecretStore::write(storeKey(gid), key); } void GroupKeyStore::removeKey(const QString &gid) { setKey(gid, QString()); } QString GroupKeyStore::ensureKey(const QString &gid) { if (const QString existing = keyFor(gid); !existing.isEmpty()) return existing; const QString key = randomHex(32); m_groupKeys.insert(gid, key); if (!SecretStore::write(storeKey(gid), key)) qCWarning(KOUTNET_LOG_NETWORK) << "group key for" << gid << "not persisted - secret store unavailable, this session only"; return key; } } // namespace koutnet