28 #include "ndn-cxx/security/impl/openssl-helper.hpp"
31 #include <openssl/rsa.h>
32 #include <openssl/x509.h>
34 #define ENSURE_PUBLIC_KEY_LOADED(key) \
36 if ((key) == nullptr) \
37 NDN_THROW(Error("Public key has not been loaded yet")); \
40 #define ENSURE_PUBLIC_KEY_NOT_LOADED(key) \
42 if ((key) != nullptr) \
43 NDN_THROW(Error("Public key has already been loaded")); \
50 class PublicKey::Impl : noncopyable
68 : m_impl(make_unique<Impl>())
80 switch (detail::getEvpPkeyType(m_impl->key)) {
96 return static_cast<size_t>(EVP_PKEY_bits(m_impl->key));
107 auto ptr = buf.data();
108 if (d2i_PUBKEY(&m_impl->key, &ptr,
static_cast<long>(buf.size())) ==
nullptr)
153 int keyType = detail::getEvpPkeyType(m_impl->key);
158 return rsaEncrypt(plainText);
165 PublicKey::getEvpPkey()
const
171 PublicKey::toPkcs8()
const
175 uint8_t* pkcs8 =
nullptr;
176 int len = i2d_PUBKEY(m_impl->key, &pkcs8);
178 NDN_THROW(Error(
"Cannot convert key to PKCS #8 format"));
180 auto buffer = make_shared<Buffer>(pkcs8, len);
187 PublicKey::rsaEncrypt(span<const uint8_t> plainText)
const
189 detail::EvpPkeyCtx ctx(m_impl->key);
191 if (EVP_PKEY_encrypt_init(ctx) <= 0)
192 NDN_THROW(Error(
"Failed to initialize encryption context"));
194 if (EVP_PKEY_CTX_set_rsa_padding(ctx, RSA_PKCS1_OAEP_PADDING) <= 0)
195 NDN_THROW(Error(
"Failed to set padding"));
199 if (EVP_PKEY_encrypt(ctx,
nullptr, &outlen, plainText.data(), plainText.size()) <= 0)
200 NDN_THROW(Error(
"Failed to estimate output length"));
202 auto out = make_shared<Buffer>(outlen);
203 if (EVP_PKEY_encrypt(ctx, out->data(), &outlen, plainText.data(), plainText.size()) <= 0)
204 NDN_THROW(Error(
"Failed to encrypt plaintext"));
An output stream that writes to a Buffer.
shared_ptr< Buffer > buf()
Return a 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)