summaryrefslogtreecommitdiff
path: root/src/pubkey.h
blob: 7fe37ec50070accbbd52ff978ac0b9ff10d34769 (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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
#pragma once

#include "storage.h"

#include <openssl/evp.h>

using std::nullopt;
using std::optional;
using std::shared_ptr;

namespace erebos {

class PublicKey
{
	PublicKey(EVP_PKEY * key):
		key(key, EVP_PKEY_free) {}
public:
	static optional<PublicKey> load(const Ref &);
	const shared_ptr<EVP_PKEY> key;
};

class SecretKey
{
	SecretKey(EVP_PKEY * key, const Stored<PublicKey> & pub):
		key(key, EVP_PKEY_free), pub(pub) {}

private:
	const shared_ptr<EVP_PKEY> key;
	Stored<PublicKey> pub;
};

class Signature
{
public:
	static optional<Signature> load(const Ref &);

	bool verify(const Ref &) const;

	Stored<PublicKey> key;
	vector<uint8_t> sig;
};

template<typename T>
class Signed
{
public:
	static optional<Signed<T>> load(const Ref &);

	bool isSignedBy(const Stored<PublicKey> &) const;

	const Stored<T> data;
	const vector<Stored<Signature>> sigs;
};

template<typename T>
optional<Signed<T>> Signed<T>::load(const Ref & ref)
{
	auto rec = ref->asRecord();
	if (!rec)
		return nullopt;

	auto data = rec->item("SDATA").as<T>();
	if (!data)
		return nullopt;

	vector<Stored<Signature>> sigs;
	for (auto item : rec->items("sig"))
		if (auto sig = item.as<Signature>())
			if (sig.value()->verify(data.value().ref))
				sigs.push_back(sig.value());

	return Signed {
		.data = data.value(),
		.sigs = sigs,
	};
}

template<typename T>
bool Signed<T>::isSignedBy(const Stored<PublicKey> & key) const
{
	for (const auto & sig : sigs)
		if (sig->key == key)
			return true;
	return false;
}

}