23 #include <ibrcommon/ssl/SHA256Stream.h>
24 #include <ibrcommon/Logger.h>
29 #include <openssl/sha.h>
30 #include <openssl/pem.h>
31 #include <openssl/err.h>
38 : type(KEY_UNSPEC), trustlevel(NONE)
61 return ibrcommon::File(
file.getPath() +
".txt");
66 std::ifstream stream(
file.getPath().c_str(), ios::in);
81 return getPrivateRSA();
83 return getPublicRSA();
91 EVP_PKEY* ret = EVP_PKEY_new();
92 FILE * pkey_file = fopen(
file.getPath().c_str(),
"r");
98 ret = PEM_read_PrivateKey(pkey_file, &ret, NULL, NULL);
104 ret = PEM_read_PUBKEY(pkey_file, &ret, NULL, NULL);
123 RSA* rsa = getPrivateRSA();
130 RSA* rsa = getPublicRSA();
142 RSA* SecurityKey::getPrivateRSA()
const
144 RSA *rsa = RSA_new();
146 FILE * rsa_pkey_file = fopen(
file.getPath().c_str(),
"r");
147 if (!rsa_pkey_file) {
148 IBRCOMMON_LOGGER_ex(critical) <<
"Failed to open " <<
file.getPath() << IBRCOMMON_LOGGER_ENDL;
149 throw ibrcommon::Exception(
"Failed to open " +
file.getPath());
151 if (!PEM_read_RSAPrivateKey(rsa_pkey_file, &rsa, NULL, NULL)) {
152 IBRCOMMON_LOGGER_ex(critical) <<
"Error loading RSA private key file: " <<
file.getPath() << IBRCOMMON_LOGGER_ENDL;
153 ERR_print_errors_fp(stderr);
154 throw ibrcommon::Exception(
"Error loading RSA private key file: " +
file.getPath());
156 fclose(rsa_pkey_file);
160 RSA* SecurityKey::getPublicRSA()
const
162 RSA *rsa = RSA_new();
164 FILE * rsa_pkey_file = fopen(
file.getPath().c_str(),
"r");
165 if (!rsa_pkey_file) {
166 IBRCOMMON_LOGGER_ex(critical) <<
"Failed to open " <<
file.getPath() << IBRCOMMON_LOGGER_ENDL;
167 throw ibrcommon::Exception(
"Failed to open " +
file.getPath());
169 if (!PEM_read_RSA_PUBKEY(rsa_pkey_file, &rsa, NULL, NULL)) {
170 IBRCOMMON_LOGGER_ex(critical) <<
"Error loading RSA public key file: " <<
file.getPath() << IBRCOMMON_LOGGER_ENDL;
171 ERR_print_errors_fp(stderr);
172 throw ibrcommon::Exception(
"Error loading RSA public key file: " +
file.getPath());
174 fclose(rsa_pkey_file);
181 ibrcommon::SHA256Stream sha;
184 ifstream stream(file.getPath().c_str());
187 if (!stream.good()) {
188 sha << stream.rdbuf() << std::flush;
192 std::stringstream fingerprint;
195 fingerprint << std::hex << std::setw(2) << std::setfill(
'0') << (int)sha.get();
198 return fingerprint.str();
203 unsigned char *p = NULL;
204 int length = i2d_RSA_PUBKEY(rsa, &p);
206 std::string ret =
"";
209 ret = std::string((
const char*)p, length);
215 throw(ibrcommon::Exception(
"Error while parsing rsa key"));
218 unsigned char hash[SHA256_DIGEST_LENGTH];
219 SHA256(p, length, hash);
221 std::stringstream stream;
222 for(
int i = 0; i < SHA256_DIGEST_LENGTH; i++)
224 stream << std::hex << std::setw(2) << std::setfill(
'0') << (int)hash[i];
virtual EVP_PKEY * getEVP() const
static void free(RSA *key)
virtual const std::string getData() const
virtual RSA * getRSA() const
bool operator==(const SecurityKey &key)
virtual const std::string getFingerprint() const
ibrcommon::File getMetaFilename() const