使用libopenssl从私钥转储公钥

Dumping public key from private using libopenssl

本文关键字:转储 公钥 私钥 libopenssl 使用      更新时间:2023-10-16

假设我想在我的c++应用程序中有一个类似openssl命令的代码。

openssl rsa -in private.pem -pubout -outform der -out ./out.pub

我该怎么做呢?

我在github上寻找一个样本,并提出了以下方案。

key  = PEM_read_bio_RSAPrivateKey(bio, NULL, 0, NULL);
len = i2d_RSAPublicKey(key, &bufp);

它返回的值与我从命令行工具获得的值不同。我想没有从私钥到公钥的转换,它只是保存了私钥。谁能告诉我使用openssl lib从私有中获取pub密钥的正确方法?我也非常感谢任何关于openssl的pubpriv密钥示例的链接。

最后我在openssl内部找到了合适的源代码。下面是

期间发生的事情

openssl rsa -in private。/out.pub

我从原始代码中删除了许多检查,使其更小。

#include <openssl/pem.h>
#include <openssl/x509.h>
EVP_PKEY *load_key(const char *file)
{
    BIO *key=NULL;
    EVP_PKEY *pkey=NULL;
    key=BIO_new(BIO_s_file());
    BIO_read_filename(key,file);
    pkey=PEM_read_bio_PrivateKey(key,NULL,NULL,NULL);
    return pkey;
}
int _tmain(int argc, _TCHAR* argv[])
{
    BIO *out=NULL;
    out=BIO_new(BIO_s_file());
    EVP_PKEY    *pkey;
    RSA *rsa=NULL;
    char *infile = path_to_pem;
    char *outfile = path_to_der;
    pkey = load_key(infile);
    if (pkey != NULL)
        rsa = EVP_PKEY_get1_RSA(pkey);
    EVP_PKEY_free(pkey);
    BIO_write_filename(out,outfile);
    i2d_RSA_PUBKEY_bio(out,rsa);
}