title: How to encrypt a string using OpenSSL C library and a public key file?
body: <p>What is the recommended way of encrypting a short <code>std::string</code> into another <code>std::string</code> using the <code>openssl</code> <a href="https://github.com/openssl/openssl" rel="nofollow noreferrer"><strong>C library</strong></a> (<em>not</em> the command-line tool of the same name) using a public keyfile, and knowing the algorithm? (in this case the string is no larger than ~100 bytes, keyfile is in <code>.pem</code> format, algorithm can be any asymmetric one like RSA/ECDSA/etc).</p>
  <p>I am looking to write a function with an interface like so: <code>bool EncryptString(const std::string&amp; InStr, const std::string&amp; InPublicKey, std::string&amp; OutString)</code>.</p>
  <p>Looking through documentation it seems like <a href="https://www.openssl.org/docs/man1.1.1/man3/EVP_PKEY_encrypt.html" rel="nofollow noreferrer"><code>EVP_PKEY_encrypt</code></a> is the function to use, which requires an <code>EVP_PKEY_CTX *ctx</code> variable. My assumption is, this variable should be initialized with <a href="https://www.openssl.org/docs/man1.1.1/man3/EVP_PKEY_CTX_new.html" rel="nofollow noreferrer"><code>EVP_PKEY_CTX_new</code></a>, which in turn requires an <code>EVP_PKEY *pkey</code> and an <code>ENGINE *e</code>. Those I don't know how to initialize, and searching through the documentation leaves me very confused.</p>
  <p>Maybe these functions are not the easiest approach, I am not familiar with this library at all and have no cryptography knowledge. I simply care about a black-box way of converting a string to an encrypted string.</p>
  <p>Thank you</p>