You are now getting to a point where you know you want to get a copy of an EVP_PKEY for one reason or another, not that it matters much why, you just need it.
So you start looking for a way to duplicate it, there has to be a function for it, right? You come across EVP_PKEY_CTX_dup, so you make the assumption that EVP_PKEY_dup should probably exist too ... well you'd be wrong. You come across this message on the OpenSSL mailling list: http://www.mail-archive.com/[email protected]/msg17608.html and the next follow-up says to just up the reference count, or RSA_dup() and copy it into the new EVP_PKEY ... except RSA_dup() doesn't exist either.
No real solutions come out of that email thread. No deep copies seem to be possible, well until you simply consider converting it from an EVP_PKEY format to PEM/DER and then back to an EVP_PKEY.
So, in that case all that is left is to encode it to PEM/DER and then decode it from PEM/DER.
// Create new memory BIO
BIO* tbio = BIO_new(BIO_s_