summaryrefslogtreecommitdiff
path: root/distfoldd/localkey.cc
blob: 031c0b8b5a50dc8d1959db5136889d792df7eaaf (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
#include <QtCore/QDir>
#include <QtCore/QDebug>
#include <QtCrypto>

#include "localkey.h"

LocalKey::LocalKey()
{
}

QString LocalKey::localKeyDir()
{
	return QDir::home().absoluteFilePath(".config/distfold");
}

bool LocalKey::setupLocalKey()
{
	QDir local_key_dir(localKeyDir());
	if (local_key_dir.exists("server.crt") && local_key_dir.exists("server.key")) {
		return true;
	}
	if (!local_key_dir.exists()) {
		if (!local_key_dir.mkpath(local_key_dir.absolutePath())) {
			qWarning() << "Could not create local key directory";
			return false;
		}
	}

	QCA::KeyGenerator keygen;
	keygen.setBlockingEnabled(true);

	qDebug() << "Generating private key...";
	QCA::PrivateKey private_key = keygen.createRSA(2048);
	if (!private_key.toPEMFile(local_key_dir.absoluteFilePath("server.key"))) {
		qWarning() << "Failed to save private key";
		return false;
	}

	qDebug() << "Generating server certificate...";
	QCA::CertificateInfo cert_info;
	cert_info.insert(QCA::CommonName, "Distfold Private Generic Cert");
	QCA::CertificateOptions cert_options;
	cert_options.setAsCA(1);
	cert_options.setInfo(cert_info);
	cert_options.setValidityPeriod(QDateTime::currentDateTime(),
	                               QDateTime::currentDateTime().addYears(2));
	QCA::Certificate cert(cert_options, private_key);
	if (!cert.toPEMFile(local_key_dir.absoluteFilePath("server.crt"))) {
		qWarning() << "Failed to save server certificate";
		return false;
	}

	return true;
}