28 #include "../detail/openssl-helper.hpp" 29 #include "../../encoding/buffer-stream.hpp" 31 #define ENSURE_PUBLIC_KEY_LOADED(key) \ 33 if ((key) == nullptr) \ 34 BOOST_THROW_EXCEPTION(Error("Public key has not been loaded yet")); \ 37 #define ENSURE_PUBLIC_KEY_NOT_LOADED(key) \ 39 if ((key) != nullptr) \ 40 BOOST_THROW_EXCEPTION(Error("Public key has already been loaded")); \ 92 if (d2i_PUBKEY(&m_impl->key, &buf, static_cast<long>(size)) ==
nullptr)
93 BOOST_THROW_EXCEPTION(
Error(
"Failed to load public key"));
140 BOOST_THROW_EXCEPTION(
Error(
"Failed to determine key type"));
142 return rsaEncrypt(plainText, plainLen);
144 BOOST_THROW_EXCEPTION(
Error(
"Encryption is not supported for key type " +
to_string(keyType)));
149 PublicKey::getEvpPkey()
const 155 PublicKey::toPkcs8()
const 159 uint8_t* pkcs8 =
nullptr;
160 int len = i2d_PUBKEY(m_impl->key, &pkcs8);
162 BOOST_THROW_EXCEPTION(Error(
"Cannot convert key to PKCS #8 format"));
164 auto buffer = make_shared<Buffer>(pkcs8, len);
171 PublicKey::rsaEncrypt(
const uint8_t* plainText,
size_t plainLen)
const 173 detail::EvpPkeyCtx ctx(m_impl->key);
175 if (EVP_PKEY_encrypt_init(ctx) <= 0)
176 BOOST_THROW_EXCEPTION(Error(
"Failed to initialize encryption context"));
178 if (EVP_PKEY_CTX_set_rsa_padding(ctx, RSA_PKCS1_OAEP_PADDING) <= 0)
179 BOOST_THROW_EXCEPTION(Error(
"Failed to set padding"));
183 if (EVP_PKEY_encrypt(ctx,
nullptr, &outlen, plainText, plainLen) <= 0)
184 BOOST_THROW_EXCEPTION(Error(
"Failed to estimate output length"));
186 auto out = make_shared<Buffer>(outlen);
187 if (EVP_PKEY_encrypt(ctx, out->data(), &outlen, plainText, plainLen) <= 0)
188 BOOST_THROW_EXCEPTION(Error(
"Failed to encrypt plaintext"));
Copyright (c) 2011-2015 Regents of the University of California.
int getEvpPkeyType(EVP_PKEY *key)
RSA key, supports sign/verify and encrypt/decrypt operations.
KeyType
The type of a cryptographic key.
Elliptic Curve key (e.g. for ECDSA), supports sign/verify operations.
shared_ptr< Buffer > buf()
Flush written data to the stream and return shared pointer to the underlying buffer.
#define ENSURE_PUBLIC_KEY_NOT_LOADED(key)
implements an output stream that constructs ndn::Buffer
std::string to_string(const V &v)
unique_ptr< T > make_unique(Args &&... args)
#define ENSURE_PUBLIC_KEY_LOADED(key)
shared_ptr< const Buffer > ConstBufferPtr