If you don't really need to duplicate the key, you can just increment its reference count, like this:
CRYPTO_add(&your_evp_pkey->references, 1, CRYPTO_LOCK_EVP_PKEY);
Otherwise, a similar (almost identical) approach to what you suggested would be the following:
int pkey_rsa_dup(EVP_PKEY *dst_pkey, EVP_PKEY *src_key) {
// Validate underlying key type - Only allow a RSA key
if (src_key->type != EVP_PKEY_RSA)
return -1;
RSA *rsa = EVP_PKEY_get1_RSA(src_key); // Get the underlying RSA key
RSA *dup_rsa = RSAPrivateKey_dup(rsa); // Duplicate the RSA key
RSA_free(rsa); // Decrement reference count
EVP_PKEY_set1_RSA(dst_pkey, dup_rsa); // Set the underlying RSA key in dst_pkey
// EVP_PKEY_set1_RSA also adjusts the other members in dst_pkey
return 0;
}
Reference: Re: How to duplicate an EVP_PKEY -> As @X-Istence says below, the RSA_dup
method suggested in this reference thread doesn't exist in OpenSSL (at least until the date of this update).