gpt4 book ai didi

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

转载 作者:知者 更新时间:2024-03-12 20:03:21 26 4
gpt4 key购买 nike

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>

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com