我们如何复制包含RSA密钥的EVP_PKEY?

upi*_*ing 6 c openssl x509 private-key

我找到了EVP_PKEY_copy_parameters可以复制的功能EVP_PKEY.但有关此功能的一些文档称它只能用于DSA/ECC算法.官方文档(来自openssl.org)未提及该函数是否可用于RSA EVP_PKEY.

EVP_PKEY(包含RSA密钥)的另一个实现可能是这样的:

EVP_PKEY_assign_RSA(RSAPrivateKey_dup(EVP_PKEY_get1_RSA(pkey)));
Run Code Online (Sandbox Code Playgroud)

你有什么建议吗?

jwe*_*ich 6

如果你真的不需要复制密钥,你可以增加它的引用计数,如下所示:

CRYPTO_add(&your_evp_pkey->references, 1, CRYPTO_LOCK_EVP_PKEY);
Run Code Online (Sandbox Code Playgroud)

否则,与您建议的方法类似(几乎相同)的方法如下:

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;
}
Run Code Online (Sandbox Code Playgroud)

参考:Re:如何复制EVP_PKEY - >正如@X-Istence所述,RSA_dupOpenSSL中不存在此参考线程中建议的方法(至少在此更新日期之前).