28 #include "ndn-cxx/security/impl/openssl-helper.hpp"
31 #define ENSURE_PUBLIC_KEY_LOADED(key) \
33 if ((key) == nullptr) \
34 NDN_THROW(Error("Public key has not been loaded yet")); \
37 #define ENSURE_PUBLIC_KEY_NOT_LOADED(key) \
39 if ((key) != nullptr) \
40 NDN_THROW(Error("Public key has already been loaded")); \
47 class PublicKey::Impl : noncopyable
65 : m_impl(make_unique<Impl>())
77 switch (detail::getEvpPkeyType(m_impl->key)) {
92 auto ptr = buf.data();
93 if (d2i_PUBKEY(&m_impl->key, &ptr,
static_cast<long>(buf.size())) ==
nullptr)
138 int keyType = detail::getEvpPkeyType(m_impl->key);
143 return rsaEncrypt(plainText);
150 PublicKey::getEvpPkey()
const
156 PublicKey::toPkcs8()
const
160 uint8_t* pkcs8 =
nullptr;
161 int len = i2d_PUBKEY(m_impl->key, &pkcs8);
163 NDN_THROW(Error(
"Cannot convert key to PKCS #8 format"));
165 auto buffer = make_shared<Buffer>(pkcs8, len);
172 PublicKey::rsaEncrypt(span<const uint8_t> plainText)
const
174 detail::EvpPkeyCtx ctx(m_impl->key);
176 if (EVP_PKEY_encrypt_init(ctx) <= 0)
177 NDN_THROW(Error(
"Failed to initialize encryption context"));
179 if (EVP_PKEY_CTX_set_rsa_padding(ctx, RSA_PKCS1_OAEP_PADDING) <= 0)
180 NDN_THROW(Error(
"Failed to set padding"));
184 if (EVP_PKEY_encrypt(ctx,
nullptr, &outlen, plainText.data(), plainText.size()) <= 0)
185 NDN_THROW(Error(
"Failed to estimate output length"));
187 auto out = make_shared<Buffer>(outlen);
188 if (EVP_PKEY_encrypt(ctx, out->data(), &outlen, plainText.data(), plainText.size()) <= 0)
189 NDN_THROW(Error(
"Failed to encrypt plaintext"));
implements an output stream that constructs ndn::Buffer
shared_ptr< Buffer > buf()
Flush written data to the stream and return shared pointer to the underlying buffer.
std::string to_string(const errinfo_stacktrace &x)
shared_ptr< const Buffer > ConstBufferPtr
KeyType
The type of a cryptographic key.
@ EC
Elliptic Curve key (e.g. for ECDSA), supports sign/verify operations.
@ RSA
RSA key, supports sign/verify and encrypt/decrypt operations.
@ NONE
Unknown or unsupported key type.
#define ENSURE_PUBLIC_KEY_NOT_LOADED(key)
#define ENSURE_PUBLIC_KEY_LOADED(key)