生成 RSA 密钥
为了生成 RSA 密钥,必须首先使用 EVP_PKEY_new 分配 EVP_PKEY :
EVP_PKEY *pkey;
pkey = EVP_PKEY_new();
还需要密钥的指数,这将需要使用 BN_new 分配 BIGNUM 然后使用 BN_set_word 进行分配 :
BIGNUM *bn;
bn = BN_new();
BN_set_word(bn, RSA_F4);
要生成密钥,请使用 RSA_new 创建一个新的 RSA 并调用 RSA_generate_key_ex :
RSA *rsa;
rsa = RSA_new();
RSA_generate_key_ex(
rsa, /* pointer to the RSA structure */
2048, /* number of bits for the key - 2048 is a good value */
bn, /* exponent allocated earlier */
NULL, /* callback - can be NULL if progress isn't needed */
);
要将新生成的密钥分配给 EVP_PKEY 结构,请调用 EVP_PKEY_assign_RSA :
EVP_PKEY_assign_RSA(pkey, rsa);
当释放 EVP_PKEY 结构时,RSA 结构将自动释放。这是通过 EVP_PKEY_free 完成的 :
EVP_PKEY_free(pkey);