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")); \
48 class PublicKey::Impl : noncopyable
66 : m_impl(make_unique<Impl>())
78 switch (detail::getEvpPkeyType(m_impl->key)) {
94 return static_cast<size_t>(EVP_PKEY_bits(m_impl->key));
105 auto ptr = buf.data();
106 if (d2i_PUBKEY(&m_impl->key, &ptr,
static_cast<long>(buf.size())) ==
nullptr)
151 int keyType = detail::getEvpPkeyType(m_impl->key);
156 return rsaEncrypt(plainText);
163 PublicKey::getEvpPkey()
const
169 PublicKey::toPkcs8()
const
173 uint8_t* pkcs8 =
nullptr;
174 int len = i2d_PUBKEY(m_impl->key, &pkcs8);
176 NDN_THROW(Error(
"Cannot convert key to PKCS #8 format"));
178 auto buffer = make_shared<Buffer>(pkcs8, len);
185 PublicKey::rsaEncrypt(span<const uint8_t> plainText)
const
187 detail::EvpPkeyCtx ctx(m_impl->key);
189 if (EVP_PKEY_encrypt_init(ctx) <= 0)
190 NDN_THROW(Error(
"Failed to initialize encryption context"));
192 if (EVP_PKEY_CTX_set_rsa_padding(ctx, RSA_PKCS1_OAEP_PADDING) <= 0)
193 NDN_THROW(Error(
"Failed to set padding"));
197 if (EVP_PKEY_encrypt(ctx,
nullptr, &outlen, plainText.data(), plainText.size()) <= 0)
198 NDN_THROW(Error(
"Failed to estimate output length"));
200 auto out = make_shared<Buffer>(outlen);
201 if (EVP_PKEY_encrypt(ctx, out->data(), &outlen, plainText.data(), plainText.size()) <= 0)
202 NDN_THROW(Error(
"Failed to encrypt plaintext"));
An output stream that writes to a Buffer.
std::shared_ptr< Buffer > buf()
Return a shared pointer to the underlying buffer.
std::string to_string(const errinfo_stacktrace &x)
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.
std::shared_ptr< const Buffer > ConstBufferPtr
#define ENSURE_PUBLIC_KEY_NOT_LOADED(key)
#define ENSURE_PUBLIC_KEY_LOADED(key)