#include "PrivateKey.h"

#include <openssl/pem.h>
#include <stdexcept>

#include "Utils.h"

using namespace std;

PrivateKey::PrivateKey(const string& filename)
    : key(NULL) {
  if (FILE *fp = fopen(filename.c_str(), "rb")) {
    key = PEM_read_PrivateKey(fp, &key, NULL, NULL);
    fclose(fp);
  } else {
    throw std::runtime_error("Can't open file: " + filename);
  }
}

PrivateKey::PrivateKey(const vector<uint8_t>& keydata)
    : key(NULL) {
  BIO *bufio = BIO_new_mem_buf((void*) &keydata[0], keydata.size());
  key = PEM_read_bio_PrivateKey(bufio, &key, 0, NULL);
  BIO_free(bufio);
}

PrivateKey::~PrivateKey()  {
  EVP_PKEY_free(key);
}

EVP_PKEY* PrivateKey::GetKey() {
  return key;
}
