1#include <vanetza/common/serialization.hpp>
2#include <vanetza/security/v3/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 <cryptopp/base64.h>
18ecdsa256::KeyPair load_private_key_from_file(
const std::string& key_path)
20 CryptoPP::AutoSeededRandomPool rng;
22 static std::string HEADER =
"-----BEGIN PRIVATE KEY-----";
23 static std::string FOOTER =
"-----END PRIVATE KEY-----";
24 std::ifstream t(key_path);
25 std::string RSA_PRIV_KEY((std::istreambuf_iterator<char>(t)),
26 std::istreambuf_iterator<char>());
30 pos1 = RSA_PRIV_KEY.find(HEADER);
31 if(pos1 == std::string::npos)
32 throw "PEM header not found";
34 pos2 = RSA_PRIV_KEY.find(FOOTER, pos1+1);
35 if(pos2 == std::string::npos)
36 throw "PEM footer not found";
39 pos1 = pos1 + HEADER.length();
41 std::string keystr = RSA_PRIV_KEY.substr(pos1, pos2);
44 CryptoPP::ByteQueue queue;
45 CryptoPP::Base64Decoder decoder;
47 decoder.Attach(
new CryptoPP::Redirector(queue));
48 decoder.Put(
reinterpret_cast<const uint8_t*
>(keystr.data()), keystr.length());
51 CryptoPP::ECDSA<CryptoPP::ECP, CryptoPP::SHA256>::PrivateKey private_key;
52 private_key.Load(queue);
54 if (!private_key.Validate(rng, 3)) {
55 throw std::runtime_error(
"Private key validation failed");
58 ecdsa256::KeyPair key_pair;
60 auto& private_exponent = private_key.GetPrivateExponent();
61 private_exponent.Encode(key_pair.private_key.key.data(), key_pair.private_key.key.size());
63 CryptoPP::ECDSA<CryptoPP::ECP, CryptoPP::SHA256>::PublicKey public_key;
64 private_key.MakePublicKey(public_key);
66 auto& public_element = public_key.GetPublicElement();
67 public_element.x.Encode(key_pair.public_key.x.data(), key_pair.public_key.x.size());
68 public_element.y.Encode(key_pair.public_key.y.data(), key_pair.public_key.y.size());
73v2::PublicKey load_public_key_from_file(
const std::string& key_path)
75 v2::PublicKey public_key;
77 std::ifstream key_src;
78 key_src.open(key_path, std::ios::in | std::ios::binary);
79 vanetza::InputArchive key_archive(key_src);
80 v2::deserialize(key_archive, public_key);
85void save_public_key_to_file(
const std::string& key_path,
const v2::PublicKey& public_key)
88 dest.open(key_path.c_str(), std::ios::out | std::ios::binary);
90 OutputArchive archive(dest);
91 v2::serialize(archive, public_key);
94Certificate load_certificate_from_file(
const std::string& certificate_path)
98 std::ifstream certificate_src;
99 certificate_src.open(certificate_path, std::ios::in | std::ios::binary);
100 vanetza::ByteBuffer buffer(std::istreambuf_iterator<char>(certificate_src), {});
101 certificate.decode(buffer);
106void save_certificate_to_file(
const std::string& certificate_path,
const Certificate& certificate)
109 dest.open(certificate_path.c_str(), std::ios::out | std::ios::binary);
111 OutputArchive archive(dest);
112 serialize(archive, certificate);