How can we copy the EVP_PKEY that includes the RSA key?

I found the function EVP_PKEY_copy_parameters , which can copy EVP_PKEY . But some documents about this feature say that it can only be used for DSA / ECC algorithms. The official documentation (from openssl.org ) does not mention whether the function can be used for RSA EVP_PKEY.

Another implementation for EVP_PKEY (which contains the RSA key) may be as follows:

 EVP_PKEY_assign_RSA(RSAPrivateKey_dup(EVP_PKEY_get1_RSA(pkey))); 

Do you have any suggestions?

+6
source share
2 answers

If you donโ€™t really need to duplicate the key, you can simply increase the reference count, for example:

 CRYPTO_add(&your_evp_pkey->references, 1, CRYPTO_LOCK_EVP_PKEY); 

Otherwise, a similar (almost identical) approach to what you suggested would be as follows:

 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; } 

Link: Re: How to duplicate EVP_PKEY โ†’ As shown below, X-Istence, the RSA_dup method proposed in this link stream does not exist in OpenSSL (at least until the date of this update).

+6
source

In OpenSSL 1.0.0d, EVP_PKEY_copy_parameters should work. However, judging by the implementation, public parameters are simply copied:

 static int pkey_rsa_copy(EVP_PKEY_CTX *dst, EVP_PKEY_CTX *src) { RSA_PKEY_CTX *dctx, *sctx; if (!pkey_rsa_init(dst)) return 0; sctx = src->data; dctx = dst->data; dctx->nbits = sctx->nbits; if (sctx->pub_exp) { dctx->pub_exp = BN_dup(sctx->pub_exp); if (!dctx->pub_exp) return 0; } dctx->pad_mode = sctx->pad_mode; dctx->md = sctx->md; return 1; } 

Besides the jweyrich solution, another simple method is first i2d_RSAPrivateKey your RSA key, then d2i_RSAPrivateKey again - there is your copy :)

+2
source

Source: https://habr.com/ru/post/891180/


All Articles