Search code examples
c++cencryptionopensslrsa

How to do RSA public key encryption using OpenSSL EVP routines?


I am using the EVP high-level functions in OpenSSL. I haven't found any examples online showing how to use these functions (e.g. EVP_EncryptInit_ex(), EVP_EncryptUpdate(), EVP_EncryptFinal_ex()) to encrypt data using an RSA public key. Specifically, I do not see a EVP_CIPHER type that matches RSA, similar to what you see for AES like: const EVP_CIPHER *EVP_aes_128_cbc(void); in evp.h. I think one for RSA is required to initialize EVP for encryption using that method.

Can anyone help me understand how to use an RSA existing key to encrypt data using OpenSSL's EVP routines? Examples would be extremely helpful.


Solution

  • To do asymmetric encryption you need to use different EVP routines than for symmetric crypto. In particular see the EVP_PKEY_encrypt() function. The man page is here, and it contains an example.

    https://www.openssl.org/docs/man3.0/man3/EVP_PKEY_encrypt.html

    Edit:

    Newer versions of OpenSSL also have a demo file showing RSA encryption:

    https://github.com/openssl/openssl/blob/master/demos/encrypt/rsa_encrypt.c