OpenSSL笔记-生成RSA公私密钥以PEM格式到char*中(非保存为文件)

x33g5p2x  于2022-07-11 转载在 其他  
字(1.3k)|赞(0)|评价(0)|浏览(420)

OpenSSL笔记-生成RSA公私密钥以PEM格式到char*中(非保存为文件)

不多说,直接上关键代码:

int ret = 0;
    RSA *r = RSA_new();
    BIGNUM *bne = BN_new();
    int bits = 2048;
    unsigned long e = RSA_F4;

    bne = BN_new();
    ret = BN_set_word(bne, e);

    if(!ret){

        qDebug() << "BN_set_word() error";
        RSA_free(r);
        BN_free(bne);
        return;
    }

    ret = RSA_generate_key_ex(r, bits, bne, nullptr);
    if(!ret){

        qDebug() << "RSA_generate_key() error";
        RSA_free(r);
        BN_free(bne);
        return;
    }

    BIO *bp_public = BIO_new(BIO_s_mem());;
    BIO *bp_private = BIO_new(BIO_s_mem());
    ret =PEM_write_bio_RSAPrivateKey(bp_private, r, NULL, NULL, 0, NULL, NULL);
    if(!ret){

        qDebug() << "PEM_write_bio_RSAPrivateKey() error";
        BIO_free_all(bp_private);
        RSA_free(r);
        BN_free(bne);
        return;
    }

    ret = PEM_write_bio_RSAPublicKey(bp_public, r);
    if(!ret){

        qDebug() << "PEM_write_bio_RSAPublicKey() error";
        BIO_free_all(bp_public);
        BIO_free_all(bp_private);
        RSA_free(r);
        BN_free(bne);
        return;
    }

    //存储到Map中
    size_t nPriKeyLen = BIO_pending(bp_private);
    size_t nPubKeyLen = BIO_pending(bp_public);

    //密钥对读取到字符串
    char* pPriKey = new char[nPriKeyLen];
    char* pPubKey = new char[nPubKeyLen];
    BIO_read(bp_private, pPriKey, nPriKeyLen);
    BIO_read(bp_public, pPubKey, nPubKeyLen);

    RSAStu rsaStu;
    rsaStu.privateKey = pPriKey;
    rsaStu.publicKey = pPubKey;

这个RSAStu是我自己写的结构体。

打印下:

这里包含的头文件为:

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

相关文章