int save_public_key_from_file(const char* filename,RSA *key) {
BIO* bio = BIO_new_file(filename, "w");
if (!bio) return NULL;
int ret = PEM_write_bio_RSA_PUBKEY(bio, key);
BIO_free(bio);
return ret;
}
int save_private_key_from_file(const char* filename, RSA* key) {
BIO* bio = BIO_new_file(filename, "w");
if (!bio) return NULL;
int ret = PEM_write_bio_RSAPrivateKey(bio, key, NULL, NULL, 0, NULL, NULL);
BIO_free(bio);
return ret;
}
int openssl_rsa() {
// 初始化 OpenSSL
OpenSSL_add_all_algorithms();
ERR_load_crypto_strings();
RSA* rsa_key = NULL;
rsa_key=RSA_generate_key(2048, RSA_F4,NULL,NULL);
int ret=save_public_key_from_file("test_pub.pem",rsa_key);
printf("ret:%d\r\n",ret);
ret = save_private_key_from_file("test_pri.pem", rsa_key);
printf("ret:%d\r\n", ret);
// 清理
RSA_free(rsa_key);
EVP_cleanup();
CRYPTO_cleanup_all_ex_data();
ERR_free_strings();
return 0;
}