void RSAKey::cache() { unsigned char buffer[8192]; unsigned char* buf = buffer; int len = i2d_RSAPublicKey(d_rsa.get(), &buf); EXCEPTION_ASSERT_WITH_LOG(len >= 0, OpenSSLException, "Invalid RSA context: cannot retrieve public key"); d_public_key.clear(); d_public_key.insert(d_public_key.end(), buffer, buffer + len); if (hasPrivateCompound()) { buf = buffer; len = i2d_RSAPrivateKey(d_rsa.get(), &buf); EXCEPTION_ASSERT_WITH_LOG(len >= 0, OpenSSLException, "Invalid RSA context: cannot retrieve private key"); d_private_key.clear(); d_private_key.insert(d_private_key.end(), buffer, buffer + len); } else { d_private_key.clear(); } }
RSAKey RSAKey::discardPrivateCompound() const { if (hasPrivateCompound()) { return createFromPEMPublicKey(getPEM(true)); } else { return *this; } }
EVPPKey EVPPKey::discardPrivateCompound() const { if (hasPrivateCompound()) { if (type() == EVP_PKEY_RSA) { return createFromRSAKey(rsaKey().discardPrivateCompound()); } throw Exception::bad_function_call("Unsupported key type"); } else { return *this; } }
std::vector<unsigned char> RSAKey::getPEM(bool discard_private_compound, PEMPassphraseCallback callback, void* userdata) const { std::shared_ptr<BIO> pbio(BIO_new(BIO_s_mem()), BIO_free); if (hasPrivateCompound() && (!discard_private_compound)) { EXCEPTION_ASSERT_WITH_LOG(PEM_write_bio_RSAPrivateKey(pbio.get(), d_rsa.get(), NULL, NULL, 0, callback, userdata), OpenSSLException, "Cannot write PEM data"); } else { EXCEPTION_ASSERT_WITH_LOG(PEM_write_bio_RSA_PUBKEY(pbio.get(), d_rsa.get()), OpenSSLException, "Cannot write PEM data"); } int len = BIO_pending(pbio.get()); std::vector<unsigned char> buffer(len); BIO_read(pbio.get(), buffer.data(), len); buffer.resize(len); return buffer; }
void RSAKey::writeToPEMKeyFile(const std::string& filename, PEMPassphraseCallback callback, void* userdata) const { FILE* fp = fopen(filename.c_str(), "w+"); if (fp == NULL) { THROW_EXCEPTION_WITH_LOG(Exception::exception, "Cannot open the file."); } int result = 0; if (hasPrivateCompound()) { result = PEM_write_RSAPrivateKey(fp, d_rsa.get(), NULL, NULL, 0, callback, userdata); } else { result = PEM_write_RSAPublicKey(fp, d_rsa.get()); } fclose(fp); EXCEPTION_ASSERT_WITH_LOG(result != 0, OpenSSLException, "Cannot write PEM file"); }