Vanetza
Loading...
Searching...
No Matches
persistence.cpp
1#include <vanetza/common/serialization.hpp>
2#include <vanetza/security/v2/persistence.hpp>
3#include <boost/variant/get.hpp>
4#include <cryptopp/eccrypto.h>
5#include <cryptopp/files.h>
6#include <cryptopp/oids.h>
7#include <cryptopp/osrng.h>
8#include <fstream>
9
10namespace vanetza
11{
12namespace security
13{
14namespace v2
15{
16
17ecdsa256::KeyPair load_private_key_from_file(const std::string& key_path)
18{
19 CryptoPP::AutoSeededRandomPool rng;
20
21 CryptoPP::ECDSA<CryptoPP::ECP, CryptoPP::SHA256>::PrivateKey private_key;
22 CryptoPP::FileSource key_file(key_path.c_str(), true);
23 private_key.Load(key_file);
24
25 if (!private_key.Validate(rng, 3)) {
26 throw std::runtime_error("Private key validation failed");
27 }
28
29 ecdsa256::KeyPair key_pair;
30
31 auto& private_exponent = private_key.GetPrivateExponent();
32 private_exponent.Encode(key_pair.private_key.key.data(), key_pair.private_key.key.size());
33
34 CryptoPP::ECDSA<CryptoPP::ECP, CryptoPP::SHA256>::PublicKey public_key;
35 private_key.MakePublicKey(public_key);
36
37 auto& public_element = public_key.GetPublicElement();
38 public_element.x.Encode(key_pair.public_key.x.data(), key_pair.public_key.x.size());
39 public_element.y.Encode(key_pair.public_key.y.data(), key_pair.public_key.y.size());
40
41 return key_pair;
42}
43
44PublicKey load_public_key_from_file(const std::string& key_path)
45{
46 PublicKey public_key;
47
48 std::ifstream key_src;
49 key_src.open(key_path, std::ios::in | std::ios::binary);
50 vanetza::InputArchive key_archive(key_src);
51 deserialize(key_archive, public_key);
52
53 return public_key;
54}
55
56void save_public_key_to_file(const std::string& key_path, const PublicKey& public_key)
57{
58 std::ofstream dest;
59 dest.open(key_path.c_str(), std::ios::out | std::ios::binary);
60
61 OutputArchive archive(dest);
62 serialize(archive, public_key);
63}
64
65Certificate load_certificate_from_file(const std::string& certificate_path)
66{
67 Certificate certificate;
68
69 std::ifstream certificate_src;
70 certificate_src.open(certificate_path, std::ios::in | std::ios::binary);
71 vanetza::InputArchive certificate_archive(certificate_src);
72 deserialize(certificate_archive, certificate);
73
74 return certificate;
75}
76
77void save_certificate_to_file(const std::string& certificate_path, const Certificate& certificate)
78{
79 std::ofstream dest;
80 dest.open(certificate_path.c_str(), std::ios::out | std::ios::binary);
81
82 OutputArchive archive(dest);
83 serialize(archive, certificate);
84}
85
86} // namespace v2
87} // namespace security
88} // namespace vanetza
described in TS 103 097 v1.2.1 (2015-06), section 6.1