且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何使用 OpenSSL 生成 RSA 私钥?

更新时间:2023-01-18 10:37:53

#include <openssl/rsa.h>
#include <openssl/pem.h>

const int kBits = 1024;
const int kExp = 3;

int keylen;
char *pem_key;

RSA *rsa = RSA_generate_key(kBits, kExp, 0, 0);

/* To get the C-string PEM form: */
BIO *bio = BIO_new(BIO_s_mem());
PEM_write_bio_RSAPrivateKey(bio, rsa, NULL, NULL, 0, NULL, NULL);

keylen = BIO_pending(bio);
pem_key = calloc(keylen+1, 1); /* Null-terminate */
BIO_read(bio, pem_key, keylen);

printf("%s", pem_key);

BIO_free_all(bio);
RSA_free(rsa);
free(pem_key);